如何在Python中计算两个向量数组的点积? [英] how to calculate the dot product of two arrays of vectors in python?
问题描述
A and B
都是带有shape(N,3)
的数组.它们每个都包含N个向量,这样A[0] = a0 (vector), A[1] = a1...
和B[0] = b0, B[1] = b1...
A and B
are both arrays with shape(N,3)
. They each contain N vectors such that A[0] = a0 (vector), A[1] = a1...
and B[0] = b0, B[1] = b1...
我想计算N对向量an和bn的点积.换句话说,我想使用shape(N,1)
获取数组C,以使C[i] = np.dot(A[i],B[i]).
在python中执行此操作的最有效方法是什么(例如,使用矢量化代码)?
I want to calculate the dot product of the N pairs of vectors an and bn. In other words, I want to obtain an array C with shape(N,1)
such that C[i] = np.dot(A[i],B[i]).
What is the most efficient way of doing this in python (e.g. using vectorized code)?
推荐答案
您可以执行逐元素乘法,然后沿第二个轴求和,就像这样-
You can perform element-wise multiplication and then sum along the second axis, like so -
C = (A*B).sum(1)
可以使用 np.einsum
,就像这样-
These multiplication and summation operations can be implemented in one go with np.einsum
, like so -
C = np.einsum('ij,ij->i',A,B)
这篇关于如何在Python中计算两个向量数组的点积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!