numpy 矩阵乘法 nxm * mxp = nxp

Jac*_*rry 2 python numpy matrix linear-algebra matrix-multiplication

我正在尝试将两个 numpy 数组作为矩阵相乘。我期望 ifA是一个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)
Run Code Online (Sandbox Code Playgroud)

结果

[[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) 
Run Code Online (Sandbox Code Playgroud)

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

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

Mat*_*all 5

*运算符提供元素乘法,这要求数组具有相同的形状,或者是“可广播的”

对于点积,请使用A.dot(B)或 在许多情况下您可以使用A @ B(在 Python 3.5 中;了解它与dot.

>>> 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]])
Run Code Online (Sandbox Code Playgroud)

对于更多选项,特别是处理高维数组,还有np.matmul.