Python中的矩阵乘法np.dot, np.multiply 和 *

1. 与线性代数中的矩阵乘法定义相同:np.dot()

np.dot(A, B):对于二维矩阵,计算真正意义上的矩阵乘积,即A的i行元素与B的j列元素相乘的积的和作为新矩阵的(i, j)元素;对于一维矩阵(即向量),计算两向量的内积。

相当于Matlab中的 *,也相当于线性代数中叉乘

矩阵相乘的图示如下:
Python中的矩阵乘法np.dot, np.multiply 和 *

线性代数举例:

A=[123456],       B=[142536] 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]

C=np.dot(A,B)=[14323277] C=np.dot(A, B)= \left[ \begin{matrix} 14 & 32 \\ 32 & 77 \\ \end{matrix} \right]

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=[123456],       B=[135246] 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]
C=np.multiply(A,B)=AB=[161582036] C=np.multiply(A, B)=A*B= \left[ \begin{matrix} 1 & 6 & 15 \\ 8 & 20 & 36 \\ \end{matrix} \right]

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表示范数的种类

参数 说明 计算方法
默认 二范数:L2L_2 x12+x22+...+xn2\sqrt{x^2_1+x^2_2+...+x^2_n}
ord=2 二范数:L2L_2 同上
ord=1 一范数:L1L_1 x1+x2+...+xn\|x_1\|+\|x_2\|+...+\|x_n\|
ord=np.inf 无穷范数:LL_\infty max(x)max(\|x\|)