numpy.dot函数如何工作?

时间:2017-04-17 12:11:39

标签: numpy

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)应该是非法的。

1 个答案:

答案 0 :(得分:2)

在此设置中,b.dot(a)相当于b.T.dot(a);实际上,bb.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)
相关问题