pythondebuggingmachine-learningpytorch

Printing all the contents of a tensor


I came across this PyTorch tutorial (in neural_networks_tutorial.py) where they construct a simple neural network and run an inference. I would like to print the contents of the entire input tensor for debugging purposes. What I get when I try to print the tensor is something like this and not the entire tensor:

enter image description here

I saw a similar link for numpy but was not sure about what would work for PyTorch. I can convert it to numpy and may be view it, but would like to avoid the extra overhead. Is there a way for me to print the entire tensor?


Solution

  • To avoid truncation and to control how much of the tensor data is printed use the same API as numpy's numpy.set_printoptions(threshold=10_000).

    Example:

    x = torch.rand(1000, 2, 2)
    print(x) # prints the truncated tensor
    torch.set_printoptions(threshold=10_000)
    print(x) # prints the whole tensor
    

    If your tensor is very large, adjust the threshold value to a higher number.

    Another option is:

    torch.set_printoptions(profile="full")
    print(x) # prints the whole tensor
    torch.set_printoptions(profile="default") # reset
    print(x) # prints the truncated tensor
    

    All the available set_printoptions arguments are documented here.