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
< > Code:
You must be a Member to view code
Access all courses and lessons, gain confidence and expertise, and learn how things work and how to use them.
or Log In
We import PyTorch.
Then we print the PyTorch version that we are using.
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.
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.
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.
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:
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:
And we see that it is indeed a list.
Lastly, we can check the type of the first element of the list.
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.