Python中的矩阵乘法
1. 与线性代数中的矩阵乘法定义相同:np.dot()
np.dot(A, B):对于二维矩阵,计算真正意义上的矩阵乘积,即A的i行元素与B的j列元素相乘的积的和作为新矩阵的(i, j)元素;对于一维矩阵(即向量),计算两向量的内积。
相当于Matlab中的
*
,也相当于线性代数中叉乘
矩阵相乘的图示如下:
线性代数举例:
A = [ 1 2 3 4 5 6 ] ,         B = [ 1 4 2 5 3 6 ] A= \left[ \begin{matrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ \end{matrix} \right] , \,\,\,\,\,\,\, B=\left[ \begin{matrix} 1 & 4 \\ 2 & 5 \\ 3 & 6 \end{matrix} \right] A=[142536],B=⎣⎡123456⎦⎤
C = n p . d o t ( A , B ) = [ 14 32 32 77 ] C=np.dot(A, B)= \left[ \begin{matrix} 14 & 32 \\ 32 & 77 \\ \end{matrix} \right] C=np.dot(A,B)=[14323277]
Python代码举例
import numpy as np
# 2D array A: 2 x 3
A = np.array([[1, 2, 3], [4, 5, 6]])
# 2D array B: 3 x 2
B = np.array([[1, 4], [2, 5], [3, 6]])
# 2D array C: 2 x 2
C = np.dot(A, B)
print(C)
结果如下:
[[14 32]
[32 77]]
假设
A.shape = (n, k), B.shape = (k, m), C = np.dot(A, B)
,那么C.shape = (n, m)
。即第一个矩阵的列数应该与第二个矩阵的行数相等。
2. 对应元素相乘(element-wise product): * 或 np.multiply()
实现对应元素相乘有两种方式,一个是np.multiply(),另外一个是*。
相当于Matlab中的
.*
线性代数举例:
A
=
[
1
2
3
4
5
6
]
,
       
B
=
[
1
3
5
2
4
6
]
A= \left[ \begin{matrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ \end{matrix} \right] , \,\,\,\,\,\,\, B=\left[ \begin{matrix} 1 & 3 & 5 \\ 2 & 4 & 6 \\ \end{matrix} \right]
A=[142536],B=[123456]
C
=
n
p
.
m
u
l
t
i
p
l
y
(
A
,
B
)
=
A
∗
B
=
[
1
6
15
8
20
36
]
C=np.multiply(A, B)=A*B= \left[ \begin{matrix} 1 & 6 & 15 \\ 8 & 20 & 36 \\ \end{matrix} \right]
C=np.multiply(A,B)=A∗B=[186201536]
Python代码举例:
import numpy as np
# 2D array A and B: 2 x 3
A = np.array([[1, 2, 3], [4, 5, 6]])
B = np.array([[1, 3, 5], [2, 4, 6]])
C1 = np.multiply(A, B)
C2 = A * B
print('C1: \n %s' %C1)
print('C2: \n %s' %C2)
结果如下:
C1:
[[ 1 6 15]
[ 8 20 36]]
C2:
[[ 1 6 15]
[ 8 20 36]]
3. np.linalg.norm 求范数
linalg = linear + algebra,norm表示范数,范数是对向量(或矩阵)的度量,是一个标量(scalar)
np.linalg.norm(x, ord = None, axis = None, keepdims = False)
ord表示范数的种类
参数 | 说明 | 计算方法 |
---|---|---|
默认 | 二范数: L 2 L_2 L2 | x 1 2 + x 2 2 + . . . + x n 2 \sqrt{x^2_1+x^2_2+...+x^2_n} x12+x22+...+xn2 |
ord=2 | 二范数: L 2 L_2 L2 | 同上 |
ord=1 | 一范数: L 1 L_1 L1 | ∥ x 1 ∥ + ∥ x 2 ∥ + . . . + ∥ x n ∥ \|x_1\|+\|x_2\|+...+\|x_n\| ∥x1∥+∥x2∥+...+∥xn∥ |
ord=np.inf | 无穷范数: L ∞ L_\infty L∞ | m a x ( ∥ x ∥ ) max(\|x\|) max(∥x∥) |