gpt4 book ai didi

python - 提高元素 block 之间差异的性能

转载 作者:行者123 更新时间:2023-11-30 22:21:59 24 4
gpt4 key购买 nike

我有一个相当简单的 block ,它获取两个数组中两个选定元素之间的绝对值差。

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))

我使用绝对差,因为我需要正值,我也可以使用平方差。 bbcc 数组在整个过程中保持不变,但 idx_into_cc 随着每次迭代而变化。

如何提高此代码的性能?

最佳答案

我们可以简单地使用矢量化索引来删除内部循环,就像这样 -

d = np.median(np.abs(bb-cc[idx_into_cc]))

关于python - 提高元素 block 之间差异的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48470221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com