Machine Learning: TensorFlow in JavaScript


If we explore the technology around us, we would see that we are surrounded by many machine learning or deep learning powered devices or services—be it Google search, SIRI, Alexa etc. I will talk about what TensorFlow is, but first let us have a look at how Machine Learning is different from the conventional programming or methods to solve problems.

Conventional Programming vs. Machine Learning

  • In conventional programming, you specify the inputs (data) and the rules, and the conventional programming block gives you the answer. For example, suppose there are two numbers: a=10 and b=20, which we want to add. We define the rule of addition as follows: a + b. The plus sign is the rule. Once we pass this information through the conventional programming block, we get the answer, which is 30. This is the simple example. As the problem gets complex, the rules also become complex.
  • In Machine learning, instead of specifying the rules, we provide the Machine learning block the answers and the input data. What Machine learning block gives us are the rules. We don’t care how complex the rules may become. For example, think of a Machine Learning block a machine that prints certain rules after processing or analysing the data and the respective answers to the items in the input data. Suppose we provide the Machine learning block some pictures of cats and dogs with their labels, the machine learning block will learn the features (or rules according to the analogy given in this section) of cats and dogs. If, after the learning process, you provide the picture of cat, the ML block will predict whether it is a cat or a dog.

Now that we have discussed the difference between the conventional programming and Machine learning, it’s time to dive deep into the discussion of TensorFlow.


In order to make Machine Learning or Deep Learning models, we use difference libraries (some are open-source and some are proprietary). In this article, we will look at the open source library called TensorFlow.js. Back in 2015, Google made the TensorFlow library an open-source for the developers, who want to work in the field of Machine Learning or Deep learning. However, that library was available in Python (although its core is written in C++). Recently, Google released its JavaScript wrapper with the name of TensorFlow.js. It can be divided primarily into two APIs:

  • Core API (a low level API)
  • Layers API (a high level API utilizing Keras) In this article, our focus will be on the Core API of TensorFlow.js.

Before exploring the world of Core API, ask yourself the following question: what exactly is a tensor?

A Tensor

In simple words, a tensor is a mathematical object that can represent numbers into n-dimensions. The easiest way to understand it is by looking at the following example:

  • If we have only one number, let us say 5, we can call it a rank-0 tensor, which is also called a scalar.
  • If we have two numbers, let us say 5 and 6, we can arrange it into one-dimensional tensor as [5,6]. It is a rank-1 tensor, which means its shape has only one value. In this case its shape is 2 (shape = [2]) since there are two elements in a tensor.
  • Let us say we have the same two numbers as above, which are 5 and 6, and want to convert them into two-dimensional tensor. It is really easy to express them into two-dimensional tensor by defining its rank equals to 2. The tensor would look like this: [[5], [6]]. As you can see, now we have 2 rows and 1 column in this case. The shape of the tensor would be: shape = [2,1].
  • Likewise, you can define the n-dimensional tensor. For example, the shape of the three-dimensional tensor would look like the following: shape = [2,3,1]. It means we have two 3x1 matrices.

Importing TensorFlow.js

In order to use the TensorFlow.js library, we first need to download or specific its JavaScript file. In this article, we are going to use CDN (content delivery network). Add the following line of code in your HTML file:

  <script src=""> </script>

The HTML file would look like this:

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src=""> </script>
    <script src=”index.js”></script>

We have also added our own custom JavaScript (index.js) file by using the following line of script:

<script src=”index.js”></script>

Now in order to check whether the TensorFlow.js is imported in code or not, copy and paste the following lines of code into index.js file and check the console:

let scalarTensor = tf.tensor(5);

If you see the output to be Tensor 5, you are good to go! If you see some kind of error, comment down below (I shall sort it out).

Alright! Now that the tensorflow.js library is up and running, we can make some different dimensional tensor first.

(1) Scalar Tensor

The scalar tensor has no shape (like the code given above for checking).

(2) One-Dimensional Tensor

In one-dimensional tensor case, the shape contains only one value and that value is equal to number of elements present in the tensor (as shown below):

let oneDimensionalTensor = tf.tensor([2,3,4,5], shape=[4]);

The output would be: Tensor [2, 3, 4, 5]

(3) Two-Dimensional Tensor

In two-dimensional tensor case, the shape contains two values, and those values are the number of rows and number of columns. The example is as follows:

let twoDimensionalTensor = tf.tensor([1,2,3,4,5,6], shape=[3,2]);

The output would be: Tensor [[1, 2], [3, 4], [5, 6]]

As you can see, we have passed the one-dimensional array with a two-dimensional shape, the TensorFlow.js changes its form and make it two dimensional array.

Addition using Tensors

Addition and Multiplication are two operations, which are extensively used in the Machine Learning or Deep learning models. The following example shows the addition of two tensor (make sure that the dimensions or shapes of both the tensors are same; they must be incompliance with the Matrix mathematics rules):

let twoDimensionalTensor = tf.tensor([1,2,3,4], shape=[2,2], dtype="float32");
let addition = twoDimensionalTensor.add(twoDimensionalTensor);

You should expect the element-wise addition. The output is as follows: Tensor [[2, 4], [6, 8]] (as expected)

Multiplication using Tensors

We can multiple two tensors (element-wise) by using the following code:

let twoDimensionalTensor = tf.tensor([1,2,3,4], shape=[2,2], dtype="float32");
let multiplcation = twoDimensionalTensor.mul(twoDimensionalTensor);

The output is: Tensor [[1, 4 ], [9, 16]] (as expected)

But what if we want to multiply two tensors by following the Matrix Multiplication rules? Well, tensorflow.js provides a helper function to accomplish that task as well. This is how you can multiple two tensors (real matrix multiplication):

let twoDimensionalTensor = tf.tensor([1,2,3,4], shape=[2,2], dtype="float32");
let multiplcation = twoDimensionalTensor.matMul(twoDimensionalTensor);

In the above case, as the number of columns of first matrix is same as the number of rows of the second matrix (in this case the same matrix), the matrix multiplication is possible. The output is: Tensor [[7 , 10], [15, 22]]


In this article, we have learned the basics of Machine or Deep Learning in general and TensorFlow.js in particular. We have also learnt how to integrate tensorflow.js into our project and utilize its functions. We have just scratched the surface. In the upcoming article, we shall discuss its more functionality. For now, that’s it for this article. I hope you like it!



Boostlog is an online community for developers
who want to share ideas and grow each other.

Delete an article

Deleted articles are gone forever. Are you sure?