83

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?

patapouf_ai
  • 17,605
  • 13
  • 92
  • 132

4 Answers4

108

For PyTorch v1.0 and possibly above:

>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])

# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>

# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>

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

>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>

In PyTorch v0.3 and 0.4:

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

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

>>> var
Variable containing:
 1  0
 0  1
[torch.IntTensor of size 2x2]

>>> var.size()
torch.Size([2, 2])

>>> list(var.size())
[2, 2]
alvas
  • 115,346
  • 109
  • 446
  • 738
  • 1
    Instead of calling `list`, does the Size class have some sort of attribute I can access directly to get the shape in a tuple or list form? – william_grisaitis Mar 12 '19 at 01:44
  • 1
    You can access the size directly without casting it into a list. The OP requested for a list hence the type casting. – alvas Mar 12 '19 at 02:58
  • Useful input. Thanks. I can add one point. The result is still list form. We can write simply to get output as an integer: `list(var.size())[0]` or `list(var.size())[1]` – Furkan Oct 20 '19 at 11:19
  • 2
    The elements of `list(var.size())` have the type of `tensor` rather than `int` in my case. How to deal with it? I need `int` – one Jul 27 '20 at 09:55
14

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.

kmario23
  • 57,311
  • 13
  • 161
  • 150
4

A torch.Size object is a subclass of tuple, and inherits its usual properties e.g. it can be indexed:

v = torch.tensor([[1,2], [3,4]])
v.shape[0]
>>> 2

Note its entries are already of type int.


If you really want a list though, just use the list constructor as with any other iterable:

list(v.shape)
iacob
  • 20,084
  • 6
  • 92
  • 119
2

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

listofints = [int(x) for x in tensor.shape]
vozman
  • 1,198
  • 1
  • 14
  • 19