gpt4 book ai didi

python - 提高 numpy 数组上复杂逻辑条件的性能

转载 作者:行者123 更新时间:2023-12-01 08:09:49 24 4
gpt4 key购买 nike

我需要在大型 2D“NUMPY”数组上评估许多逻辑条件,并将总体结果收集在 bool “RESULT”numpy 数组中。

所有条件都与 AND 语句链接的简单示例可能是:

结果= cond1(NUMPY) & cond2(NUMPY) & cond3(NUMPY) & ....

我想了解是否有办法优化性能。

例如,在本例中,如果 NUMPY 数组中的大多数值的第一个条件 (cond1) 为 False,则评估这些值的所有其他条件将浪费资源,因为 AND 条件无论如何都会生成 False在最终的 RESULT 数组中。

有什么想法吗?

最佳答案

您可以手动进行短路,但我应该补充一点,这可能只在相当极端的情况下才值得。

这是 99 个链接逻辑与的示例。短路可以使用 where 关键字或使用奇特的索引来完成。第二个(但不是第一个)为本示例提供了不错的速度。

import numpy as np

a = np.random.random((1000,))*1.5
c = np.random.random((100, 1))*1.5

def direct():
return ((a+c) < np.arccos(np.cos(a+c)*0.99)).all(0)

def trickya():
out = np.ones(a.shape, '?')
for ci in c:
np.logical_and(out, np.less(np.add(a, ci, where=out), np.arccos(np.multiply(np.cos(np.add(a, ci, where=out), where=out), 0.99, where=out), where=out), where=out), out=out, where=out)
return out

def trickyb():
idx, = np.where((a+c[0]) < np.arccos(np.cos(a+c[0])*0.99))
for ci in c[1:]:
idx = idx[(a[idx]+ci) < np.arccos(np.cos(a[idx]+ci)*0.99)]
out = np.zeros(a.shape, '?')
out[idx] = True
return out

assert (direct()==trickya()).all()
assert (direct()==trickyb()).all()

from timeit import timeit

print('direct ', timeit(direct, number=100))
print('where kw', timeit(trickya, number=100))
print('indexing', timeit(trickyb, number=100))

示例运行:

direct   0.49512664100620896
where kw 0.494946873979643
indexing 0.17760096595156938

关于python - 提高 numpy 数组上复杂逻辑条件的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55325419/

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