pytorch --- tensor.permute()和torch.transpose()

tensor.permute(dim1, dim2, dim3, …)

permute可以对任意高维矩阵进行转置.但只有 tensor.permute() 这个调用方式

x = torch.rand(2,3,4)
print("x.shape:", x.shape)
x = x.permute(2,1,0)
print("x.shape:", x.shape)

输出:

x.shape: torch.Size([2, 3, 4])
x.shape: torch.Size([4, 3, 2])
[Finished in 1.0s]

例2:

t.rand(2,3,4,5).permute(3,2,0,1).shape
Out[669]: torch.Size([5, 4, 2, 3])

总结
传入permute方法的参数是维度, 未进行变换前的dim是[0, 1, 2]的方式, 转换后表示将第0维度和第2维度调换

torch.transpose(tensor, dim1, dim2)

transpose只能操作2D矩阵的转置(就是每次transpose只能在两个维度之间转换,其他维度保持不变)。有两种调用方式。连续使用transpose也可实现permute的效果

torch.transpose(Tensor, 1, 0)
t.rand(2,3,4,5).transpose(3,0).transpose(2,1).transpose(3,2).shape
Out[672]: torch.Size([5, 4, 2, 3])
t.rand(2,3,4,5).transpose(1,0).transpose(2,1).transpose(3,1).shape
Out[670]: torch.Size([3, 5, 2, 4])

transpose和permute的区别

主要区别是transpose只能在两个维度之间转换, permute可以一下转换好几个维度

参考
PyTorch 高维矩阵转置 Transpose 和 Permute

发布了33 篇原创文章 · 获赞 1 · 访问量 2617

猜你喜欢

转载自blog.csdn.net/orangerfun/article/details/103957890