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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46826218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:51:40  来源:igfitidea点击:

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

pythonpytorchtensor

提问by patapouf_ai

In numpy, V.shapegives a tuple of ints of dimensions of V.

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

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

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

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

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

回答by alvas

For PyTorch v1.0 and possibly above:

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

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

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

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


In PyTorch v0.3 and 0.4:

在 PyTorch v0.3 和 0.4 中:

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

简单地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]

回答by kmario23

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

如果您喜欢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.: Note that tensor.shapeis an alias to tensor.size(), though tensor.shapeis an attribute of the tensor in question whereas tensor.size()is a function.

PS:请注意,这tensor.shape是 的别名tensor.size(),尽管tensor.shape是所讨论的张量的属性,而tensor.size()是函数。