Tensorflow.js Crash-Course

TensorFlow.js is a deep learning library providing you with the power to train and deploy your favorite deep learning models in the browser and Node.js.
TensorFlow.js is a deep learning library providing you with the power to train and deploy your favorite deep learning models in the browser and Node.js. It doesn't matter if you are a Javascript developer with no Machine Learning experience whatsoever or an ML developer searching for a new opportunity to use his/her knowledge inside the browser; Tensorflow.js can provide you with huge benefits.
This is because Tensorflow.js provides us with both a simple high-level API called layers API, which is very similar to the Keras deep learning framework and can be used to create new models, as well as a low-level API — the Core API (previously deeplearn.js) — which lets you implement a lot of custom functionality.
In this article, I'll show you the basics of Tensorflow.js, including:
- Getting started
- Basics
- Building Linear Regression with the Core API
- Using the Layers API
- Converting existing Tensorflow/Keras models to Tensorflow.js
- Using ML5.js
Use Cases of Tensorflow.js
TensorFlow.js supports three main workflows as specified by Josh Gordon in "Introducing TensorFlow.js: Machine Learning in Javascript".
- Use a pre-trained model for inference. TensorFlow.js can be used with any pre-existing TensorFlow or Keras model by simply transforming them into TensorFlow.js format.
- Re-train an existing model. Use transfer learning to augment an existing model trained offline to enable it to perform correctly for each unique user.
- Create models directly in the browser. Use TensorFlow.js to define, train, and run models entirely in the browser using JavaScript.
Example Applications
Google provides us with a few demo applications that show us the real power of Tensorflow.js. These include computer vision examples like their Emoji Scavenger Hunt game and their Pac-Man Webcam Controller.

They also include examples of using Recurrent Neural Networks to play music, explore pictures using pose estimation, and teach a model to recognize images and play sound.

Setup
Browser Setup
There are two main ways to get TensorFlow.js in your browser-based projects:
- Using script tags.
- Installation via Yarn or NPM
script tags:
Installation via Yarn or NPM:
Node.js Setup
Tensorflow.js can also be run with Node.js. Here you can either install it with native C++ bindings or if you're on a Linux machine and have a supported NVIDIA® GPU with CUDA support, you can use the GPU package for even higher performance.
Option 1: Install TensorFlow.js with native C++ bindings.
Option 2: (Linux Only) If your system has an NVIDIA GPU with CUDA support, use the GPU package even for higher performance.
Tensors
If you are familiar with deep learning frameworks like TensorFlow or PyTorch, you should already be familiar with the concepts of Tensors. If not, here is a quick overview. Tensors are the central unit of data in TensorFlow, and mathematically a Tensor represents an n-dimensional array that is optimized for hardware usage.
A tf.Tensor also contains the following properties:
- rank: defines how many dimensions the tensor contains
- shape: which defines the size of each dimension of the data
- dtype: which defines the data type of the tensor.
In Tensorflow.js, we can create a scalar-tensor by typing:
To log the tensor to a console, use the .print
method.
You can also create a tensor from an array:
To get the shape of a tensor, use the .shape
method.
To transform a tensor back to an array, TensorFlow.js provides us with the .array
method.
Operators
Tensorflow.js also provides us with a wide variety of operations that allow you to manipulate the data. If we, for example, want to find the square of a tensor, we can use the square
method.
This outputs a tensor of [1, 4, 9, 16].
Tensorflow.js also allows chaining operations like squaring a tensor and then adding a constant to it.
Tensor Disposal (Memory Cleaning)
When using the WebGL backend, memory must be managed explicitly. This means that it's not sufficient to let a tf.Tensor
go out of scope for its memory to be released. To destroy the memory of a tf.Tensor,
we need to perform a call to the dispose
method.
This is fine for single tensors but can get inconvenient quickly as you write more code. But not disposing of tensors can cause memory overhead, and therefore Tensorflow.js offers a special operator that can dispose of multiple tensors automatically — the tidy
method.
Output:
Using the tidy
method, TensorFlow.js automatically disposed of the tf.Tensor
variables that weren't needed for the final calculation anymore.
Building Linear Regression with the Core API
The CoreAPI isn't made for creating big Neural Networks primarily. Instead, it is used for customizations, but nonetheless, it is useful if you have some basic understanding of how you could use the Core API to create something like a simple Linear Regression model that fits some random uniform data, which is what we are going to do.
This code first creates a random uniform data-set and two tf.variable
variables initialized between -1 and 1. After that, we set Stochastic Gradient Descent(SGD) as our optimizer, implement mean squared error as our loss function, and implement our prediction function. Lastly, we create a loop that runs for 50 epochs and optimizes our two tf.Variables
— m and b — using our optimizer and loss function.
Layers API
The Tensorflow.js Layers API allows us to quickly prototype and create a Machine Learning model. It is modeled after the popular Keras deep learning library.
To create a model with the Layers API, we need to create a tf.sequential
object and then use the add()
method to add some layers. So if we, for example, want to create a model for the XOR problem, we can use the following code.
You can also use an Array of already-constructed Layers to create a tf.Sequential model:
After creating the model, you can train it with the fit
or fitDataset
method.
If your data-set fits in main memory and is available as a single tensor, you can train a model by calling the fit()
method.
If your data doesn't fit entirely in memory or is being streamed, you can train a model using the fitDataset method.
Convolutional Neural Networks
A Convolutional Neural Network (CNN/ConvNet) is a kind of Deep Learning algorithm that enables us to extract features from an image. It can be used for almost every computer vision task and completely redefined the way computers 'see'.
The Layers API already has all the building blocks we need to create a CNN — Convolutional Layers, Pooling Layers, … — so we only need to use them. For example, we can create a simple model that can be used with the MNIST data-set.
This code above creates a Neural Network with two Convolutional blocks (a block is a convolutional + pooling layer). Then it flattens the output so it can be used with a fully connected layer.
After creating the model, we can compile it and start with the training. Now instead of using Stochastic Gradient Descent (SGD) — the veteran under the optimizers — we will use Adam because of its faster converge time.
We didn't really load in the MNIST data-set. But if we did, we could train the model with the following code.
This would result in a model that could predict the class of a picture of a digit with over 90% accuracy. If you're interested in a detailed walkthrough on training a model on the MNIST data-set take a look at the 'TensorFlow.js — Handwritten digit recognition with CNNs' codelab.
Recurrent Neural Network
CNNs are great when working with images, but they can't capture temporal patterns. Therefore they can't be used for problems including weather forecasting and stock price predictions, which rely heavily on temporal patterns.
This is where Recurrent Neural Networks (RNNs) come into play. They allow us to operate over sequences of input vectors by providing a kind of memory. For more information, check out this excellent article.
Just like for CNNs, the LayerAPI provides us with all the needed layers to build our RNN.
This code creates a RNN model. A long short-term memory (LSTM) model, if we want to be exact. We can use such an architecture to, for example, create a model that learns to predict the next word in the alphabet.
This script trains a RNN model to predict the next character of the alphabet. The first 20 lines are used to create the data-set. The only thing to keep in mind here is that we are one-hot-encoding the output vectors in lines 8–9 (could also be done using the oneHot
method provided by Tensorflow.js).
After that, we create a model with one LSTM layer and one hidden, fully connected layer. And lastly, we are training the model and making predictions.
This script should print the following outputs to the developer console:
I know this is an oversimplified example and undoubtedly not useful in the real world, but the basic process of creating the Recurrent Neural Network will stay the same for other RNN models. If you are interested in a more complicated example, check out this post showing how to predict stock prices with Tensorflow.js.
Convert an existing model to Tensorflow.js
Even though it is useful to create your own models from scratch in the browser, it won't be the primary use-case of Tensorflow.js. Instead, you will convert pre-trained models from Tensorflow or Keras to Tensorflow.js and use them for inference.
To convert the models, we need the Tensorflow.js converter python module.
Converting a Keras H5 model to Tensorflow.js
Now that we have the Tensorflow.js module installed, we can either use the command-line tool or the Python API to convert our models. To convert a Keras model to Tensorflow.js, we need to specify Keras as our input format.
Command Line:
Python API:
Converting a Tensorflow model to Tensorflow.js
When converting from Tensorflow to Tensorflow.js, we need to look out for the specific Tensorflow model type. The converter supports the conversion of the three main types — SavedModel, Frozen Graph, Tensorflow Hub.
Convert SavedModel example:
Convert frozen model example:
Tensorflow Hub module example:
Output formats
The Tensorflow.js converter doesn't create the same output format for every input format. Keras models will be converted to tfjs_layers_model
format, while Tensorflow models will be converted to tfjs_graph_model
format.

