PyTorch Print Tensor: Print Full Tensor in PyTorch

PyTorch Print Tensor - Print full tensor in PyTorch so that you can see all of the elements rather than just seeing the truncated or shortened version

PyTorch Print Tensor - Print full tensor in PyTorch so that you can see all of the elements rather than just seeing the truncated or shortened version

Video Transcript


We import PyTorch.

import torch


Then we print the PyTorch version we are using.

print(torch.__version__)

We are using 0.2.0_4.


For this video, we create a PyTorch tensor using the PyTorch rand functionality and assign the tensor to the Python variable big_random_variable_ex.

big_random_variable_ex = (torch.rand(200, 3, 4) * 100).int()

This Python variable holds a PyTorch tensor that is of size 200x3x4 with random float32 numbers that are multiplied by 100 and then cast to integers.


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

print(big_random_variable_ex)


Let’s scroll through to see what we got.

We see matrix 0, matrix 1, matrix 2 (dot dot dot), matrix 197, matrix 198, and matrix 199.

So we are only seeing a truncated or shortened version of the PyTorch tensor.


To print a verbose version of the PyTorch tensor so that we can see all of the elements, we’ll have to change the PyTorch print threshold option.


To do that, we do the following: torch.set_printoptions.

torch.set_printoptions(threshold=10000)

We’re setting the threshold to 10,000.


The reason we set such a high number is to force PyTorch to print all of the elements in the tensor.

The threshold is set by default to 1000, so setting it 10 times bigger than the default is a good start.

The threshold is the total number of array elements which trigger summarization rather than the full representation.


If we check the shape of our example tensor:

big_random_variable_ex.shape

We see that it is a PyTorch tensor, the size of which is 200x3x4.


So we can calculate the number of elements easily.

200 * 3 * 4

So 200 * 3 * 4, we have 2400, which is why the default of 1000 triggered summarization but the threshold being set to 10,000 will not.


So let’s try printing our tensor again.

print(big_random_variable_ex)

So print big_random_variable_ex.


We can scroll through and now you can see that we have in fact all of our matrices.


So we can see here is number 32, and we scroll down, scroll down.

Here is number 115.

We can continue scrolling down until we get to our very last one.


That is how you can print a verbose version of a PyTorch tensor so that you can see all of the elements rather than just seeing the truncated or shortened version.

Receive the Data Science Weekly Newsletter every Thursday

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