【发布时间】:2018-02-06 00:47:38
【问题描述】:
我正在尝试将两个 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。
【问题讨论】:
-
如果你想要矩阵乘法,你要么需要做
A.dot(B),要么使用介绍的new operator。如果 A 的类型为 np.matrix 或 scipy 稀疏矩阵(其中 A*B 实际上是矩阵乘法)numpy-docs: basic operations,则此行为会有所不同。
标签: python numpy matrix linear-algebra matrix-multiplication