numpy矩阵乘法形状 [英] numpy matrix multiplication shapes
问题描述
在矩阵乘法中,假设A
是3 x 2矩阵(3行2列),而B
是2 x 4矩阵(2行4列),则如果矩阵C
应该具有3行4列.为什么numpy不做这个乘法?当我尝试以下代码时,出现错误:ValueError: operands could not be broadcast together with shapes (3,2) (2,4)
In matrix multiplication, assume that the A
is a 3 x 2 matrix (3 rows, 2 columns ) and B
is a 2 x 4 matrix (2 rows, 4 columns ), then if a matrix C = A * B
, then C
should have 3 rows and 4 columns. Why does numpy not do this multiplication? When I try the following code I get an error : 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,并得到相同的答案.为什么?在这种情况下如何进行矩阵乘法?
I try with transposing A and B and alwasy get the same answer. Why? How do I do the matrix multiplication in this case?
推荐答案
用于numpy数组的*
运算符是逐元素乘法(类似于相同维度数组的Hadamard乘积),而不是矩阵乘法.
The *
operator for numpy arrays is element wise multiplication (similar to the Hadamard product for arrays of the same dimension), not matrix multiply.
例如:
>>> a
array([[0],
[1],
[2]])
>>> b
array([0, 1, 2])
>>> a*b
array([[0, 0, 0],
[0, 1, 2],
[0, 2, 4]])
对于与numpy数组相乘的矩阵:
For matrix multiply with numpy arrays:
>>> 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.]])
此外,您可以使用矩阵类:
In addition you can use the matrix class:
>>> 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数组的更多信息,请参见此处,有关以下内容的更多信息可以在此处找到该矩阵类.
More information on broadcasting numpy arrays can be found here, and more information on the matrix class can be found here.
这篇关于numpy矩阵乘法形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!