What is the difference between np.sum and np.add.reduce?

前端 未结 2 1772
挽巷
挽巷 2020-12-30 23:22

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

For example, add.reduce()

相关标签:
2条回答
  • 2020-12-30 23:42

    There is actually one difference that might bite you if you were to blindly refactor from one to the other:

    >>> import numpy as np
    >>> a = np.arange(4).reshape(2, 2)
    >>> 
    >>> np.sum(a)
    6
    >>> np.add.reduce(a)
    array([2, 4])
    >>> 
    

    The axis default values are different!

    0 讨论(0)
  • 2020-12-30 23:51

    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.

    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 is the module where the add ufunc is defined.

    0 讨论(0)
提交回复
热议问题