簡體   English   中英

是numpy.einsum的更快替代方法,用於獲取兩個向量列表的“元素方式”的點積?

[英]Faster alternative to numpy.einsum for taking the “element-wise” dot product of two lists of vectors?

假設您獲得了兩個向量數組:

v1 = np.array([ [1, 2], [3, 4] ]) v2 = np.array([ [10, 20], [30, 40]])

我們想生成一個數組,它等效於:

v3 = np.array([ np.dot(v1[0], v2[0]), np.dot(v1[1], v2[1]) ])

目前,我使用:

v3 = np.einsum('ij,ij->i', v1, v2)

但是,我在代碼中做了很多事情 ,因此此處的加速對我非常有幫助。

我們如何加快速度? np.einsum已經非常有效,但是我想知道對於這個特定用例 ,是否有更快的方法?

einsum盡我所能想到的3種選擇中的最佳選擇:

In [73]: timeit v3=np.einsum('ij,ij->i',v1,v2)
100000 loops, best of 3: 5.14 us per loop

In [74]: timeit np.diag(np.dot(v1,v2.T))
100000 loops, best of 3: 7.43 us per loop

In [75]: timeit np.sum(v1*v2,axis=1)
100000 loops, best of 3: 16.8 us per loop

要問的幾個問題:

  • 這個計算真的那么昂貴嗎?
  • 如果比較昂貴,您是否必須經常這樣做?
  • 您可以合並einsum調用-並置數組嗎?

嘗試inner1d

import numpy as np
import cProfile
from numpy.core.umath_tests import inner1d

v1 = np.random.random((10**7,2,))  # 10 million random vectors
v2 = np.random.random((10**7,2,))  # 10 million random vectors
v3 = np.einsum('ij,ij->i', v1, v2) # einsum
v4 = inner1d(v1,v2)                # inner1d (~2x faster than einsum)

cProfile.run("np.einsum('ij,ij->i', v1, v2)") # cProfile: 3 function calls in 0.065 seconds
cProfile.run("inner1d(v1,v2)") # cProfile: 2 function calls in 0.033 seconds

print np.allclose(v3,v4) # Returns True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM