TensorflowJs – basic tensor operations and getting the individual values from a tensor

We have seen in the previous article that tensors are just a fancy way of referring to a structured collection of numbers. Any data container from a simple variable (0-dimension array) to a vector (1-dimension array) and up to a 6-dimension array is called a tensor.

In today's article, we will take a look at what are some basic tensor operations that TensorflowJs API provides out of the box, and also how to get the values from a tensor.

Let's roll!

Tensor operations with TensorflowJs

While tensors serve as the main containers of data the TensorflowJs library also provides a set of operations meant for the manipulation of this data.

For example, we can use a basic add operation to calculate the sum of two arrays:

const a = tf.tensor1d([1, 2, 3]);
const b = tf.tensor1d([10, 20, 30]);

An alternate way of writing this is:

tf.add(a, b).print();  // [11, 22, 33]

In the case where the shape of the two tensors are not the same we will get the below error:

Uncaught Error: Operands could not be broadcast together with shapes

And we also have access to multiple other arithmetic operations such as: tf.sub(), tf.maximum() or tf.pow().

Note that the tensors are immutable. Therefore these operations do not change their values. The operations return will always return new tensors.

Alongside basic math operations, TensorflowJs also comes with many other types of operations like:

• tf.unique(): retrieves unique elements
• tf.transpose(): transposes 2d matrixes arrays
• tf.greater(): returns the truth value of (a > b) for elements in 2 tensors

You can checkout the TensorflowJs API docs to see the full list.

TensorflowJs - getting the individual values from a tensor

Tensorflow was initially made for distributed computing. While this is great for the huge amount of computing needed for machine learning, it makes some basic operations a bit less intuitive.

For example when we try to iterate through the individual values in a tensor, or when we try to extract the results of a TensorflowJs model prediction in a Javascript variable.

Let's say we have the following tensor:

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

If we want to get the individual values from this tensor we will need to first call the asynchronous array() method and only after the returned promise is resolved we will get access to the actual values:

a.array().then(mat => {
for(let i = 0; i < mat.length; i++)
for(let j = 0; j < mat[i].length; j++)
console.log(`mat[\${i}][\${j}] has a value of \${mat[i][j]}`)
});

The above code will return the following output:

mat[0][0] has a value of 1
mat[0][1] has a value of 2
mat[1][0] has a value of 3
mat[1][1] has a value of 4

And if you want to get the flattened data we can use the data() method:

a.data().then(arr => {
console.log(arr)
// [1, 2, 3, 4]
});

There are also synchronous versions of these methods but can cause performance issues.

// gets the multi-dimensional array
console.log(a.arraySync());
// gets the flattened data
console.log(a.dataSync());

Bun, in general, you should try to use the asynchronous array() and data() methods in production.

ðŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

ðŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

ðŸ“– 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away: