numpy 矩阵乘法 n x m * m x p = n x p

numpy Matrix Multiplication n x m * m x p = n x p

我正在尝试将两个 numpy 数组作为矩阵相乘。我希望如果 A 是一个 n x m 矩阵并且 B 是一个 m x p 矩阵,那么 A*B 会产生一个 n x p 矩阵。

此代码创建了一个 5x3 矩阵和一个 3x1 矩阵,正如 shape 属性 验证的那样。我很小心地在两个维度上创建了两个数组。最后一行执行乘法,我希望得到一个 5x1 矩阵。

A = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]])
print(A)
print(A.shape)
B = np.array([[2],[3],[4]])
print(B)
print(B.shape)
print(A*B)

结果

[[1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]
 [5 5 5]]
(5, 3)
[[2]
 [3]
 [4]]
(3, 1)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-38-653ff6c66fb7> in <module>()
      5 print(B)
      6 print(B.shape)
----> 7 print(A*B)

ValueError: operands could not be broadcast together with shapes (5,3) (3,1) 

即使是异常消息也表明内部尺寸(3 和 3)匹配。为什么乘法会抛出异常?我应该如何生成 5x1 矩阵?

我正在使用 Python 3.6.2 和 Jupyter Notebook 服务器 5.2.2。

*运算符提供逐元素乘法,这要求数组的形状相同,或者是'broadcastable'

对于点积,使用 A.dot(B) 或者在许多情况下您可以使用 A @ B(在 Python 3.5;

>>> import numpy as np
>>> A = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]])
>>> B = np.array([[2],[3],[4]])
>>> A @ B
array([[ 9],
       [18],
       [27],
       [36],
       [45]])

要获得更多选项,尤其是处理高维数组,还有 np.matmul