在numpy中,V.shape
给出了一个维数为V的整数元组。
在张量流V.get_shape().as_list()
中,给出了V维度的整数列表。
在pytorch中,V.size()
给出了一个大小对象,但是如何将其转换为整数?
答案 0 :(得分:14)
对于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]
答案 1 :(得分:4)
如果你是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 :请注意,tensor.shape
是tensor.size()
的别名,但tensor.shape
是有问题张量的属性,而tensor.size()
是一个功能。
答案 2 :(得分:1)
以前的答案为您提供了火炬列表。 这是获取整数列表的方法
listofints = [int(x) for x in tensor.shape]
答案 3 :(得分:0)
torch.Size
对象是 a subclass of tuple
,并继承其通常的属性,例如它可以被索引:
v = torch.tensor([[1,2], [3,4]])
v.shape[0]
>>> 2
注意它的条目已经是 int
类型。
如果你真的想要一个列表,只需像其他任何可迭代对象一样使用 list
构造函数:
list(v.shape)