这两个命令在变化矩阵时常用,用久了又会返回来思考二者对矩阵变换结果的影响。此处举例说明:
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)结果是不一样的,前者是基于转置改变维度,后者还是从前往后组装元素,要特别注意。



