numpy矩阵乘法形状

时间:2013-08-15 15:03:55

标签: python numpy matrix-multiplication

在矩阵乘法中,假设A是3 x 2矩阵(3行,2列),B是2 x 4矩阵(2行,4列),那么如果矩阵C = A * B,然后C应该有3行4列。 numpy为什么不做这个乘法?当我尝试以下代码时出现错误:ValueError: operands could not be broadcast together with shapes (3,2) (2,4)

a = np.ones((3,2))
b = np.ones((2,4))
print a*b

我尝试转置A和B,alwasy得到相同的答案。为什么?在这种情况下如何进行矩阵乘法?

1 个答案:

答案 0 :(得分:16)

numpy数组的*运算符是元素乘法(类似于同一维数组的Hadamard乘积),而不是矩阵乘法。

例如:

>>> a
array([[0],
       [1],
       [2]])
>>> b
array([0, 1, 2])
>>> a*b
array([[0, 0, 0],
       [0, 1, 2],
       [0, 2, 4]])

对于使用numpy数组的矩阵乘法:

>>> a = np.ones((3,2))
>>> b = np.ones((2,4))
>>> np.dot(a,b)
array([[ 2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.],
       [ 2.,  2.,  2.,  2.]])

此外,您可以使用矩阵类:

>>> a=np.matrix(np.ones((3,2)))
>>> b=np.matrix(np.ones((2,4)))
>>> a*b
matrix([[ 2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.],
        [ 2.,  2.,  2.,  2.]])

可以找到有关广播numpy数组的更多信息here,可以找到有关矩阵类的更多信息here