How to normalize an array in NumPy?

582    Asked by ColemanGarvin in Python , Asked on Apr 14, 2021

Question description - I would like to have the norm of one NumPy array. More specifically, I am looking for an equivalent version of this function

def normalize(v):

norm = np.linalg.norm(v)

if norm == 0:

return v

return v / norm

Is there something like that in sklearn or numpy?

This function works in a situation where v is the 0 vector.

Answered by Coleman Garvin

The numpy normalize of data is important for the fast and smooth training of our machine learning models. Scikit learn, a library of python has sklearn.preprocessing.normalize, that helps to normalize the data easily.

For example:



import numpy as np

from sklearn.preprocessing import normalize

  x = np.random.rand(1000)*10norm1 = x / np.linalg.norm(x)norm2 = normalize(x[:,np.newaxis], axis=0).ravel()print(np.all(norm1 == norm2))# TrueHope this answer helps

Your Answer

Interviews

Parent Categories