torch.transpose、np.transpose、torch.permute详解

超链接:深度学习工作常用方法汇总,矩阵维度变化、图片、视频等操作,包含(torch、numpy、opencv等)


1. torch.transpose、np.transpose、torch.permute

torch版:

x.transpose()

torch.transpose()一次只能在两个维度间进行转置(也可以理解为维度转换),最长用的是opencv中BGR转RGB。

import torch

x = torch.tensor([[[1, 2, 3], [4, 5, 6]],
                  [[7, 8, 9], [10, 11, 12]]])


b = x.transpose(1, 2)

print('x_shape:', x.shape)  # torch.Size([2, 2, 3])
print('b_shape:', b.shape)  # b_shape: torch.Size([2, 3, 2])
print(b)

numpy版:

x.transpose()

np.transpose(),维度变换,同torch.transpose()不同的是,np中是可以变换所有的轴,而且必须把所有的轴都写上去,否则会报错,而torch中一次只能变换2个轴。

感觉同torch中的permute函数一样。

import numpy as np

x = np.arange(12).reshape((3, 2, 2))
a = x.transpose(1, 2, 0)
print('x_shape:', x.shape)  # (3, 2, 2)
print('a_shape:', a.shape)  # (2, 2, 3)

torch版:

x.permute

torch.permute 同np.transpose一样,一次可以改变多个轴。

import torch

x = torch.tensor([[[1, 2, 3], [4, 5, 6]],
                  [[7, 8, 9], [10, 11, 12]]])


b = x.permute(1, 2, 0)

print('x_shape:', x.shape)  # torch.Size([2, 2, 3])
print('b_shape:', b.shape)  # b_shape: torch.Size([2, 3, 2])
print(b)

总结:reshape 与 view 可以重新设置维度;permute 和 transpose 只能 在已有的维度之间转换,并且包含转置的概念。
np.transpose 同 torch.permute一样,一次修改多个轴;
torch.transpose,一次只能修改1个轴。

猜你喜欢

转载自blog.csdn.net/qq_28949847/article/details/128568817