简体   繁体   English

使用 numpy 高效计算多个点积

[英]Efficiently compute multiple dot products with numpy

I am trying to compute many dot products efficiently.我正在尝试有效地计算许多点积。 This post gets really close to what I am trying to do, but I can't quite get it to work. 这篇文章非常接近我想要做的事情,但我无法让它发挥作用。 I have a large list of matrices (a), and a list of vectors (b).我有一个很大的矩阵列表(a)和一个向量列表(b)。 I want to do a series of dot product operations between them.我想在他们之间做一系列的点积操作。 This is what works now:这就是现在的工作:

import numpy as np
a # shape (15000,4,4)
b # shape (15000,4)

out = np.empty((15000,4))

for i in range(15000):
    out[i] = np.dot(a[i],b[i])

All my attempts to adapt np.tensordot or np.einsum from the linked post have failed to give me what I want.我从链接的帖子中调整 np.tensordot 或 np.einsum 的所有尝试都未能给我想要的。 If anyone sees how to do this I would really appreciate it.如果有人看到如何做到这一点,我将不胜感激。

Einstein summation works just fine:爱因斯坦求和工作得很好:

>>> a = np.random.randn(100, 4, 4)
>>> b = np.random.randn(100, 4)
>>> foo = np.einsum('ijk,ik->ij', a, b)
>>> bar = np.zeros_like(foo)
>>> for i, (ai, bi) in enumerate(zip(a, b)):
        bar[i] = np.dot(ai, bi)
>>> np.allclose(foo, bar)
True

To explain the summation a bit, note that you're contracting the last axis of b .为了稍微解释一下总和,请注意您正在收缩b最后一个轴。 So you can think about doing each inner product as if by np.einsum('jk,k->j', a[0], b[0]) .所以你可以考虑用np.einsum('jk,k->j', a[0], b[0])来做每个内积。 But we're doing one for each element of a and b , thus the inclusion of the first axis, which is not contracted.但是我们对ab每个元素都做了一个,因此包含了第一个轴,它没有被收缩。 Hence, ijk,ik->ij .因此, ijk,ik->ij

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

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