Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with zeros in numpy array normalization

Tags:

python

numpy

I have a numpy array of 2D vectors, which I am trying to normalize as below. The array can have vectors with magnitude zero.

x = np.array([[0.0, 0.0], [1.0, 0.0]])
norms = np.array([np.linalg.norm(a) for a in x])

>>> x/norms
array([[ nan,   0.],
       [ inf,   0.]])

>>> nonzero = norms > 0.0
>>> nonzero
array([False,  True], dtype=bool)

Can I somehow use nonzero to apply the division only to x[i] such that nonzero[i] is True? (I can write a loop for this - just wondering if there's a numpy way of doing this)

Or is there a better way of normalizing the array of vectors, skipping all zero vectors in the process?

like image 822
M-V Avatar asked Jul 21 '13 05:07

M-V


People also ask

How do I normalize data between 0 and 1 in Python?

In Python, sklearn module provides an object called MinMaxScaler that normalizes the given data using minimum and maximum values. Here fit_tranform method scales the data between 0 and 1 using the MinMaxScaler object.

How do you normalize values in a NumPy array?

In order to normalize a vector in NumPy, we can use the np. linalg. norm() function, which returns the vector's norm value. We can then use the norm value to divide each value in the array to get the normalized array.

What is the use of the zeros () function in NumPy array?

Python numpy. zeros() function returns a new array of given shape and type, where the element's value as 0.


1 Answers

If you can do the normalization in place, you can use your boolean indexing array like this:

nonzero = norms > 0
x[nonzero] /= norms[nonzero]
like image 111
Jaime Avatar answered Sep 19 '22 20:09

Jaime