This is important to know for loading the model into Tensorflow.js later.
Use a converted model.
After converting your favorite models to a Tensorflow.js ready format, you are ready to use them for your application.
Models with the tfjs_layers_model
format can be loaded into Tensorflow.js using the loadLayersModel
method.
Models in tfjs_graph_model
format can be loaded using the loadGraphModel
method.
After loading the model, it can be used like any other model.
Working with data - Tensorflow.js Data
TensorFlow.js Data provides simple APIs to load and parse data from disk or over the web in a variety of formats, and to prepare that data for use in machine learning models (e.g. via operations like filter, map, shuffle, and batch). - TF.js repository
There are two ways to import/use Tensorflow.js Data:
- You can use TF.js data through the @tensorflow/tfjs package.
- You can get TF.js Data as a standalone module: @tensorflow/tfjs-data. Note that
tfjs-data
requirestfjs-core
, so if you import@tensorflow/tfjs-data
, you also need to import@tensorflow/tfjs-core
.
Example: Importing the Boston Housing data-set:
For more information, check out the TensorFlow.js Data Github README.
Tensorflow.js Visualization - tfjs-vis
tfjs-vis is a small library for in-browser visualization intended for use with TensorFlow.js. It allows you to visualize model behavior and Tensorflow.js specific object and also offers you a way of organizing visualizations.
You can install tfjs-vis
with NPM or Yarn:
If you want to learn how to use the library, I recommend checking out the two demos available on Github:

ML5JS - Friendly Machine Learning for the Web
ml5js is a high-level Machine Learning library built on top of TensorFlow.js. It is heavily inspired by Processing and p5.js and aims to make machine learning approachable for a broad audience of artists, creative coders, and students.
It allows you to train and use state-of-the-art models with only a few lines of code.
Image Classification:
If you want to learn more about ML5JS, I recommend checking out the documentation as well as Coding Trains "A Beginner's Guide to Machine Learning with ml5.js", which gives you an excellent introduction to the library.
Resources
- TensorflowJS Homepage
- TensorflowJS API Documentation
- TensorflowJS Github Repository
- TensorflowJS Gallery
- TensorflowJS Examples
Summary
Tensorflow.js is a powerful deep learning library that enables us to use the power of Machine Learning in the browser. It can not only be used to train your own model inside the browser, but it also supports using models written in another Deep Learning library like Tensorflow or Keras.