我想我没有用过
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