Matrix and Vector Products in Numpy

最近复习了numpy中的数组和广播机制并总结成两篇文章分别为【broadcasting in numpy】和【ndarray in Numpy】。本文总结Numpy提供的几个用于矩阵和向量乘法的线性代数函数。

inner(a, b)

a 和 b的最后一个维度的内积。结果的维度为a.shape[:-1] + b.shape[:-1]

一维数组的内积

1
2
3
4
>>> a = np.array([1,2,3])
>>> b = np.array([0,1,0])
>>> np.inner(a, b)
2

多维数组与一维数组的内积

1
2
3
4
5
>>> a = np.arange(24).reshape((2,3,4))
>>> b = np.arange(4)
>>> np.inner(a, b)
array([[ 14, 38, 62],
[ 86, 110, 134]])

数组与标量

1
2
3
>>> np.inner(np.eye(2), 7)
array([[ 7., 0.],
[ 0., 7.]])

matmul(a, b[, out])

Matrix product of two arrays.

The behavior depends on the arguments in the following way.

  • 如果都是二维数组时 they are multiplied like conventional matrices.
  • 如果a是一维数组, it is promoted to a matrix by prepending a 1 to its dimensions. After matrix multiplication the prepended 1 is removed.
  • 如果b是一维数组, it is promoted to a matrix by appending a 1 to its dimensions. After matrix multiplication the appended 1 is removed.
  • If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.
  • a 和 b都不能是标量(scalar)

两个二维数组

1
2
3
4
5
>>> a = [[1, 0], [0, 1]]
>>> b = [[4, 1], [2, 2]]
>>> np.matmul(a, b)
array([[4, 1],
[2, 2]])

二维数组与一维数组

1
2
3
4
5
6
>>> a = [[1, 0], [0, 1]]
>>> b = [1, 2]
>>> np.matmul(a, b)
array([1, 2])
>>> np.matmul(b, a)
array([1, 2])

dot(a, b[, out])

该函数可以是inner, matmul, multiply三个函数的结合体。

  • 如果a和b有一个是一维数组时,等价于inner(a, b)

  • 如果a和b都是二维数组时,等价于matmul(a, b)

  • 如果a和b有一个是标量时,等价于multiply(a, b)
  • If a is an N-D array and b is an M-D array (where M>=2), it is a sum product over the last axis of a and the second-to-last axis of b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
>>> x = np.arange(12).reshape((3,4))
>>> a = np.arange(4)
>>> b = np.arange(12, 24).reshape((3,4))
>>> c = 10
>>> np.dot(x, a)
array([14, 38, 62])
>>> np.inner(x, a)
array([14, 38, 62])
>>>
>>> np.dot(x, b.T)
array([[ 86, 110, 134],
[302, 390, 478],
[518, 670, 822]])
>>> np.matmul(x, b.T)
array([[ 86, 110, 134],
[302, 390, 478],
[518, 670, 822]])
>>>
>>> np.dot(x, c)
array([[ 0, 10, 20, 30],
[ 40, 50, 60, 70],
[ 80, 90, 100, 110]])
>>> np.multiply(x, c)
array([[ 0, 10, 20, 30],
[ 40, 50, 60, 70],
[ 80, 90, 100, 110]])

vdot(a, b)

计算两个一维向量的 内积 。 如果参数传的是多维数组,则将其 flatten 后计算内积

1
2
3
4
>>> x = np.arange(1, 7).reshape(2, 3)
>>> y = np.arange(2, 8).reshape(2, 3)
>>> np.vdot(x, y) == np.vdot(x.flatten(), y.flatten())
True

outer(a, b[, out])

一维数组与一维数组的外积

1
2
3
4
5
6
>>> m = np.arange(1, 4)
>>> n = np.arange(3, 6)
>>> np.outer(m, n)
array([[ 3, 4, 5],
[ 6, 8, 10],
[ 9, 12, 15]])

参考资料

https://docs.scipy.org/doc/numpy/reference/routines.linalg.html