TF – TensorFlow

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):


<script src=””></script&gt;

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

Example 2

<script src=””></script&gt;

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.


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:

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:


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

Try it Yourself »


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

Try it Yourself »


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:


const tensorA = tf.tensor([1, 2, 3, 4], [2, 2], “int32”);
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


const tensorA = tf.tensor([[1, 2], [3, 4]]); => 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():


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 »