sam*_*mol 8 python multidimensional-array deep-learning pytorch tensor
tensor.permute()和之间有什么区别tensor.view()?
他们似乎做同样的事情。
kma*_*o23 10
In [12]: aten = torch.tensor([[1, 2, 3], [4, 5, 6]])
In [13]: aten
Out[13]:
tensor([[ 1, 2, 3],
[ 4, 5, 6]])
In [14]: aten.shape
Out[14]: torch.Size([2, 3])
Run Code Online (Sandbox Code Playgroud)
torch.view()将张量重塑为不同但兼容的形状。例如,我们的输入张量aten的形状为(2, 3)。这可以被视为作为形状的张量(6, 1),(1, 6)等等,
# reshaping (or viewing) 2x3 matrix as a column vector of shape 6x1
In [15]: aten.view(6, -1)
Out[15]:
tensor([[ 1],
[ 2],
[ 3],
[ 4],
[ 5],
[ 6]])
In [16]: aten.view(6, -1).shape
Out[16]: torch.Size([6, 1])
Run Code Online (Sandbox Code Playgroud)
可替换地,它也可以被重新成形或视图编作为形状的行向量(1, 6),如下所示:
In [19]: aten.view(-1, 6)
Out[19]: tensor([[ 1, 2, 3, 4, 5, 6]])
In [20]: aten.view(-1, 6).shape
Out[20]: torch.Size([1, 6])
Run Code Online (Sandbox Code Playgroud)
而tensor.permute()仅用于交换轴。下面的例子将使事情变得清楚:
In [39]: aten
Out[39]:
tensor([[ 1, 2, 3],
[ 4, 5, 6]])
In [40]: aten.shape
Out[40]: torch.Size([2, 3])
# swapping the axes/dimensions 0 and 1
In [41]: aten.permute(1, 0)
Out[41]:
tensor([[ 1, 4],
[ 2, 5],
[ 3, 6]])
# since we permute the axes/dims, the shape changed from (2, 3) => (3, 2)
In [42]: aten.permute(1, 0).shape
Out[42]: torch.Size([3, 2])
Run Code Online (Sandbox Code Playgroud)
您还可以使用负索引来做与以下相同的事情:
In [45]: aten.permute(-1, 0)
Out[45]:
tensor([[ 1, 4],
[ 2, 5],
[ 3, 6]])
In [46]: aten.permute(-1, 0).shape
Out[46]: torch.Size([3, 2])
Run Code Online (Sandbox Code Playgroud)
视图更改了张量的表示方式。例如:具有 4 个元素的张量可以表示为 4X1 或 2X2 或 1X4,但置换会改变轴。在排列数据时移动但视图数据没有移动而只是重新解释。
下面的代码示例可能对您有所帮助。a是 2x2 张量/矩阵。通过使用视图,您可以将其读a作列向量或行向量(张量)。但是你不能转置它。要转置,您需要置换。转置是通过交换/排列轴来实现的。
In [7]: import torch
In [8]: a = torch.tensor([[1,2],[3,4]])
In [9]: a
Out[9]:
tensor([[ 1, 2],
[ 3, 4]])
In [11]: a.permute(1,0)
Out[11]:
tensor([[ 1, 3],
[ 2, 4]])
In [12]: a.view(4,1)
Out[12]:
tensor([[ 1],
[ 2],
[ 3],
[ 4]])
In [13]:
Run Code Online (Sandbox Code Playgroud)
奖励:见https://twitter.com/karpathy/status/1013322763790999552
| 归档时间: |
|
| 查看次数: |
6537 次 |
| 最近记录: |