pytorch中reshape()、view()、permute()、transpose()总结

1. reshape() 和 view()

参考链接:
PyTorch中view的用法
pytorch中contiguous()

功能相似,但是 view() 只能操作 tensor,reshape() 可以操作 tensor 和 ndarray。view() 只能用在 contiguous 的 variable 上。如果在 view 之前用了 transpose, permute 等,需要用 contiguous() 来返回一个 contiguous copy。 view() 操作后的 tensor 和原 tensor 共享存储。
pytorch 中的 torch.reshape() 大致相当于 tensor.contiguous().view()。

import torch
import numpy as np

a = np.arange(6)
print('a:\n',a)
b = a.reshape(2,3)
print('b-np.reahspe():\n', b)
c = torch.tensor(a)
d = c.reshape(2,3)
print('d-torch.reshape():\n',d)
e = c.view(2,3)
print('e-torch.view()\n',e)

输出:

a:
 [0 1 2 3 4 5]
b-np.reahspe():
 [[0 1 2]
 [3 4 5]]
d-torch.reshape():
 tensor([[0, 1, 2],
        [3, 4, 5]], dtype=torch.int32)
e-torch.view()
 tensor([[0, 1, 2],
        [3, 4, 5]], dtype=torch.int32)

2. permute() 和 transpose()

参考链接:
pytorch — tensor.permute()和torch.transpose()

两者都是实现维度之间的交换,transpose 只能一次转换两个维度,permute 可以一次转换多个维度,permute 可以通过 transpose 组合的形式实现。在卷积神经网络中,cross-channel max pooling 就用到了这类变换。

permute:

import torch
a = torch.tensor([[[0,1,2],[3,4,5]]])
print("a.shape:", a.shape)
print('a:\n',a)
b = a.permute(0,2,1)
print("b.shape:", b.shape)
print('b:\n',b)
c = a.permute(1,2,0)
print("c.shape:", c.shape)
print('c\n',c)

输出:

a.shape: torch.Size([1, 2, 3])
a:
 tensor([[[0, 1, 2],
         [3, 4, 5]]])
b.shape: torch.Size([1, 3, 2])
b:
 tensor([[[0, 3],
         [1, 4],
         [2, 5]]])
c.shape: torch.Size([2, 3, 1])
c
 tensor([[[0],
         [1],
         [2]],

        [[3],
         [4],
         [5]]])

transpose

a = torch.tensor([[[0,1,2],[3,4,5]]])
print("a.shape:", a.shape)
print('a:\n',a)
d = a.transpose(0,1)
print("d.shape:", d.shape)
print('d\n',d)
e = a.transpose(2,1)
print("e.shape:", e.shape)
print('e\n',e)

输出:

a.shape: torch.Size([1, 2, 3])
a:
 tensor([[[0, 1, 2],
         [3, 4, 5]]])
d.shape: torch.Size([2, 1, 3])
d
 tensor([[[0, 1, 2]],

        [[3, 4, 5]]])
e.shape: torch.Size([1, 3, 2])
e
 tensor([[[0, 3],
         [1, 4],
         [2, 5]]])

reshape 与 view 可以重新设置维度;permute 和 transpose 只能 在已有的维度之间转换,并且包含转置的概念。

猜你喜欢

转载自blog.csdn.net/weixin_41735859/article/details/106049688