Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise minimum of multiple vectors in numpy

Tags:

python

numpy

I know that in numpy I can compute the element-wise minimum of two vectors with

numpy.minimum(v1, v2)

What if I have a list of vectors of equal dimension, V = [v1, v2, v3, v4] (but a list, not an array)? Taking numpy.minimum(*V) doesn't work. What's the preferred thing to do instead?

like image 622
kuzzooroo Avatar asked Sep 01 '16 17:09

kuzzooroo


People also ask

How do you find the minimum value in NumPy?

For finding the minimum element use numpy. min(“array name”) function.

What does [: :] mean on NumPy arrays?

The [:, :] stands for everything from the beginning to the end just like for lists. The difference is that the first : stands for first and the second : for the second dimension. a = numpy. zeros((3, 3)) In [132]: a Out[132]: array([[ 0., 0., 0.], [ 0., 0., 0.], [ 0., 0., 0.]])

What is element-wise multiplication in NumPy?

NumPy multiply() function is used to compute the element-wise multiplication of the two arrays with the same shape or multiply one array with a single numeric value. This function provides several parameters that allow the user to specify what value to multiply with. Use numpy.

What does .all do in NumPy?

all() in Python. The numpy. all() function tests whether all array elements along the mentioned axis evaluate to True.


2 Answers

Convert to NumPy array and perform ndarray.min along the first axis -

np.asarray(V).min(0)

Or simply use np.amin as under the hoods, it will convert the input to an array before finding the minimum along that axis -

np.amin(V,axis=0)

Sample run -

In [52]: v1 = [2,5]

In [53]: v2 = [4,5]

In [54]: v3 = [4,4]

In [55]: v4 = [1,4]

In [56]: V = [v1, v2, v3, v4]

In [57]: np.asarray(V).min(0)
Out[57]: array([1, 4])

In [58]: np.amin(V,axis=0)
Out[58]: array([1, 4])

If you need to final output as a list, append the output with .tolist().

like image 96
Divakar Avatar answered Sep 25 '22 14:09

Divakar


*V works if V has only 2 arrays. np.minimum is a ufunc and takes 2 arguments.

As a ufunc it has a .reduce method, so it can apply repeated to a list inputs.

In [321]: np.minimum.reduce([np.arange(3), np.arange(2,-1,-1), np.ones((3,))])
Out[321]: array([ 0.,  1.,  0.])

I suspect the np.min approach is faster, but that could depend on the array and list size.

In [323]: np.array([np.arange(3), np.arange(2,-1,-1), np.ones((3,))]).min(axis=0)
Out[323]: array([ 0.,  1.,  0.])

The ufunc also has an accumulate which can show us the results of each stage of the reduction. Here's it's not to interesting, but I could tweak the inputs to change that.

In [325]: np.minimum.accumulate([np.arange(3), np.arange(2,-1,-1), np.ones((3,))])
     ...: 
Out[325]: 
array([[ 0.,  1.,  2.],
       [ 0.,  1.,  0.],
       [ 0.,  1.,  0.]])
like image 30
hpaulj Avatar answered Sep 25 '22 14:09

hpaulj