矩阵运算
论numpy中matrix 和 array的区别:
matrix 和 array的差别: Numpy matrices必须是2维的,但是 numpy arrays (ndarrays) 可以是多维的(1D,2D,3D····ND). Matrix是Array的一个小的分支,包含于Array。所以matrix 拥有array的所有特性。
1.基本运算
import numpy as npa = np.array([[-1,2],[2,3]])b = np.array([[3,4],[4,5]])print '\n a:\n',aprint '\n b:\n',b##转置print '\n a transpose:\n',a.T##共扼矩阵#print '\n a H:\n',a.I##逆矩阵print '\n a inv:\n',np.linalg.inv(a) # 求逆##转置print '\n a transpose:\n',a.T# a + b,矩阵相加print "\n a+b: \n",a+b# a - b,矩阵相减print "\n a-b: \n",a-b#2x2 矩阵,矩阵相乘print "\n a mul b:\n",a.dot(b.T)#2x3矩阵,矩阵点乘print "\n a dot b: \n",a*b#2x3矩阵,矩阵点除print "\n a/b \n:",a/np.linalg.inv(b)#求迹print "\n a trace",np.trace(a) #特征,特征向量eigval,eigvec = np.linalg.eig(a) #eigval = np.linalg.eigvals(a) #直接求解特征值print "\n a eig value:\n",eigval,print'\n a eig vector:\n',eigvec
运算结果:
a:[[-1 2] [ 2 3]] b:[[3 4] [4 5]] a transpose:[[-1 2] [ 2 3]] a inv:[[-0.42857143 0.28571429] [ 0.28571429 0.14285714]] a transpose:[[-1 2] [ 2 3]] a+b: [[2 6] [6 8]] a-b: [[-4 -2] [-2 -2]] a mul b:[[ 5 6] [18 23]] a dot b: [[-3 8] [ 8 15]] a/b : [[ 0.2 0.5] [ 0.5 -1. ]] a trace 2 a eig value:[-1.82842712 3.82842712] a eig vector:[[-0.92387953 -0.38268343] [ 0.38268343 -0.92387953]]
2.特殊矩阵
import numpy as npa = np.zeros([4,5]) # all zeroprint '\nall zero \n',aa = np.ones([7,6]) # all oneprint '\nall one \n',aa = np.eye(4,7) # 4x7 diagonalprint '\n4x7 diagonal \n',aa = np.diag(range(5)) # 5x5 diagonalprint '\n5x5 diagonal \n',aa = np.empty((2,3))print '\nempty \n',aa = np.arange(10, 30, 5) # array([10, 15, 20, 25]), 1-Dprint '\n array([10, 15, 20, 25]), 1-D \n',aa = np.linspace(0, 2, 9) # 9 numbers from 0 to 2print '\n9 numbers from 0 to 2 \n',aa = np.random.random((2,3)) # random matricsprint '\nrandom matrics \n',aimport numpy as npa = np.zeros([4,5]) # all zeroprint '\nall zero \n',aa = np.ones([7,6]) # all oneprint '\nall one \n',aa = np.eye(4,7) # 4x7 diagonalprint '\n4x7 diagonal \n',aa = np.diag(range(5)) # 5x5 diagonalprint '\n5x5 diagonal \n',aa = np.empty((2,3))print '\nempty \n',aa = np.arange(10, 30, 5) # array([10, 15, 20, 25]), 1-Dprint '\n array([10, 15, 20, 25]), 1-D \n',aa = np.linspace(0, 2, 9) # 9 numbers from 0 to 2print '\n9 numbers from 0 to 2 \n',aa = np.random.random((2,3)) # random matricsprint '\nrandom matrics \n',a
运算结果:
all zero [[ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0.]]all one [[ 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1.] [ 1. 1. 1. 1. 1. 1.]]4x7 diagonal [[ 1. 0. 0. 0. 0. 0. 0.] [ 0. 1. 0. 0. 0. 0. 0.] [ 0. 0. 1. 0. 0. 0. 0.] [ 0. 0. 0. 1. 0. 0. 0.]]5x5 diagonal [[0 0 0 0 0] [0 1 0 0 0] [0 0 2 0 0] [0 0 0 3 0] [0 0 0 0 4]]empty [[ 0.06012241 0.30847312 0.20174074] [ 0.37654373 0.71036135 0.15586512]] array([10, 15, 20, 25]), 1-D [10 15 20 25]9 numbers from 0 to 2 [ 0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ]random matrics [[ 0.44052293 0.42283564 0.44825331] [ 0.66735609 0.32664018 0.17015328]]