np.sum 和 np.add.reduce - 在生产中,你用​​什么?

2023-12-12

作为背景,请阅读这篇快速帖子和明确的答案:np.sum 和 np.add.reduce 有什么区别?

因此,对于小数组,使用add.reduce是比较快的。让我们看一下我为了学习而试验的以下代码,它对一个二维数组求和:

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当您不知道数组的大小,并且绝对不知道它是否超过一维时。有人用吗add.reduce在生产代码中,如果您的数组不明显/小?如果是这样,为什么?

欢迎对代码即兴创作提出任何意见。


我不认为我用过np.add.reduce when np.sum or 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]: 

arr.sum是最快的。显然它胜过np.sum因为少了一层函数调用。np.add.reduce并没有更快。

The ufunc.reduce有它的一席之地,特别是对于ufunc没有相当于sum or prod。 (好像我最近对此发表了评论)。

我怀疑你会发现更多用途np.add.at or np.add.reduceat than np.add.reduce在这样的答案中。那些是ufunc没有等效方法的构造。

或者搜索类似的关键字keepdims。这对于所有 3 个结构都可用,但几乎所有示例都将使用它sum, not 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

np.sum 和 np.add.reduce - 在生产中,你用​​什么? 的相关文章

随机推荐