#native_company# #native_desc#
#native_cta#

Creating Tensors

Let's get physical

Sometimes, nothing beats holding a copy of a book in your hands. Writing in the margins, highlighting sentences, folding corners. So this book is also available from Amazon as a paperback.

Buy now on Amazon

We’ve covered the basic concept of Tensors in the previous lecture. In this lecture, we are going to learn how you use them in practice with TensorFlow.js. There will be a short quiz at the end.

Code

The code for this lecture, and the next lecture on operations, is in the tensorflow-basics folder in the source code associated with this course.

That folder has three files, like so:

.
├── index.html	(1)
├── main.js		(2)
└── scratch.js	(3)
1 This index.html file loads tensorflow.js and also just the scratch.js file.
2 This file contains all the completed code for this lecture.
3 This file should be empty.

Open the index.html as we taught in the setup-instructions lecture and then open the console in the browser, this is where the messages will go.

Add your code to scratch.js and refresh the browser to execute it. If you have problems, check main.js to see the correct completed code.

Creating a Tensor

We create a Tensor using the tf.tensor function like so:

var a = tf.tensor([1, 2, 3]); 	(1)
console.log(a.rank); 		    (2)
console.log(a.shape); 		    (3)
1 Creates a 1D tensor of size 3.
2 rank returns the rank (dimensionality) of a Tensor, for our example will return 1.
3 shape returns the size of each of the dimensions; for our example, this returns just [3].

Getting data from the Tensor

Now we want to look at the Tensor, print it out, and access the data we passed in.

You might try printing out the Tensor like so:

console.log(a);

But this would print out something like so:

t {kept: false, isDisposedInternal: false, shape: Array(1), dtype: "float32", size: 3, …}

It’s the Tensor object, but not the data the Tensor holds.

To print out the data inside a Tensor, we have a helper function called print() which we use like so:

a.print();

This will print to the console something like:

Tensor
    [1, 2, 3]

But that’s just for logging if you want to get access to the data itself you need to use another function called dataSync(), like so:

let data = a.dataSync();
console.log(data);

Which will print out something like so:

Float32Array(3) [1, 2, 3]

data in this case is a standard JavaScript floating-point array that you can use as you would use any other array.

Explicitly defining the rank

In the above example, tf.tensor guesses the rank of the Tensor based on the shape of the input data passed in, but you can be more explicit and specify the exact rank you are expecting in the input data like so:

var a = tf.tensor1d([1, 2, 3]);
console.log(a.rank);
console.log(a.shape);
a.print();

Note

In this example we are using tf.tensor1d instead of tf.tensor.

If we use a specific rank tensor like tf.tensor1d we can catch simple errors like the one below:

var a = tf.tensor1d([[1, 2, 3]]);

The above will print an error to the console, the reason might be hard to see, but if you look closely you will see that instead of passing a 1D array we are passing in a 2D array like so:

[[1, 2, 3]]

or to make it even easier to see:

[
    [1, 2, 3]
]

Another error that you may commonly encounter is when the input data’s shape is not complete, like so:

var a = tf.tensor([[1, 2], [3]]);

To fix the above, we need to make the shape the same size for all the axis, like so:

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

Explicitly providing the shape

Finally you can be even more explicit and provide the shape yourself, like so:

var a = tf.tensor(
    [1, 2, 3, 4],   (1)
    [2, 2]          (2)
);
1 We give it the raw data as a 1D array.
2 We additionally give the shape of the data, this is a rank 2, a 2D Tensor.

This is the typical pattern when dealing with non-trivial shapes of data. It’s tough for the human eye and mind to understand and recognize shapes beyond 2D. So we would provide the data as a 1D array and explicitly think about and talk about the shape.

Important

Get used to talking about Tensors and reasoning about them in terms of their shape and rank.

Quiz

Question

In the What are Tensors? lecture, we gave an example of a set of 100, 640 x 480 pixel black and white images.

Imagine all the data was provided as a 1D array called data, like so:

var data = Array(100*640*480).fill(1); (1)
1 This creates an array of size 100*640*480 where each value is the number 1

How would you represent that data set as a Tensor?

Solution

If you remember from the What are Tensors? lecture we defined the shape as [sample_size, width, height, colors]. For our specific example, the shape would then be [100, 640, 480, 1], colors is 1 because our image only has one color black.

We can then create a Tensor that represents this image like so:

var a = tf.tensor(data, [100, 640, 480, 1]);

We could be even more explicit by using tf.tensor4D and specifying the rank like so:

var a = tf.tensor4d(data, [100, 640, 480, 1]);

If you specified the wrong shape, for instance, if you used the shape [100, 640, 480, 2] then you would get an error in the console like so:

`Uncaught Error: Based on the provided shape, [100,640,480,2], the tensor should have 61440000 values but has 30720000`

Summary

You can create Tensors using the tf.tensor function. It guesses the shape and rank of the Tensor from the input data, or you can be more explicit by providing the shape as the second parameter by using one of the rank specific tensor creation functions like tf.tensor4d.

The standard model for non-trivial use cases is to provide the data as a 1D array and then specify the shape yourself rather than trying to morph the data into the shape you expect and having TensorFlow try to guess the shape of the Tensor from the shape of your data.



Advanced JavaScript

This unique course teaches you advanced JavaScript knowledge through a series of interview questions. Bring your JavaScript to the 2021's today.

Level up your JavaScript now!