问题
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