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

numpy.reshape, numpy.transpose的理解

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

numpy.reshape, numpy.transpose的理解

这两个命令在变化矩阵时常用,用久了又会返回来思考二者对矩阵变换结果的影响。此处举例说明:

1.np.reshape

该命令会重排矩阵元素,可看代码:

a = np.random.randint(1, 10, [1, 6, 2] )
print(a)
print(a.reshape(2, 3, 2))
print(a.reshape(3, 2, 2))
print(a.reshape(3, 2, 2).transpose(1, 0, 2))

结果为:

#print(a)
[[[9 1]
  [5 8]
  [4 2]
  [7 1]
  [4 9]
  [7 9]]]

#print(a.reshape(2, 3, 2))
[[[9 1]
  [5 8]
  [4 2]]

 [[7 1]
  [4 9]
  [7 9]]]

#print(a.reshape(3, 2, 2))
[[[9 1]
  [5 8]]

 [[4 2]
  [7 1]]

 [[4 9]
  [7 9]]]

#print(a.reshape(3, 2, 2).transpose(1, 0, 2))
[[[9 1]
  [4 2]
  [4 9]]

 [[5 8]
  [7 1]
  [7 9]]]

reshape后实际是将原始矩阵顺序重新排列。此处还发现a.reshape(2, 3, 2).reshape(3, 2, 2)与.reshape(3, 2, 2)结果一致。此处的np.transpose放在第2节中叙述。

2.np.transpose

该函数是用于实现矩阵的转置。而对于高维矩阵则该函数也可实现维度交换,但与reshape不一样。此处是基于转置的交换维度,排列顺序不会与原始相同。先看看对于二维矩阵:

mm = np.random.randint(1, 10, [2, 3])
print(mm)#[[1 3 3]
 					  #[9 3 8]]
print(mm.transpose(1, 0))#[[1 9]
 													  #[3 3]
 													  #[3 8]]

此处是基于转置的交换维度。此时可以再来理解1节中的a.reshape(3, 2, 2).transpose(1, 0, 2)。转置只发生在0和1维度中,2维度可以看做固定元素。由结果可见,transpose是将0和1维度转置,并且,a.reshape(3, 2, 2).transpose(1, 0, 2)与a.reshape(2, 3, 2)结果是不一样的,前者是基于转置改变维度,后者还是从前往后组装元素,要特别注意。

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

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

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