我正在尝试将两个 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 中;read how it differs from 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]])
对于更多选项,特别是处理高维数组,还有 np.matmul
.
关于python - numpy 矩阵乘法 n x m * m x p = n x p,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633812/