np.sum和np.add.reduce有什么区别? [英] What is the difference between np.sum and np.add.reduce?

查看:125
本文介绍了np.sum和np.add.reduce有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

np.sumnp.add.reduce有什么区别?
虽然文档非常明确:

What is the difference between np.sum and np.add.reduce?
While the docs are quite explicit:

例如,add.reduce()等同于sum().

For example, add.reduce() is equivalent to sum().

两者的性能似乎完全不同:对于相对较小的数组大小,add.reduce的速度大约快两倍.

The performance of the two seems to be quite different: for relatively small array sizes add.reduce is about twice faster.

$ python -mtimeit -s"import numpy as np; a = np.random.rand(100); summ=np.sum" "summ(a)"
100000 loops, best of 3: 2.11 usec per loop
$ python -mtimeit -s"import numpy as np; a = np.random.rand(100); summ=np.add.reduce" "summ(a)"
1000000 loops, best of 3: 0.81 usec per loop

$ python -mtimeit -s"import numpy as np; a = np.random.rand(1000); summ=np.sum" "summ(a)"
100000 loops, best of 3: 2.78 usec per loop
$ python -mtimeit -s"import numpy as np; a = np.random.rand(1000); summ=np.add.reduce" "summ(a)"
1000000 loops, best of 3: 1.5 usec per loop

对于更大的数组大小,差异似乎消失了:

For larger array sizes, the difference seems to go away:

$ python -mtimeit -s"import numpy as np; a = np.random.rand(10000); summ=np.sum" "summ(a)"
100000 loops, best of 3: 10.7 usec per loop
$ python -mtimeit -s"import numpy as np; a = np.random.rand(10000); summ=np.add.reduce" "summ(a)"
100000 loops, best of 3: 9.2 usec per loop

推荐答案

简短的回答:当参数是一个numpy数组时,np.sum最终会调用add.reduce来完成工作.处理参数并分配给add.reduce的开销是为什么np.sum较慢的原因.

Short answer: when the argument is a numpy array, np.sum ultimately calls add.reduce to do the work. The overhead of handling its argument and dispatching to add.reduce is why np.sum is slower.

更长的答案: np.sum numpy/core/fromnumeric.py 中定义.在np.sum的定义中,您将 看到工作已传递到_methods._sum.在 _methods.py 中的该函数很简单:

Longer answer: np.sum is defined in numpy/core/fromnumeric.py. In the definition of np.sum, you'll see that the work is passed on to _methods._sum. That function, in _methods.py, is simply:

def _sum(a, axis=None, dtype=None, out=None, keepdims=False):
    return um.add.reduce(a, axis=axis, dtype=dtype,
                            out=out, keepdims=keepdims)

um是定义add ufunc的模块.

um is the module where the add ufunc is defined.

这篇关于np.sum和np.add.reduce有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