numpy.dot如何为一维数组和多维数组工作?

时间:2016-04-20 08:52:10

标签: python numpy

具体来说,为什么以下不起作用

a = np.array([[3],[2],[1],[2]])
b = np.array([1, 2, 5, 2])
np.dot(b,a)

它给出错误:

ValueError: shapes (4,1) and (4,) not aligned: 1 (dim 1) != 4 (dim 0)

但这有效:

np.dot(a,b)

1 个答案:

答案 0 :(得分:1)

>>> b=b.reshape(1,4)    #just reshape b
>>> b
array([[1, 2, 5, 2]])
>>> a
array([[3],
       [2],
       [1],
       [2]])

>>> np.dot(a,b)
array([[ 3,  6, 15,  6],
       [ 2,  4, 10,  4],
       [ 1,  2,  5,  2],
       [ 2,  4, 10,  4]])
>>> np.dot(b,a)
array([[16]])