Introduction
In late 2015 Google Brain team released a Machine learning framework publicly Called as TensorFlow (without .js). This framework was focused on effectively solving ML problems for Google using python. After that very soon Google Realized - it would be beneficial if they put this framework to IoT and mobile devices which has limited computing powers and that required and adaption of TensorFlow which is known as TensorFlow Lite. After this successful adoption, pushing TensorFlow to other ideal languages gets clear path.
TensorFlow.js
Just after couple of years, in early 2018 Google launched their Machine learning framework Built with JavaScript called as TensorFlow.js. This opens door for Web developers to Use AIML Directly in browsers or server using Nodejs. That time “Python only” chains was removed from popular AI frameworks. Now we can run AIML models directly in browsers using JS.
Its important to note that TensorFlow models are directed acyclic graphs (DAGs), Means its language independent structure that let you train a model in one language and use it in another.
Tensor
Tensors are the collection of data in structured type. For any programming language it not big task to convert any data to the numbers But it might be a new concept to let your decide how data will ultimately formed.
A machine can’t understand human language directly — it only understands numbers. So the text must be converted into numbers first so the model can properly read and process it.
A tensor, as defined mathematically, is simply a structured set of values of any dimension.
Example
const vector = tf.tensor([1, 2, 3, 4]);
console.log(vector);
//output
Tensor
[1, 2, 3, 4]Benefits of building AI models in Browser.
No server needed – Without having server dependencies you can run AI Model directly in Browser (user device).
Better privacy - While running AI model on browser, data stays on local system of user.
Low latency – For producing results it doesnt take much time as Model runs in local system
Cost-effective – No backend compute costs.
Cross-platform – Works anywhere with a browser.
Offline support – Models can run even without internet.(Once model gets load in your system)
Easy deployment – Just load the model via JavaScript. (No extra efforts or items required for computation)
Types of Machine Learning.
While learning AIML you should Have an idea about in how many ways we can train a Machine. there are 4 type of Machine Learning we can use to trained AI models or Machine. and they are they are -
Supervised Learning
It simply means we have labeled data to train a machine. We provide answers for each question so that the machine can provide a suitable answer for your query by following the data on which it is trained.
Example -
const apps = [
‘whatsApp’,
‘SnapChat’,
‘FaceBook’,
‘Artai’,
]
const Features = [
‘Modern UI’,
’Clear Video calls’,
‘Emojis in Chat’,
‘End to end encryption’
]Unsupervised Learning
Unsupervised learning does not require labeled data (no answer key). The model automatically finds patterns and creates groups based on similarities.
How it works ?
It creates its own logic based on patterns in the data. Then, when new data comes, it decides which group it fits into.
Example
You give the model 100 website URLs.
The model scans all websites and it finds patterns (traffic, speed, content, etc.).
It groups them into:
High traffic
Medium traffic
Low traffic
(No labels were given — the model created these groups by itself.)
Later, if you provide a new website, the model:
analyzes it
finds the pattern
places it in the closest matching group
Semi-supervised Learning
Occasionally, we work with partially labeled data, which comprises a combination of a
small amount of labeled data (with answers) and a
large amount of unlabeled data (without answers).
AI models utilize both types of data to enhance their accuracy and make more precise predictions compared to unsupervised and supervised data.
For instance, consider a product review system. In most cases, it is not guaranteed that you will obtain proper labeled data (positive, negative, or neutral reviews).
If the data is not classified, this type of learning will be employed to categorize the data based on the reviews’ types.
Semi-supervised learning can be beneficial in various applications, including sentiment analysis, review categorization, topic discovery, and spam filtering.
Reinforcement Learning
Reinforcement learning is a type of learning method mainly used in games. It works based on the actions taken by the system, using trial and error, as well as rewards. If the result made by the machine is good, it gets a reward for that result. The AI model learns through rewards and punishments, depending on its actions.
The learning process includes the following steps:
Take Action: The agent does an action in the environment.
Receive Feedback: The agent gets a reward (or penalty) because of its action.
Update Strategy: The agent changes its plan or policy to try to get the most rewards over time, instead of just focusing on immediate rewards.
The goal of reinforcement learning is to get the most total rewards over time, instead of just looking for immediate rewards.
How TesorFlow.js Model gets trained?
When we start studying AIML concepts, this question arises: How do these AI models get trained? Where are they stored? Is it actual training data or something else? How do they produce output? I had the same question in my mind when I started learning. So let’s discuss briefly how we can train an AIModel in TensorFlow.js and what are the things it stores for producing answers to your questions?
Storage -
When an AI model is trained, it does not store the actual training data, but a trained model stores everything in weights and biases.
Weights - numbers the model learns
Biases - small helper values
Model architecture - layers, connections
And numbers are the knowledge that the model learns. This is the process of model training.
But where are these weights stored?
If the training happens on a browser - Chrome/Safari/FireFox
For training on a browser, models can use either IndexedDB or browser storage.
IndexedDB -
it’s a small database inside your browser that lets websites store data locally on your device (even large files).
Websites can store models, images, settings, user data, etc., in a small database inside Chrome/Firefox/Safari, which works offline and allows TensorFlow.js to save trained models for instant loading next time.
For example - when you train a model in the browser, it gets stored in your browser, not on a server.
await model.save(‘indexeddb://your-model’);Consider this IndexedDB as a local storage box in your browser where your ML model can live permanently. Even if you shut down your browser or your computer.
If the training happens on a server - Node.js
TensorFlow.js models are stored in .json and .bin files. After training, you can load the model anywhere. During prediction, these files are loaded into memory.
Example
Suppose the model learns:
weight = 3
bias = 10
These two numbers are the model’s knowledge.
How prediction works with these values?
If size = 5:
price = 3 × 5 + 10
price = 25
The model used:
weight = 3
bias = 10
These numbers are what get stored inside the trained model.
Real ML Models
Real models don’t have just 1 weight — they can have thousands to millions of weights, like:
weights = [0.34, -0.12, 1.45, 0.89, …]
biases = [0.54, -0.21, …]
But the idea is the same. Weights decide how strong each input is, and bias shifts the output up or down. In this way, these weights and biases are stored in the formats we discussed above.
Installation of NPM packages or script
Using NPM Package -
Most suitable for every user
npm i @tensorflow/tfjsIf you’re using a Windows or Linux system with a GPU, like CUDA or NVIDIA, you can take advantage of this more robust library for training models on the server side. However, keep in mind that TensorFlow for Mac with the M1 or M2 + chipset isn’t currently supported. Remember to check the compatibility of TensorFlow with your hardware before you begin.
npm i @tensorflow/tfjs-nodeUsing Script -
If you are not using nodeJS the simply add script tag to html document. This is another way you can use include TensorFlow.js in our project.
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"> </script>
</head>
<body>
<h4>Tiny TFJS example<hr/></h4>
<div id="micro-out-div">Training...</div>
<script src="./index.js"> </script>
</body>
</html>While using script in html document You will have to make sure it’s loaded properly before starting execution.
Practical Implementation
Let’s create a straightforward recommendation system using TensorFlow.js.
import * as tf from '@tensorflow/tfjs';
// Users
const users = ['Alex', 'John', 'Mia'];
// Movies
const movies = ['Action', 'Comedy', 'Drama', 'Sci-Fi'];
// User Ratings Matrix (rows = users, columns = movies)
const userRatings = tf.tensor([
[5, 3, 0, 4], // Alex
[4, 0, 0, 3], // John
[0, 4, 5, 0] // Mia
]);
// Movie Features (genre flags)
const movieFeatures = tf.tensor([
[1, 0, 0], // Action
[0, 1, 0], // Comedy
[0, 1, 1], // Drama
[1, 0, 1] // Sci-Fi
]);
Calculate User Preferences
Matrix multiplication helps find what each user likes.
const userPreferences = tf.matMul(userRatings, movieFeatures);
userPreferences.print();
// Output
Tensor
[[9, 3, 4],
[7, 0, 3],
[0, 9, 9]]Meaning - Alex enjoys Action movies, which he rates a 9. John has a preference for both Action and Sci-Fi films. Mia, on the other hand, appreciates a mix of Comedy and Drama.
Recommend Movies
Pick the movie with highest similarity to user preference.
function recommendMovie(userIndex) {
const userPref = userPreferences.slice([userIndex, 0], [1, -1]);
const scores = tf.matMul(movieFeatures, userPref.transpose());
scores.print();
const best = scores.argMax().dataSync()[0];
return movies[best];
}
console.log('Recommendation for Alex:', recommendMovie(0));Finally
I understand that learning AIML can be a bit confusing at first. However, with this article, I hope you gain a decent understanding of how to create an AIML model and the essential things you need to learn. In the future, I will upload a few more in-depth articles with practical examples, so don’t forget to subscribe to Webredo. Thank you for reading this article.
LOADING...

