transpose 作用是改变序列
需要注意的是,无论是numpy,还是pytorch,transpose一次都只能在两个维度上转换
参考另一篇博文
官方文档 numpy transpose
直接举例说明:
参数说明:
二维
import numpy as np
arr = np.arange(12).reshape((3, 4))
arr_np = np.transpose(arr, axes=(1, 0))
print(arr)
print(arr_np)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]] (3, 4)
[[ 0 4 8]
[ 1 5 9]
[ 2 6 10]
[ 3 7 11]] (4, 3)
三维
arr = np.arange(12).reshape((2, 3, 2))
# 这里要注意 axes 的参数必须要和arr的数据维度一致
arr_np = np.transpose(arr, axes=(0, 2, 1))
print(arr, arr.shape)
print(arr_np, arr_np.shape)
[[[ 0 1]
[ 2 3]
[ 4 5]]
[[ 6 7]
[ 8 9]
[10 11]]] (2, 3, 2)
[[[ 0 2 4]
[ 1 3 5]]
[[ 6 8 10]
[ 7 9 11]]] (2, 2, 3)
参数说明:
经过我测试发现,dim0和dim1的顺序对结果并无影响,
即 torch.transpose(x, 1, 0)
和 torch.transpose(x, 0, 1)
结果是一样的
二维
import torch
arr_tensor = torch.arange(12).reshape((3, 4))
arr_torch = torch.transpose(arr_tensor, 1, 0)
print(arr_tensor, arr_tensor.shape)
print(arr_torch, arr_torch.shape)
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]]) torch.Size([3, 4])
tensor([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]]) torch.Size([4, 3])
三维
arr_tensor = torch.arange(12).reshape((2, 3, 2))
arr_torch = torch.transpose(arr_tensor, 2, 1)
print(arr_tensor, arr_tensor.shape)
print(arr_torch, arr_torch.shape)
tensor([[[ 0, 1],
[ 2, 3],
[ 4, 5]],
[[ 6, 7],
[ 8, 9],
[10, 11]]]) torch.Size([2, 3, 2])
tensor([[[ 0, 2, 4],
[ 1, 3, 5]],
[[ 6, 8, 10],
[ 7, 9, 11]]]) torch.Size([2, 2, 3])
可以对任意高维矩阵进行转置