PyTorch:如何将张量的形状作为 int 列表

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

在 numpy 中,V.shape 给出了 V 维度的整数元组。

在tensorflow中V.get_shape().as_list()给出了V维数的整数列表。

在pytorch中,V.size()给出了一个size对象,但是如何将其转换为int?

对于 PyTorch v1.0 及可能更高版本:

>>> 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'>

您可以将任何 torch.Size 对象转换为原生 Python 列表:

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

在 PyTorch v0.3 和 0.4 中:

简单list(var.size()),例如:

>>> 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]

如果您喜欢 NumPyish 语法,那么 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.:请注意 tensor.shapetensor.size() 的别名,尽管 tensor.shape 是有问题的张量,而 tensor.size() 是一个函数。

之前的回答得到了 torch.Size 的列表 这是获取整数列表的方法

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

A torch.Size object is a subclass of tuple,并继承其通常的属性,例如它可以被索引:

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

注意它的条目已经是 int 类型。


如果你真的想要一个列表,只需使用 list 构造函数,就像任何其他可迭代对象一样:

list(v.shape)