Np.sum and np.add.reduce - in production, what do you use?

As a background, please read this quick post and the clear answer: What is the difference between np.sum and np.add.reduce?

So, for a small array, usage add.reduceis faster. Take the following code that I experimented with for training, which summarizes a 2D array:

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)

So, the above seems redundant - I believe that it is better to use sumwhen you do not know the size of your array, and definitely if it is more than one dimension. Does anyone use add.reducein production code if your array is not obvious / small? If so, why?

Any comments on code improvisation are welcome.

-1
source share
1

, 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]: 

arr.sum . , np.sum, . np.add.reduce .

ufunc.reduce , ufunc, sum prod. (, ).

, np.add.at np.add.reduceat, np.add.reduce SO. ufunc , .

, keepdims. 3 , sum, 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
+1

Source: https://habr.com/ru/post/1694029/


All Articles