PyTorch Tensor Shape: Get the PyTorch Tensor size

PyTorch Tensor Shape - Get the PyTorch Tensor size as a PyTorch Size object and as a list of integers

PyTorch Tensor Shape - Get the PyTorch Tensor size as a PyTorch Size object and as a list of integers

Video Transcript


We import PyTorch.

import torch


Then we print the PyTorch version that we are using.

print(torch.__version__)

We are using PyTorch 0.2.0_4.


For this video, we’re going to create a PyTorch tensor using the PyTorch rand functionality.

random_tensor_ex = (torch.rand(2, 3, 4) * 100).int()

It’s going to be 2x3x4.

We’re going to multiply the result by 100 and then we’re going to cast the PyTorch tensor to an int.

Finally, we’re going to assign that result to the random_tensor_ex Python variable.


We can then print the tensor to see what we created.

print(random_tensor_ex)

We see that it is a 2x3x4 tensor of size 2x3x4.

When we print it, we see that the last line tells us the size of the tensor we created.


However, if we wanted to get the size programmatically, we can use the .size() PyTorch functionality.

random_tensor_ex.size()

Here, we can see random_tensor_ex.size().

When we run it, we get a torch.Size object (2, 3, 4).


We can check the type of object that it returns.

type(random_tensor_ex.size())

So type(random_tensor_ex.size()).

We see that it’s with a class 'torch.Size'.


To get the actual integers from the size object, we can use Python’s list functionality.

random_tensor_size_list = list(random_tensor_ex.size())

We pass our random_tensor_ex variable to the list functionality and then we assign that to a Python variable, random_tensor_size_list.


We can then print the random_tensor_size_list:

print(random_tensor_size_list)

And we can see that it is a Python list that’s 2, 3, 4.


We can check the type of object that running our random_tensor_ex variable through the list functionality returned:

type(random_tensor_size_list)

And we see that it is indeed a list.


Lastly, we can check the type of the first element of the list.

type(random_tensor_size_list[0])

Remembering that Python is a zero-based index programming language, we see that it is an int.

So the list that we returned here is integer 2, integer 3, integer 4.


That is how you can get the PyTorch tensor shape as a PyTorch size object and as a list of integers.

Receive the Data Science Weekly Newsletter every Thursday

Easy to unsubscribe at any time. Your e-mail address is safe.