JavaScript Machine Learning: Building ML Models in the Browser

Machine Learning (ML) has revolutionized various industries, enabling computers to learn and make predictions based on patterns and data. Traditionally, ML models were built and executed on servers or high-performance machines. However, with the advancements in web technologies, it is now possible to build and deploy ML models directly in the browser using JavaScript.

In this article, we will explore the exciting world of JavaScript Machine Learning and learn how to build ML models that can run in the browser.

Understanding Machine Learning

Machine Learning is a subset of Artificial Intelligence (AI) that focuses on creating models capable of learning from data and making predictions or decisions. There are primarily two types of ML: supervised learning and unsupervised learning.

Supervised learning involves training a model on labelled data, where the input features and corresponding output values are known. The model learns patterns from the labelled data to make predictions on new, unseen data.

Unsupervised learning, on the other hand, deals with unlabeled data. The model discovers hidden patterns and structures within the data without any predefined labels.

JavaScript Machine Learning Libraries

To get started with JavaScript Machine Learning, follow these steps −

Step 1: Install Node.js

Node.js is a JavaScript runtime environment that allows us to run JavaScript code outside of a web browser. It provides the necessary tools and libraries to work with TensorFlow.js.

Step 2: Set Up a Project

Once Node.js is installed, open your preferred code editor and create a new directory for your ML project. Navigate to the project directory using the command line or terminal.

Step 3: Initialise a Node.js Project

In the command line or terminal, run the following command to initialise a new Node.js project −

npm init -y

This command creates a new package.json file, which is used to manage project dependencies and configurations.

Step 4: Install TensorFlow.js

To install TensorFlow.js, run the following command in the command line or terminal −

npm install @tensorflow/tfjs

Step 5: Start Building ML Models

Now that your project is set up and TensorFlow.js is installed, you are ready to start building ML models in the browser. You can create a new JavaScript file, import TensorFlow.js, and use its APIs to define, train, and make predictions with ML models.

Let's dive into some code examples to understand how to work with TensorFlow.js and build ML models in JavaScript.

Example 1: Linear Regression

Linear regression is a supervised learning algorithm used for predicting continuous output values based on input features.

Let's see how we can implement linear regression using TensorFlow.js.

// Import TensorFlow.js library
import * as tf from '@tensorflow/tfjs';

// Define input features and output values
const inputFeatures = tf.tensor2d([[1], [2], [3], [4], [5]], [5, 1]);
const outputValues = tf.tensor2d([[2], [4], [6], [8], [10]], [5, 1]);

// Define the model architecture
const model = tf.sequential();
model.add(tf.layers.dense({ units: 1, inputShape: [1] }));

// Compile the model
model.compile({ optimizer: 'sgd', loss: 'meanSquaredError' });

// Train the model, outputValues, { epochs: 100 }).then(() => {
   // Make predictions
   const predictions = model.predict(inputFeatures);

   // Print predictions


In this example, we start by importing the TensorFlow.js library. Then, we define our input features and output values as tensors. Next, we create a sequential model and add a dense layer with one unit. We compile the model with the 'sgd' optimizer and 'meanSquaredError' loss function. Finally, we train the model for 100 epochs and make predictions on the input features. The predicted output values are printed to the console.


   [4.124609 ],

Example 2: Sentimental Analysis

Sentiment analysis is a popular application of ML that involves analyzing text data to determine the sentiment or emotional tone expressed in the text. We can use TensorFlow.js to build a sentiment analysis model that predicts whether a given text has a positive or negative sentiment.

Consider the code shown below.

// Import TensorFlow.js library
import * as tf from '@tensorflow/tfjs';
import '@tensorflow/tfjs-node'; // Required for Node.js environment

// Define training data
const trainingData = [
   { text: 'I love this product!', sentiment: 'positive' },
   { text: 'This is a terrible experience.', sentiment: 'negative' },
   { text: 'The movie was amazing!', sentiment: 'positive' },
   // Add more training data...

// Prepare training data
const texts = => item.text);
const labels = => (item.sentiment === 'positive' ? 1 : 0));

// Tokenize and preprocess the texts
const tokenizedTexts = => text.toLowerCase().split(' '));
const wordIndex = new Map();
let currentIndex = 1;
const sequences = => {
   return => {
      if (!wordIndex.has(token)) {
         wordIndex.set(token, currentIndex);
      return wordIndex.get(token);

// Pad sequences
const maxLength = sequences.reduce((max, seq) => Math.max(max, seq.length), 0);
const paddedSequences = => {
   if (seq.length < maxLength) {
      return seq.concat(new Array(maxLength - seq.length).fill(0));
   return seq;

// Convert to tensors
const paddedSequencesTensor = tf.tensor2d(paddedSequences);
const labelsTensor = tf.tensor1d(labels);

// Define the model architecture
const model = tf.sequential();
model.add(tf.layers.embedding({ inputDim: currentIndex, outputDim: 16, inputLength: maxLength }));
model.add(tf.layers.dense({ units: 1, activation: 'sigmoid' }));

// Compile the model
model.compile({ optimizer: 'adam', loss: 'binaryCrossentropy', metrics: ['accuracy'] });

// Train the model, labelsTensor, { epochs: 10 }).then(() => {
   // Make predictions
   const testText = 'This product exceeded my expectations!';
   const testTokens = testText.toLowerCase().split(' ');
   const testSequence = => {
      if (wordIndex.has(token)) {
         return wordIndex.get(token);
      return 0;
   const paddedTestSequence = testSequence.length < maxLength ? testSequence.concat(new Array(maxLength - testSequence.length).fill(0)) : testSequence;
   const testSequenceTensor = tf.tensor2d([paddedTestSequence]);
   const prediction = model.predict(testSequenceTensor);
   const sentiment = prediction.dataSync()[0] > 0.5 ?  'positive' : 'negative';

   // Print the sentiment prediction
   console.log(`The sentiment of "${testText}" is ${sentiment}.`);


Epoch 1 / 10
eta=0.0 ========================================================================> 
14ms 4675us/step - acc=0.00 loss=0.708 
Epoch 2 / 10
eta=0.0 ========================================================================> 
4ms 1428us/step - acc=0.667 loss=0.703 
Epoch 3 / 10
eta=0.0 ========================================================================> 
5ms 1733us/step - acc=0.667 loss=0.697 
Epoch 4 / 10
eta=0.0 ========================================================================> 
4ms 1419us/step - acc=0.667 loss=0.692 
Epoch 5 / 10
eta=0.0 ========================================================================> 
6ms 1944us/step - acc=0.667 loss=0.686 
Epoch 6 / 10
eta=0.0 ========================================================================> 
5ms 1558us/step - acc=0.667 loss=0.681 
Epoch 7 / 10
eta=0.0 ========================================================================> 
5ms 1513us/step - acc=0.667 loss=0.675 
Epoch 8 / 10
eta=0.0 ========================================================================> 
3ms 1057us/step - acc=1.00 loss=0.670 
Epoch 9 / 10
eta=0.0 ========================================================================> 
5ms 1745us/step - acc=1.00 loss=0.665 
Epoch 10 / 10
eta=0.0 ========================================================================> 
4ms 1439us/step - acc=1.00 loss=0.659 
The sentiment of "This product exceeded my expectations!" is positive.

Updated on: 25-Jul-2023


Kickstart Your Career

Get certified by completing the course

Get Started