# Python之numpy教程（六）：线性代数、随机数

1319人阅读 评论(0)

1.用dot函数计算矩阵乘积

x = np.array([[1.,2.,3.],[4.,5.,6.]])
y = np.array([[6.,23.],[-1,7],[8,9]])
x

array([[ 1.,  2.,  3.],
[ 4.,  5.,  6.]])
y

array([[  6.,  23.],
[ -1.,   7.],
[  8.,   9.]])
x.dot(y) # 相当于np.dot(x,y)

array([[  28.,   64.],
[  67.,  181.]])

2.
np.ones(3)

array([ 1.,  1.,  1.])
np.dot(x,np.ones(3))

array([  6.,  15.])

3.计算逆矩阵：inv函数

from numpy.linalg import inv, qr
X = np.random.randn(5,5)
mat = X.T.dot(X)
inv(mat)

array([[  3.09810926e+00,   9.66906262e-02,  -6.71590697e-01,
1.76863564e+00,   6.95340665e-01],
[  9.66906262e-02,   1.82492276e-01,  -2.12923224e-01,
3.39846096e-01,  -1.55992532e-03],
[ -6.71590697e-01,  -2.12923224e-01,   6.62563230e-01,
-9.28381212e-01,  -1.94807430e-01],
[  1.76863564e+00,   3.39846096e-01,  -9.28381212e-01,
2.07619786e+00,   3.63450776e-01],
[  6.95340665e-01,  -1.55992532e-03,  -1.94807430e-01,
3.63450776e-01,   2.98244346e-01]])
mat.dot(inv(mat))

array([[  1.00000000e+00,  -9.54097912e-18,   0.00000000e+00,
0.00000000e+00,  -1.11022302e-16],
[ -4.44089210e-16,   1.00000000e+00,   1.11022302e-16,
0.00000000e+00,   0.00000000e+00],
[ -2.22044605e-16,  -7.02563008e-17,   1.00000000e+00,
1.11022302e-16,   0.00000000e+00],
[  1.11022302e-16,  -2.37006595e-16,   2.22044605e-16,
1.00000000e+00,  -5.55111512e-17],
[ -8.88178420e-16,  -1.11022302e-16,  -4.44089210e-16,
-4.44089210e-16,   1.00000000e+00]])

4.qr函数计算OR分解
q, r = qr(mat)
r

array([[ -2.72698131,  -0.85635373,   3.8710866 ,   3.06751167,
7.55827106],
[  0.        , -11.90081274,  -4.41399286,   0.86802486,
-4.83999815],
[  0.        ,   0.        ,  -3.80739854,  -2.01002972,
1.07068051],
[  0.        ,   0.        ,   0.        ,  -0.79327916,
2.42858942],
[  0.        ,   0.        ,   0.        ,   0.        ,
1.16051992]])

5.常用numpy.linalg函数汇总：

6.用normal函数生产随机正态分布样本：

sample = np.random.normal(size=(4,4))
sample

array([[-1.47203302, -1.6101196 ,  0.24138146,  1.22912807],
[-0.15997584, -0.32986161, -1.06285386,  0.89258052],
[-1.97772238,  0.17555981,  0.14792538, -2.54519949],
[-0.31237017,  0.58656156, -0.01663986,  1.49902958]])

7.numpy随机函数汇总：

0
0

个人资料
• 访问：148982次
• 积分：2125
• 等级：
• 排名：千里之外
• 原创：100篇
• 转载：1篇
• 译文：0篇
• 评论：3条
文章分类
阅读排行
最新评论