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

新手上路,请多包涵

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

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

在 pytorch 中, V.size() 给出了一个大小对象,但我如何将其转换为整数?

原文由 patapouf_ai 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 898
2 个回答

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

原文由 alvas 发布,翻译遵循 CC BY-SA 4.0 许可协议

如果您喜欢 NumPy ish 语法,那么这里有 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]

PS : 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 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题