torch.transpose:转置经常在矩阵中使用,交换两个维度。
torch.transpose(tensor,dim_0,dim_1)
代码示例:
import torch
a=torch.tensor([[[1,2,3],[4,5,6]],
[[7,8,9],[10,11,12]]])
b=torch.transpose(a,1,2)
print("tensor_a",a)
print("tensor_b",b)
print("a的shape:",a.shape)
print("b的shape:",b.shape)
输出:
tensor_a: tensor([[[ 1, 2, 3],
[ 4, 5, 6]],
[[ 7, 8, 9],
[10, 11, 12]]])
tensor_b: tensor([[[ 1, 4],
[ 2, 5],
[ 3, 6]],
[[ 7, 10],
[ 8, 11],
[ 9, 12]]])
a的shape: torch.Size([2, 2, 3])
b的shape: torch.Size([2, 3, 2])
注:transpose只能交换两个维度,想想矩阵,再想想维度0是什么。