Python 提高元素间差异块的性能
我有一个相当简单的块,它从两个数组中获得两个选定元素之间的绝对值差Python 提高元素间差异块的性能,python,performance,numpy,Python,Performance,Numpy,我有一个相当简单的块,它从两个数组中获得两个选定元素之间的绝对值差 import numpy as np # Input data with proper format. N_bb, N_cc = np.random.randint(1e5), np.random.randint(1e5) bb = np.random.uniform(0., 1., N_bb) cc = np.random.uniform(0., 1., N_cc) # My actual code repeats thi
import numpy as np
# Input data with proper format.
N_bb, N_cc = np.random.randint(1e5), np.random.randint(1e5)
bb = np.random.uniform(0., 1., N_bb)
cc = np.random.uniform(0., 1., N_cc)
# My actual code repeats this process ~500 times.
all_ds = []
for _ in range(500):
# An index into cc for each element in bb.
idx_into_cc = np.random.randint(0, len(cc), len(bb))
# This is the block I need to make faster.
aa = []
for i, b in enumerate(bb):
aa.append(abs(b - cc[idx_into_cc[i]]))
d = np.median(aa)
# Use 'd' before the next iteration, and store the result.
all_ds.append(some_func(d))
我使用绝对差,因为我需要正值,我也可以使用平方差。bb
和cc
数组在整个过程中保持不变,但是idx\u-into\u-cc
随着每次迭代而变化
如何提高这段代码的性能?我们可以简单地使用矢量化索引来删除内部循环,如下所示-
d = np.median(np.abs(bb-cc[idx_into_cc]))
可能在循环开始之前将
aa
初始化为其完整大小,然后使用索引而不是append
?我可以想象,在引擎盖下更有效地实现这一点。将最后一行替换为d=np.median(np.abs(bb-cc[idx\u-into\u-cc])
以删除内环?好吧,这太简单了。现在我很惭愧我没有想到这一点(一定是我在工作的第11个小时…)非常感谢Divakar,你想把你的cmmt变成一个答案吗?矢量化索引?NumPy称之为花式索引;)(简单地说,就是使用数组索引数组)