【问题标题】:Is there a faster way to separate the minimum and maximum of two arrays?有没有更快的方法来分隔两个数组的最小值和最大值?
【发布时间】:2013-05-10 19:02:35
【问题描述】:
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 个?

为什么amin 的实现方式与where 不同,如果它快得多?

【问题讨论】:

    标签: python numpy where minimum


    【解决方案1】:

    使用 numpy 的内置元素 maximumminimum - 它们比 where 快​​。 numpy docs for 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
    

    【讨论】:

    • 等等,什么!?出于某种原因,我认为这些是aminamax 的同义词。这些文档甚至没有相互链接。叹。这确实快得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多