最近复习了numpy中的数组和广播机制并总结成两篇文章分别为【broadcasting in numpy】和【ndarray in Numpy】。本文总结Numpy提供的几个用于矩阵和向量乘法的线性代数函数。
a 和 b的最后一个维度的内积。结果的维度为a.shape[:-1] + b.shape[:-1]
一维数组的内积
1 | 1,2,3]) a = np.array([ |
多维数组与一维数组的内积
1 | 24).reshape((2,3,4)) a = np.arange( |
数组与标量
1 | 2), 7) np.inner(np.eye( |
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 | 1, 0], [0, 1]] a = [[ |
二维数组与一维数组
1 | 1, 0], [0, 1]] a = [[ |
该函数可以是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 (whereM>=2
), it is a sum product over the last axis of a and the second-to-last axis of b
1 | 12).reshape((3,4)) x = np.arange( |
计算两个一维向量的 内积 。 如果参数传的是多维数组,则将其 flatten
后计算内积
1 | 1, 7).reshape(2, 3) x = np.arange( |
一维数组与一维数组的外积
1 | 1, 4) m = np.arange( |
参考资料
https://docs.scipy.org/doc/numpy/reference/routines.linalg.html