Numpy 计算 N 维向量数组的点积

huangapple go评论52阅读模式
英文:

Numpy compute dot product of arrays of N-d vectors

问题

I want to compute a dot product of an array of vectors stored as rows using Numpy. Given a and b each array of M vectors of 2 components with both of shapes as (M, 2). I want to compute ab^T along axis 0.

我想使用Numpy计算一个以行向量存储的数组的点积。给定的a和b分别是包含2个分量的M个向量的数组,它们的形状都是(M, 2)。我想沿着轴0计算ab^T

I did tried the following which seems to work by writing the product as matrix product on paper but I feel there must exists a better way without the need of allocating a matrix.

我尝试了以下方法,似乎通过在纸上将乘积表示为矩阵乘积可以工作,但我觉得必须存在一种更好的方法,而不需要分配一个矩阵。

My current version:

我的当前版本:

np.diag( ( a @ b[:, :, None]).reshape(a.shape[0], a.shape[0]) )

英文:

I want to compute a dot product of an array of vectors stored as rows using Numpy. Given a and b each array of M vectors of 2 components with both of shapes as (M, 2). I want to compute ab^T along axis 0.

I did tried the following which seems to work by writing the product as matrix product on paper but I feel there must exists a better way without the need of allocating a matrix.

My current version:

np.diag( ( a @ b[:, :, None]).reshape(a.shape[0], a.shape[0]) )

答案1

得分: 1

np.einsum('ij,ij->i', a, b)

英文:

It turns out I encountered the einsum function which with the bellow indexes produces the same result as my first try:

np.einsum('ij,ij->i', a, b)

huangapple
  • 本文由 发表于 2023年3月31日 20:03:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定