numpy数组转置与轴变换
矩阵的转置
>>> import numpy as np
>>> arr=np.arange(15).reshape((3,5))
>>> arr
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> arr.T
array([[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]])
矩阵的内积
>>> import numpy as np
>>> arr=np.arange(15).reshape((3,5))
>>> arr
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> arr.T
array([[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]])
>>> np.dot(arr.T,arr)
array([[125, 140, 155, 170, 185],
[140, 158, 176, 194, 212],
[155, 176, 197, 218, 239],
[170, 194, 218, 242, 266],
[185, 212, 239, 266, 293]])
轴变换
二维轴变换
1.两轴交换
>>> import numpy as np
>>> arr=np.arange(15).reshape((3,5))
>>> arr
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
>>> arr.transpose(1,0)#1轴和0轴进行交换
array([[ 0, 5, 10],
[ 1, 6, 11],
[ 2, 7, 12],
[ 3, 8, 13],
[ 4, 9, 14]])
三维轴变换
>>> arr = np.arange(16).reshape((2, 2, 4))
>>> arr
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
>>> arr.transpose((1,0,2))
array([[[ 0, 1, 2, 3],
[ 8, 9, 10, 11]],
[[ 4, 5, 6, 7],
[12, 13, 14, 15]]])
1.这种变化有点麻烦,不好理解。但是如果简单化就好了,加入用P(x,y,z)来表示矩阵中的每一个点,那么在numpy中,这个x,y,z就分别对应0,1,2
2.举个例子比如原来数组中0这个元素,它原来的坐标是(0,0,0),那么transpose(1,0,2)对于这个点来说就是把x,y坐标互换,而z坐标不变,则其在新的矩阵中坐标依旧是(0,0,0)不变
3.举个另外点的例子比如4这个点,其坐标是(0,1,1),那么它的x和y坐标交换之后是(1,0,1),所以它在新的矩阵中位置是(1,0,1)
4.事实上transpose函数正是对原来矩阵中每个点做这个变换,最后得到新的矩阵
两轴交换
交换1轴和2轴
>>> arr
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
>>> arr.swapaxes(1,2)
array([[[ 0, 4],
[ 1, 5],
[ 2, 6],
[ 3, 7]],
[[ 8, 12],
[ 9, 13],
[10, 14],
[11, 15]]])
>>> arr
array([[[ 0, 1, 2, 3],
[ 4, 5, 6, 7]],
[[ 8, 9, 10, 11],
[12, 13, 14, 15]]])
原文地址:https://www.cnblogs.com/mengxiaoleng/p/11617244.html
时间: 2024-11-09 10:45:34