【发布时间】:2021-01-11 10:59:29
【问题描述】:
这是我正在处理的 Numpy 中的一个简化用例,如何调度一些计算?
def f(x,th1=0.25,th2=0.75):
if x < th1:
return x+10
elif x > th2:
return x+30
else:
return x+20
x 是一个 Numpy 向量
x=np.random.uniform(0,1,10**6)
当然,如果我尝试f(x),我会得到预期的结果
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
现在我可以使用一个简单的循环了:
%%timeit
tmp=[]
for i in range(x.shape[0]):
tmp.append(f(x[i]))
np.array(tmp)
我收到873 ms ± 8.98 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
我也可以使用np.vectorize
fvec=np.vectorize(f)
和
%%timeit
fvec(x)
给248 ms ± 2.45 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)。
但我很确定有人可以使用“面具”来真正提升,或者可能是另一种 numpy 技巧。所以,轮到你了……提前致谢。
【问题讨论】:
标签: python performance numpy