@BruceWang
2018-01-03T17:58:59.000000Z
字数 1485
阅读 1290
NumpyPandasMatplot
*
表示 矩阵乘法, numpy要用dot来实现
import numpy as np
x = np.array([[1.,3.,4.], [4., 6., 4.,]])
y = np.array([[2., 34.], [3, -1], [8, 9]])
x
array([[ 1., 3., 4.],
[ 4., 6., 4.]])
y
array([[ 2., 34.],
[ 3., -1.],
[ 8., 9.]])
x.dot(y) #等价于 np.dot(x,y)
array([[ 43., 67.],
[ 58., 166.]])
np.dot(x,y)
array([[ 43., 67.],
[ 58., 166.]])
np.dot(x, np.ones(3))
array([ 8., 14.])
from numpy.linalg import inv, qr
x = np.random.randn(5,5)
x
array([[-0.25604936, -0.37046846, -0.31466935, 0.32535943, -1.61892552],
[ 1.60670687, 0.66499406, -1.0295848 , 1.63642336, 1.04195686],
[-0.74594367, -1.69804565, 0.11274666, 0.06128499, -1.04758812],
[-1.59361246, -1.1524569 , -0.11915486, 1.17406321, 0.81504085],
[ 0.50660175, -0.84230231, -0.25309318, -0.41806509, -1.68770548]])
mat = x.T.dot(x)
np.round(mat, 2) # 这里round指的是取小数点后几位,2就是取第二位
array([[ 6. , 3.84, -1.6 , 0.42, 0.72],
[ 3.84, 5.5 , -0.41, -0.14, 3.55],
[-1.6 , -0.41, 1.25, -1.81, -0.35],
[ 0.42, -0.14, -1.81, 4.34, 2.78],
[ 0.72, 3.55, -0.35, 2.78, 8.32]])
np.round(inv(mat), 2)
array([[ 2.94, -0.32, 10.36, 4.87, -1.31],
[ -0.32, 0.79, 0.65, 0.65, -0.5 ],
[ 10.36, 0.65, 43.17, 21.17, -6.41],
[ 4.87, 0.65, 21.17, 10.81, -3.41],
[ -1.31, -0.5 , -6.41, -3.41, 1.31]])
np.round(mat.dot(inv(mat)), 2) # 结果应该是1
array([[ 1., 0., 0., 0., 0.],
[ 0., 1., 0., 0., 0.],
[-0., 0., 1., 0., 0.],
[-0., -0., -0., 1., 0.],
[ 0., -0., 0., 0., 1.]])
q, r = qr(mat) # qr 计算的是QR decomposition
np.round(r,2) # numpy.linalg 更多用法查源文件
array([[-7.35, -6.44, 1.93, -1.18, -3.49],
[ 0. , -4.05, -0.62, -0.81, -7.21],
[ 0. , 0. , -1.9 , 5.25, 4.62],
[ 0. , 0. , 0. , 0.66, 2.16],
[ 0. , 0. , 0. , 0. , -0.13]])