torch.transpose()

首先transpose是为了转换矩阵维度的,在numpy和pytorch中的作用都是一样的,分别举例说明:

arr = np.arange(24).reshape((2, 3, 4))
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]

目标:将矩阵 arr 的0维度和1维度进行交换
需要注意,transpose每次只能转换两个维度

np.transpose()

np_transpose = arr.transpose((1, 0, 2))
np_transpose = np.transpose(arr, (1, 0, 2))	# 和上一行代码操作结果一致
print(np_transpose, np_transpose.shape)

[[[ 0  1  2  3]
  [12 13 14 15]]

 [[ 4  5  6  7]
  [16 17 18 19]]

 [[ 8  9 10 11]
  [20 21 22 23]]] (3, 2, 4)

torch.transpose()

使用方法和numpy有略微不同

tensor_arr = torch.tensor(arr)
torch_transpose = tensor_arr.transpose(0, 1)
torch_transpose = torch.transpose(tensor_arr, 0, 1)	# 和上一行代码的结果一致
print(torch_transpose, torch_transpose.shape)
tensor([[[ 0,  1,  2,  3],
         [12, 13, 14, 15]],

        [[ 4,  5,  6,  7],
         [16, 17, 18, 19]],

        [[ 8,  9, 10, 11],
         [20, 21, 22, 23]]], dtype=torch.int32) torch.Size([3, 2, 4])

这里通过索引讲解一下:
在原始的矩阵 arr 中,每个元素的索引号可以表示成
[ 000 001 002 003 010 011 012 013 020 021 022 023 030 031 032 033 ] [ 100 101 102 103 110 111 112 113 120 121 122 123 130 131 132 133 ] \begin{bmatrix} 000 & 001 & 002 & 003 \\ 010 & 011 & 012 & 013 \\ 020 & 021 & 022 & 023 \\ 030 & 031 & 032 & 033 \end{bmatrix} \begin{bmatrix} 100 & 101 & 102 & 103 \\ 110 & 111 & 112 & 113 \\ 120 & 121 & 122 & 123 \\ 130 & 131 & 132 & 133 \end{bmatrix} 000010020030001011021031002012022032003013023033100110120130101111121131102112122132103113123133
将维度为0和维度为1进行转换,那么新索引可以表示为
[ 000 001 002 003 100 101 102 103 200 201 202 203 300 301 302 303 ] [ 010 011 012 013 110 111 112 113 210 211 212 213 310 311 312 313 ] \begin{bmatrix} 000 & 001 & 002 & 003 \\ 100 & 101 & 102 & 103 \\ 200 & 201 & 202 & 203 \\ 300 & 301 & 302 & 303 \end{bmatrix} \begin{bmatrix} 010 & 011 & 012 & 013 \\ 110 & 111 & 112 & 113 \\ 210 & 211 & 212 & 213 \\ 310 & 311 & 312 & 313 \end{bmatrix} 000100200300001101201301002102202302003103203303010110210310011111211311012112212312013113213313
将对应索引进行拼接,就是最终的 (3, 2, 4)的shape了
所以transpose更深层次的意义是将 矩阵 中数值的索引顺序改变,例:原来[0, 2] 索引的数值 2 在 transpose 后的矩阵中通过[2, 0] 索引,在高维度 tensor 通过这种理解对 transpose 操作就会更为清晰,

  • 10
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值