一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第10天,点击查看活动详情。
向量与矩阵的计算
【a】向量内积:dot
a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b)
22
【b】向量范数和矩阵范数:np.linalg.norm
在矩阵范数的计算中,最重要的是ord参数,可选值如下:
| ord | norm for matrices | norm for vectors |
|---|---|---|
| None | Frobenius norm | 2-norm |
| 'fro' | Frobenius norm | / |
| 'nuc' | nuclear norm | / |
| inf | max(sum(abs(x), axis=1)) | max(abs(x)) |
| -inf | min(sum(abs(x), axis=1)) | min(abs(x)) |
| 0 | / | sum(x != 0) |
| 1 | max(sum(abs(x), axis=0)) | as below |
| -1 | min(sum(abs(x), axis=0)) | as below |
| 2 | 2-norm (largest sing. value) | as below |
| -2 | smallest singular value | as below |
| other | / | sum(abs(x)ord)(1./ord) |
matrix_target = np.arange(4).reshape(-1,2)
matrix_target
array([[0, 1],
[2, 3]])
np.linalg.norm(matrix_target, 'fro')
3.7416573867739413
np.linalg.norm(matrix_target, np.inf)
5.0
np.linalg.norm(matrix_target, 2)
3.702459173643833
vector_target = np.arange(4)
vector_target
array([0, 1, 2, 3])
np.linalg.norm(vector_target, np.inf)
3.0
np.linalg.norm(vector_target, 2)
3.7416573867739413
np.linalg.norm(vector_target, 3)
3.3019272488946263
【c】矩阵乘法:@
a = np.arange(4).reshape(-1,2)
a
array([[0, 1],
[2, 3]])
b = np.arange(-4,0).reshape(-1,2)
b
array([[-4, -3],
[-2, -1]])
a@b
array([[ -2, -1],
[-14, -9]])