[python] PyTorch: How to get the shape of a Tensor as a list of int

In numpy, V.shape gives a tuple of ints of dimensions of V.

In tensorflow V.get_shape().as_list() gives a list of integers of the dimensions of V.

In pytorch, V.size() gives a size object, but how do I convert it to ints?

This question is related to python pytorch tensor

The answer is


If you're a fan of NumPyish syntax, then there's tensor.shape.

In [3]: ar = torch.rand(3, 3)

In [4]: ar.shape
Out[4]: torch.Size([3, 3])

# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]

# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]

# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]

P.S.: Note that tensor.shape is an alias to tensor.size(), though tensor.shape is an attribute of the tensor in question whereas tensor.size() is a function.


Previous answers got you list of torch.Size Here is how to get list of ints

listofints = [int(x) for x in tensor.shape]