线性代数,比如矩阵乘法、分解、行列式等方阵数学,是所有数组类库的重要组成部分。
In [129]: x = np.array([[1,2,3], [3,4,5]])
In [130]: x
Out[130]:
array([[1, 2, 3],
[3, 4, 5]])
In [131]: y = np.array([[3,4,6],[7,2,9]])
In [132]: y
Out[132]:
array([[3, 4, 6],
[7, 2, 9]])
In [134]: y = np.array([[2,3],[5,6],[9,2]])
In [135]: x.dot(y)
Out[135]:
array([[39, 21],
[71, 43]])
numpy.linalg
拥有一个矩阵分解的标准函数集,以及其他常用函数,例如求逆和行列式求解。
In [136]: from numpy.linalg import inv, qr
In [137]: X = np.random.randn(5, 5)
In [138]: mat = X.T.dot(X)
In [139]: inv(mat)
Out[139]:
array([[ 16.0830843 , -3.09847288, 1.3719282 , -8.02394659,
-2.01368608],
[ -3.09847288, 0.80570115, -0.43573792, 1.59528045, 0.5403839 ],
[ 1.3719282 , -0.43573792, 0.50518134, -0.73008886,
-0.53726275],
[ -8.02394659, 1.59528045, -0.73008886, 4.23739373,
0.85359181],
[ -2.01368608, 0.5403839 , -0.53726275, 0.85359181,
1.14188384]])
In [140]: mat.dot(inv(mat))
Out[140]:
array([[ 1.00000000e+00, -5.69723909e-16, -3.39660391e-16,
1.06402282e-15, -1.51758411e-16],
[ 6.42960955e-16, 1.00000000e+00, -2.86059909e-16,
-9.61835202e-16, -3.87218670e-16],
[ 1.39737022e-15, -1.68904588e-15, 1.00000000e+00,
1.73491222e-16, -2.42876170e-16],
[ -3.04457040e-15, 9.43887510e-17, -5.60042541e-16,
1.00000000e+00, -1.44458002e-15],
[ 7.72274884e-16, -1.27249276e-17, -3.95069353e-17,
1.38063644e-15, 1.00000000e+00]])
In [141]: q, r = qr(mat)
In [142]: r
Out[142]:
array([[-4.04255057, -1.39134664, -6.06580244, -7.56440291, -3.92585523],
[ 0. , -8.33083848, -3.78109366, 2.47164582, 0.3925423 ],
[ 0. , 0. , -4.0276473 , -0.2245597 , -1.98080643],
[ 0. , 0. , 0. , -0.27179383, 0.89687684],
[ 0. , 0. , 0. , 0. , 0.38725626]])
numpy.random
模块填补了Python内建的random
模块的不足,可以高效地生成多种概率分布下的完整样本值数组。使用normal来获得一个 4 × 4 4\times4 4×4的正态分布样本数组:
In [143]: samples = np.random.normal(size=(4,4))
In [144]: samples
Out[144]:
array([[-0.22657084, -0.11345777, -1.10101581, -1.51033461],
[-0.95128159, -1.66971715, -0.90686224, 0.47082015],
[-1.78667954, -0.34068302, -0.60262926, 1.29337839],
[ 0.85877971, -0.10044819, -1.02113362, 2.42169541]])
考虑一个简单的随机漫步,从0开始,步进为1和-1,且两种步进发生的概率相等。以下是使用内建random模块利用纯Python实现的一个1,000步的随机漫步:
import matplotlib.pyplot as plt
position = 0
walk = [position]
steps = 1000
for i in range(steps):
step = 1 if random.randint(0, 1) else -1
position += step
walk.append(position)
print(plt.plot(walk[:100]))
'''
[]
'''