Numpy two matrices, pairwise dot product of rows [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-17 06:25:25

问题


We are currently working on a python project and have to vectorize a lot due to performance constraints. We end up with the following calculation: We have two numpy arrays of shape (20,6) and want to calculate the pairwise dot product of the rows, i.e. we should obtain a (20,1) matrix in the end, where each row is the scalar obtained by the respective vector dot multiplication.


回答1:


You can multiply the two arrays element wise and then do sum by rows, and then you have an array where each element is a dot product from rows of the two original arrays:

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

(a * b).sum(axis=1)
# array([11, 10])


来源:https://stackoverflow.com/questions/41322618/numpy-two-matrices-pairwise-dot-product-of-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!