Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numpy - summing up a list of vectors

I am trying to sum a list of NumPy vectors in a list. (In this example it's a list of 2 items, but in my case the list can be of any size.) How to sum them into a new vector?

a = np.array([100, 100])
b = np.array([200, 200])
my_list = [a, b]

ab = np.add(my_list)

np.add(a, b) works, but it's not a list. I have already tried np.add(*my_list) and np.add(np.array(my_list)) as well as np.add(np.array([my_list])), but without any success. What would be the correct way to do this? Thanks!

like image 295
adamvagyok Avatar asked Dec 27 '15 12:12

adamvagyok


1 Answers

Solution 1 np.add.reduce()

You can use the reduce attribute of np.add:

a = np.array([100, 100])
b = np.array([200, 200])
c = np.array([1000, 2000])
L = [a, b, c]
np.add.reduce(L)

results in:

array([1300, 2300])

All universal function that take two in-arguments have a reduce attribute, that applies this function like reduce, i.e.:

np.add.reduce(L)

becomes:

np.add(np.add(L[0], L[1]), L[2])

Add more parenthesis and appropriate np.add calls if the list L gets larger.

From the docs:

Docstring:

  reduce(a, axis=0, dtype=None, out=None, keepdims=False)

Reduces a's dimension by one, by applying ufunc along one axis.

Solution 2 np.sum()

Alternatively, you can use np.sum along the first axis:

>>> np.sum(L, axis=0)
array([1300, 2300

Performance

The performance of both seems to be the same.

For small arrays:

a = np.array([100, 100])
b = np.array([200, 200])
c = np.array([1000, 2000])
L = [a, b, c, a, b, c, a, b, c]

reduce is a little bit faster:

%timeit np.sum(L, axis=0)

10000 loops, best of 3: 20.7 µs per loop

%timeit np.add.reduce(L)
100000 loops, best of 3: 15.7 µs per loop

For large arrays:

size = int(1e6)
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)
L = [a, b, c, a, b, c, a, b, c]

There is no difference:

%timeit np.sum(L, axis=0)
10 loops, best of 3: 41.5 ms per loop

%timeit np.add.reduce(L)
10 loops, best of 3: 41.9 ms per loop
like image 195
Mike Müller Avatar answered Sep 24 '22 15:09

Mike Müller