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?
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.
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.
Python numpy. zeros() function returns a new array of given shape and type, where the element's value as 0.
If you can do the normalization in place, you can use your boolean indexing array like this:
nonzero = norms > 0
x[nonzero] /= norms[nonzero]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With