Tutorials References Exercises Videos Menu
Paid Courses Website NEW Pro NEW

TensorFlow.js Tutorial

What is TensorFlow.js?

A popular JavaScript library for Machine Learning.

Lets us train and deploy machine learning models in the Browser.

Lets us add machine learning functions to any Web Application.

Using TensorFlow

To use TensorFlow.js, add the following script tag to your HTML file(s):

Example

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.6.0/dist/tf.min.js"></script>

To make sure you always use the latest version, use this:

Example 2

<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>

TensorFlow was developed by the Google Brain Team for internal Google use, but was released as open software in 2015.

In January 2019, Google developers released TensorFlow.js, the JavaScript implementation of TensorFlow.

Tensorflow.js was designed to provide the same features as the original TensorFlow library written in Python.


Tensors

TensorFlow.js is a JavaScript library to define and operate on Tensors.

A Tensor is much the same as a multidimensional array.

A Tensor contains numeric values in a (one or more) dimensional shape.

A Tensor has the following main properties:

PropertyDescription
dtypeThe data type
rankThe number of dimensions
shapeThe size of each dimension


Creating a Tensor

A Tensor can be created from any N-dimensional array:

Example 1

const tensorA = tf.tensor([[1, 2], [3, 4]]);

Try it Yourself »

Example 2

const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);

Try it Yourself »


Tensor Shape

A Tensor can also be created from an array and a shape parameter:

Example1

const shape = [2, 2];
const tensorA = tf.tensor([1, 2, 3, 4], shape);

Try it Yourself »

Example2

const tensorA = tf.tensor([1, 2, 3, 4], [2, 2]);

Try it Yourself »

Example3

const tensorA = tf.tensor([[1, 2], [3, 4]], [2, 2]);

Try it Yourself »


Tensor Data Types

A Tensor can have the following data types:

  • bool
  • int32
  • float32 (default)
  • complex64
  • string

When you create a tensor, you can specify the data type as the third parameter:

Example

const tensorA = tf.tensor([1, 2, 3, 4], [2, 2], "int32");
/*
Results:
tensorA.rank = 2
tensorA.shape = 2,2
tensorA.dtype = int32
*/

Try it Yourself »


Retrieve Tensor Values

You can get the data behind a tensor using tensor.data():

Example

const tensorA = tf.tensor([[1, 2], [3, 4]]);
tensorA.data().then(data => display(data));

// Result: 1,2,3,4
function display(data) {
  document.getElementById("demo").innerHTML = data;
}

Try it Yourself »

You can get the array behind a tensor using tensor.array():

Example

const tensorA = tf.tensor([[1, 2], [3, 4]]);
tensorA.array().then(array => display(array[0]));

// Result: 1,2
function display(data) {
  document.getElementById("demo").innerHTML = data;
}

Try it Yourself »