import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([5, 6])
a.dot(b)
b.dot(a)
a.dot(b) 和 b.dot(a) 会怎样?对于矩阵乘法,a.dot(b) 应该是非法的。
最佳答案
在此设置中,b.dot(a)
等同于 b.T.dot(a)
;事实上,b
和 b.T
恰好具有相同的形状,所以尽管符号使它看起来像 b
是一个行向量,但它实际上不是。但是,我们可以将其重新定义为明确地表现为行向量,在这种情况下操作会按预期失败:
In [25]: b.dot(a)
Out[25]: array([23, 34])
In [26]: b.T.dot(a)
Out[26]: array([23, 34])
In [30]: b.shape
Out[30]: (2,)
In [31]: b.T.shape
Out[31]: (2,)
In [27]: c = b.reshape((1, 2))
In [28]: c.dot(a)
Out[28]: array([[23, 34]])
In [29]: a.dot(c)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-29-5d91888f8066> in <module>()
----> 1 a.dot(c)
ValueError: shapes (2,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)
关于numpy - numpy.dot 函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43451249/