本文共 1295 字,大约阅读时间需要 4 分钟。
numpy/reference: https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/
数据array相乘,矩阵matrix相乘运算的差别
MATLAB中矩阵相乘用星号"*",元素相乘用点星 ".*"
对于array数据,对应元素相乘也就是每个元素的平方,直接用星号*
a=np.array([[1,2,3], [4,5,6]])print(a*a)print(a**2) # 对应元素相乘,结果相等
结果都是:
[[ 1 4 9] [16 25 36]]
对于array数据,矩阵的乘法用函数 np.dot()
a=np.array([[1,2,3], [4,5,6]])print( np.dot(a,a.T)) print( a.dot(a.T)) #另一种写法
结果都是:
[[14 32] [32 77]]
对于matrix数据,对应元素相乘,即元素平方,用函数 np.multiply(a,a)
a=np.mat([[1,2,3], [4,5,6]])np.multiply(a,a)
结果:
matrix([[ 1, 4, 9], [16, 25, 36]])
对于matrix数据,矩阵乘法, 用星号* ,或者函数, np.dot()
a=np.mat([[1,2,3], [4,5,6]])print (np.dot(a,a.T)) #矩阵乘法print (a*a.T)
结果:matrix([[14, 32], [32, 77]])
其它一些矩阵运算:
数据array的指数运算,使用**,
a=np.array([[-1,2,3], [2,-4,6]])print(a**3)结果:
array([[ -1, 8, 27], [ 8, -64, 216]], dtype=int32)
合并数组
import numpy as np#np.hstack(a,b)#!注意 只接受一个参数,list或者tuple#np.vstack(a,b)a1 = np.array([[1,2], [4,5]])a2 = np.array([3,6])a2.shape=1,2print(np.vstack((a1,a2)))#垂直放,列要求相等a2.shape=2,1print(np.hstack([a1,a2]))#水平放,行要求相等
一维的array不区分行列,所以转置操作无效。可以通过shape属性,变为二维再使用转置
用数组的shape属性调整维度,升维降维,等价于reshape (r,c)
特征向量按特征值排序
value,eigvector = np.linalg.eig(Cx) indices = np.argsort(value) indices[::-1]eigvector[:,indices]