PyTorch 中 tensor.permute 和 tensor.view 的区别?

新手上路,请多包涵

tensor.permute()tensor.view() 有什么区别?

他们似乎在做同样的事情。

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

阅读 723
1 个回答

输入

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

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

或者,也可以将其重新整形或 查看 为形状为 (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])

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

您还可以使用负索引来做同样的事情:

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

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

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