英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论