代码之家  ›  专栏  ›  技术社区  ›  rishijd

np。sum和np。添加减产,你用什么?

  •  0
  • rishijd  · 技术社区  · 8 年前

    作为背景,请阅读这篇快速的帖子和明确的答案: What is the difference between np.sum and np.add.reduce?

    因此,对于小型阵列,使用 add.reduce 速度更快。让我们看一下我在学习中使用的以下代码,它对2D数组求和:

    a = np.array([[1,4,6],[3,1,2]])
    print('Sum function result =', np.sum(a))
    
    # faster for small array - 
    # print(np.add.reduce(a))
    
    # but the only reduces dimension by 1. So do this repeatedly. I create a copy of x since I keep reducing it:
    x = np.copy(a)
    while x.size > 1:
        x = np.add.reduce(x)
    
    print('Sum with add.reduce =', x)
    

    因此,上面的内容似乎有些过头了——我想最好还是直接使用 sum 当你不知道你的数组的大小时,如果它是一个以上的维度。是否有人使用 添加减少 在生产代码中,如果数组不明显/不小?如果是,为什么?

    欢迎对代码即兴创作发表任何评论。

    1 回复  |  直到 8 年前
        1
  •  3
  •   hpaulj    8 年前

    我想我没有用过 np.add.reduce 什么时候 np.sum arr.sum 也可以。为什么要键入更长的内容来实现微不足道的加速呢。

    考虑中等大小数组上的1轴和:

    In [299]: arr = np.arange(10000).reshape(100,10,5,2)
    
    In [300]: timeit np.sum(arr,axis=0).shape
    20.1 µs ± 547 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    In [301]: timeit arr.sum(axis=0).shape
    17.6 µs ± 22.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    In [302]: timeit np.add.reduce(arr,axis=0).shape
    18 µs ± 300 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    In [303]: 
    

    合计金额 是最快的。很明显,这比 np。总和 因为少了一个级别的函数调用。 np。添加减少 不是更快。

    这个 ufunc.reduce 有自己的位置,尤其是 ufunc 这不等于 sum prod . (似乎我最近对此发表了评论)。

    我想你会发现 np.add.at np.add.reduceat np。添加减少 在SO答案中。那些是 ufunc公司 没有等效方法的构造。

    或搜索关键字,如 keepdims . 这在所有3种构造中都可用,但几乎所有示例都将使用它 总和 reduce .

    在设置这些测试时,我偶然发现了一个我没有意识到的差异:

    In [307]: np.add.reduce(arr).shape    # default axis 0
    Out[307]: (10, 5, 2)
    In [308]: np.sum(arr)     # default axis None
    Out[308]: 49995000
    In [309]: arr.sum()
    Out[309]: 49995000