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?

For PyTorch v1.0 and possibly above:

&gt;&gt;&gt; import torch
&gt;&gt;&gt; var = torch.tensor([[1,0], [0,1]])

# Using .size function, returns a torch.Size object.
&gt;&gt;&gt; var.size()
torch.Size([2, 2])
&gt;&gt;&gt; type(var.size())
&lt;class 'torch.Size'&gt;

# Similarly, using .shape
&gt;&gt;&gt; var.shape
torch.Size([2, 2])
&gt;&gt;&gt; type(var.shape)
&lt;class 'torch.Size'&gt;


You can cast any torch.Size object to a native Python list:

&gt;&gt;&gt; list(var.size())
[2, 2]
&gt;&gt;&gt; type(list(var.size()))
&lt;class 'list'&gt;




In PyTorch v0.3 and 0.4:

Simply list(var.size()), e.g.:

&gt;&gt;&gt; import torch
&gt;&gt;&gt; from torch.autograd import Variable
&gt;&gt;&gt; from torch import IntTensor
&gt;&gt;&gt; var = Variable(IntTensor([[1,0],[0,1]]))

&gt;&gt;&gt; var
Variable containing:
 1  0
 0  1
[torch.IntTensor of size 2x2]

&gt;&gt;&gt; var.size()
torch.Size([2, 2])

&gt;&gt;&gt; list(var.size())
[2, 2]

