我正在尝试将两个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。
发布于 2018-02-06 09:04:30
*运算符提供元素乘法,这要求数组具有相同的形状,或者是'broadcastable'。
对于点产品,可以使用A.dot(B),或者在很多情况下可以使用A @ B (在Python3.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。
https://stackoverflow.com/questions/48633812
复制相似问题