# Understanding Tensors in PyTorch 🔥

In this first post, I will try to deconstruct tensors which are the fundamental data structures behind neural networks.

July 17, 2019 - 12 minute read -

So we put a tensor in your tensor and attained a higher dimension. Wait what?

Image source

For smaller dimensions, we can think in geometric analogies as shown above, like for e.g.

• A 0-d Tensor or Scalar would be a point in space.
• A 1-d Tensor or Vector would be a line in that space.
• A 2-d Tensor or Matrix would be a square (or rectangle), and
• A 3-d Tensor would be a cube (or cuboid)

Similarly we can go further,

• A 4-d Tensor would be a vector of cubes.
• A 5-d Tensor would be a matrix of cubes.
• A 6-d Tensor would be a cube made up of cubes.
• A 7-d Tensor would be a vector of cubes made up of cubes!

You get the idea.

As you can see, tensors are nothing but a generalisation of things we know and love : scalars, vectors and matrices. Specifically it is a N-dimensional data structure (or container) where $N$ is the number of dimensions. For people familiar with arrays, its just a multi-dimensional array.

As the world around us is three dimensional, we have a hard time visualising tensors, especially as the dimensions go beyond our own. Like imagine a 10-dimensional tensor in your head. What does it look like? Use the analogy of cubes and let me know in the comments below!

But why are they important for deep learning, you ask? Well they are central to linear algebra and also the fundamental data structures of a neural network. Its all N-dimensional tensors under the hood, following some predefined rules (dot products and applying some non-linearity) to compute some output given certain inputs.

Let’s see how we can create tensors in PyTorch.

## Import Libraries

A good practice before starting any experiment is to set a fixed seed. This makes things deterministic, meaning every time we run the experiment certain non-determinisitic (i.e. probabilistic) processes won’t result in different values. And yes, 42 is a reference to The Hitchhiker’s Guide to the Galaxy :)

## Generating Tensors

There are various ways to generate tensors in PyTorch. Let’s try a few and also check the resulting tensors’ datatypes,

Note : Here torch.tensor() with a single number actually returns a scalar value with int64 as the data type, whereas the others return a tensor. In general, torch.tensor() accepts a list of numbers and the dimensions/size of the tensor is determined from it.

Lets try passing a list of lists to torch.tensor() as follows,

So its a 2-d tensor of 3x3 size. We can peek into its contents just to be sure,

So we can pass lists like,

• $[..]$ which is a list (or an array). It would be a rank 1 or a 1-d tensor.
• $[[..],[..],[..]]$ which is a list of lists. It would be a rank 2 or a 2-d tensor.
• $[[[..],[..]],[[..],[..]]]$ which is a list of lists containing lists. It would be a rank 3 or a 3-d tensor. and so on.

The notion of Rank is very important when dealing with tensors. In a rigorous mathematical setting, it would have a slightly different meaning, but here I am using the term interchangeably with dimensions.

torch.empty() can be used for randomly initialising a tensor with a given size,

Similarly, torch.ones() is for creating a tensor with all the values as ones.

Both torch.empty() and torch.ones() accept dimensions of the tensor you want to create.

Note : We can use the GPU variant of tensors by just adding .cuda() at the end. This allows for faster computations by leveraging GPU memory.

## Specifying data types and type coercion

One way to force a PyTorch tensor to be of a specific datatype is to use the dtype argument as follows,

Note : The datatypes are specified with torch.<something>.

However, we cannot do this with torch.Tensor() since it is actually an alias for torch.FloatTensor() and fixes a default datatype of float rather than inferring it from the tensor passed. On the other hand, datatypes can be explicitly stated with torch.tensor() (as we saw above).

Now let’s check torch.tensor()’s default datatype,

Another cool thing is that if we just use a dot at the end of a number, the tensor becomes of type float,

Next up, we can check the sizes or shapes of tensors with .size(),

Note : Both .size() and .shape works.

Did I say tensors can only contain number? They can contain boolean values (or strings) as well. Using dtype=torch.bool we can convert a tensors of ones into a tensor of True(s) as follows,

The tensors should only contain elements of homogeneous datatypes.

## Generating tensors containing random numbers

Now let’s generate a tensor with torch.rand(), which will be composed of numbers randomly drawn from a uniform distribution $U \backsim [0,1)$

If U is a random variable uniformly distributed on $[0, 1]$, then $(r1 - r2) * U + r2$ is uniformly distributed on $[r1, r2]$. We can also use uniform_ to perform operations inplace (anything with a underscore at the end means inplace). Let’s see them in action,

## Indexing and slicing

Both indexing and slicing of PyTorch’s tensors work similar to numpy’s ndarrays and python’s lists. For e.g.

We can get a copy of the entire tensor like so,

We can specify indices for each dimension of the tensor to get the specific element as follows,

We can also slice the tensors along a specific dimension as follows,

In case you forgot how slicing worked in python, here’s a quick refresher :

• z[start:stop] - Get all items from start index all the way upto stop index-1
• z[start:] - Get all items from start index all the way to the end
• z[:stop] - Get all items from the beginning all the way to the stop index-1
• z[:] - Get the copy of the entire list

The only difference here is that we are dealing with multiple dimensions for tensors.

## 0-d Tensor or a Scalar

We can have scalars in PyTorch as follows,

or

Note that although their sizes are slightly different, however a 2-d tensor of size 1x1 contains just one number. Similarly a 3-d tensor of size 1x1x1 will also contain a single element and so on.

And since its just a single number we can retrieve it by using .item()

## 1-d Tensor or a Vector

Similarly for vectors,

or we can manually define as,

## 2-d Tensor or a Matrix

Now let’s generate a 16x16 matrix as follows,

We can visualise the matrix by plotting it as a heatmap. This allow us to quickly get a sense of the numbers contained within visually.

The intensity of each block corresponds to the values in the matrix. Doesn’t it look like the pixels of very low resolution grayscale image?

## 3-d Tensor

Now let’s create a 3-d tensor of size 16x16x16 as follows,

Now imagine a cube with all the faces having a size of 16. We can visualise each slice of this cube along its depth. For the 1st slice,

Similarly, the second slice,

and so on. In fact, our whole 16x16x16 cube is made up of 16 of these 16x16 slices (makes sense doesn’t it?).

Just for fun, let’s examine the cross-section i.e. all the 16 slices of our cube,

Our 16x16x16 3-d tensor turned out to be composites of 16 different grayscale images in way! Looking at matrices and tensors in this way is helpful, especially in the context of image processing since images have depth in the form of channels (like RGB) and are composites of 2-d tensors.

Note : The numbers on the axis in all the heatmaps represent indices in the 1st and 2nd dimensions.

A very neat feature in PyTorch is the seamless conversion between PyTorch and numpy data structures (tensors to ndarray) by just calling .numpy().

This means we can leverage all functions/methods which rely on a numpy array.

Now let’s jump a few dimensions and revisit what a 6-d tensor looked like (remember?),

Let the sizes along each dimension for the tensor be 16x16x16x16x16x16. Think about it :

• The larger cube represents a 3-d tensor of size 16x16x16.
• The smaller cubes within also represents a 3-d tensor of size 16x16x16.
• If the larger cube contains 16x16x16 smaller cubes with each having a size of 16x16x16 we get our 6-d tensor.

Tensors ain’t so scary anymore, right? We will go deeper next time with concepts such as broadcasting and tensor operations. In case you find a typo or something didn’t quite click, please leave a comment below!