有没有更快的方法来分离两个数组的最小值和最大值?

4
In [3]: f1 = rand(100000)
In [5]: f2 = rand(100000)

# Obvious method:
In [12]: timeit fmin = np.amin((f1, f2), axis=0); fmax = np.amax((f1, f2), axis=0)
10 loops, best of 3: 59.2 ms per loop

In [13]: timeit fmin, fmax = np.sort((f1, f2), axis=0)
10 loops, best of 3: 30.8 ms per loop

In [14]: timeit fmin = np.where(f2 < f1, f2, f1); fmax = np.where(f2 < f1, f1, f2)
100 loops, best of 3: 5.73 ms per loop


In [36]: f1 = rand(1000,100,100)

In [37]: f2 = rand(1000,100,100)

In [39]: timeit fmin = np.amin((f1, f2), axis=0); fmax = np.amax((f1, f2), axis=0)
1 loops, best of 3: 6.13 s per loop

In [40]: timeit fmin, fmax = np.sort((f1, f2), axis=0)
1 loops, best of 3: 3.3 s per loop

In [41]: timeit fmin = np.where(f2 < f1, f2, f1); fmax = np.where(f2 < f1, f1, f2)
1 loops, best of 3: 617 ms per loop

比如,也许有一种方法可以在两个where命令中使用2个返回一次完成吗?

如果aminwhere快得多,为什么它没有采用与where相同的实现方式?

1个回答

5
使用numpy内置的逐元素maximumminimum函数-它们比where快。在numpy maximum文档中的注释证实了这一点:

相当于np.where(x1 > x2, x1, x2),但更快且具有正确的广播。

你需要用类似下面的代码运行第一个测试:
fmin = np.minimum(f1, f2); fmax = np.maximum(f1, f2)

我的研究结果表明这个方法更快。请注意,只要两个参数的形状相同,minimummaximum可以在任何n维数组上使用。

Using amax                    3.506
Using sort                    1.830
Using where                   0.635
Using numpy maximum, minimum  0.178

2
等等,什么!?我以为它们是aminamax的同义词,因为某种原因文档甚至没有相互链接。唉,确实快多了。 - endolith

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接