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

ris*_*ijd 1 python numpy

作为背景,请阅读这篇快速文章和明确的答案: 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)
Run Code Online (Sandbox Code Playgroud)

所以,上面的内容似乎有点矫枉过正——我认为当你不知道数组的大小时最好使用它sum,并且绝对如果它超过一维。add.reduce如果您的数组不明显/不小,有人会在生产代码中使用吗?如果是这样,为什么?

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

hpa*_*ulj 5

我不认为我曾经使用过np.add.reducenp.sumarr.sum做得同样好。为什么要为了一点点加速而输入更长的内容呢?

\n\n

考虑适度大小的数组上的 1 轴总和:

\n\n
In [299]: arr = np.arange(10000).reshape(100,10,5,2)\n\nIn [300]: timeit np.sum(arr,axis=0).shape\n20.1 \xc2\xb5s \xc2\xb1 547 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 10000 loops each)\nIn [301]: timeit arr.sum(axis=0).shape\n17.6 \xc2\xb5s \xc2\xb1 22.7 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\nIn [302]: timeit np.add.reduce(arr,axis=0).shape\n18 \xc2\xb5s \xc2\xb1 300 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 100000 loops each)\nIn [303]: \n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n

ufunc.reduce有其一席之地,特别是对于ufunc没有相当于sum或的情况prod。(似乎我最近对此发表了评论)。

\n\n

我怀疑你会发现np.add.ator的用途np.add.reduceatnp.add.reduceSO 答案更多。这些是ufunc没有等效方法的构造。

\n\n

或者搜索类似的关键字keepdims。这对于所有 3 个结构都可用,但几乎所有示例都将其与sum, not 一起使用reduce

\n\n

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

\n\n
In [307]: np.add.reduce(arr).shape    # default axis 0\nOut[307]: (10, 5, 2)\nIn [308]: np.sum(arr)     # default axis None\nOut[308]: 49995000\nIn [309]: arr.sum()\nOut[309]: 49995000\n
Run Code Online (Sandbox Code Playgroud)\n