栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

torch.transpose()

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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} ⎣⎢⎢⎡​000010020030​001011021031​002012022032​003013023033​⎦⎥⎥⎤​⎣⎢⎢⎡​100110120130​101111121131​102112122132​103113123133​⎦⎥⎥⎤​
将维度为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} ⎣⎢⎢⎡​000100200300​001101201301​002102202302​003103203303​⎦⎥⎥⎤​⎣⎢⎢⎡​010110210310​011111211311​012112212312​013113213313​⎦⎥⎥⎤​
将对应索引进行拼接,就是最终的 (3, 2, 4)的shape了
所以transpose更深层次的意义是将 矩阵 中数值的索引顺序改变,例:原来[0, 2] 索引的数值 2 在 transpose 后的矩阵中通过[2, 0] 索引,在高维度 tensor 通过这种理解对 transpose 操作就会更为清晰,

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857511.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号