简体   繁体   English

带有 numpy 的矢量化内积

[英]Vectorized inner product with numpy

I need to compute many inner products for vectors stored in numpy arrays.我需要为存储在 numpy 数组中的向量计算许多内积。

Namely, in mathematical terms,也就是说,在数学上,

V i = Σ k A i,k B i,k V i = Σ k A i,k B i,k

and

C i,j = Σ k A i,k D i,j,k C i,j = Σ k A i,k D i,j,k

I can of course use a loop, but I am wondering whether I could make use of a higher level operator like dot or matmul in a clever way that I haven't thought of.我当然可以使用循环,但我想知道是否可以以一种我没有想到的聪明方式使用更高级别的运算符,如dotmatmul What is bugging me is that np.cross does accept arrays of vector to perform on, but dot and inner don't do what I want.困扰我的是np.cross确实接受要执行的向量数组,但dotinner不做我想要的。

Your mathematical formulas already give you the outline to define the subscript when using np.einsum .您的数学公式已经为您提供了使用np.einsum时定义下标的轮廓。 It is as simple as:它很简单:

V = np.einsum('ij,ik->i', A, B)

which translates to V[i] = sum(A[i][k]*B[i][k]) .这转化为V[i] = sum(A[i][k]*B[i][k])

and

C = np.einsum('ik,ijk->ij', A, D)

ie C[i][j] = sum(A[i][k]*D[i][j][k]C[i][j] = sum(A[i][k]*D[i][j][k]

You can read more about the einsum operator on this other question .您可以在另一个问题上阅读有关einsum运算符的更多信息。

These can be done with element-wise multiplication and sum:这些可以通过逐元素乘法和求和来完成:

Vi = Σk Ai,k Bi,k
V = (A*B).sum(axis=-1)

and

Ci,j = Σk Ai,k Di,j,k
C = (A[:,None,:] * D).sum(axis=-1)

einsum may be faster, but it's a good idea of understand this approach. einsum可能更快,但理解这种方法是个好主意。

To use matmul we have to add dimensions to fit the要使用matmul我们必须添加尺寸以适应

(batch,i,j)@(batch,j,k) => (batch,k)

pattern.图案。 The sum-of-products dimension is j .乘积和维度是j Calculation-wise this is fast, but application here may be a bit tedious.计算方面这很快,但这里的应用可能有点乏味。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM