# How to normalize an array in NumPy?

### Machine Learning

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.

### Replies

The below code can be used to normalize an array in NumPy.

x = np.random.rand(1000)*10

norma = x / np.linalg.norm(x)

normb = normalize(x[:,np.newaxis], axis=0).ravel()

print np.all(norma == normb)

# True

Here is the code that can give you optimal performance.

import numpy as np

def normalized(a, axis=-1, order=2):

l2 = np.atleast_1d(np.linalg.norm(a, order, axis))

l2[l2==0] = 1

return a / np.expand_dims(l2, axis)

A = np.random.randn(3,3,3)

print(normalized(A,0))

print(normalized(A,1))

print(normalized(A,2))

print(normalized(np.arange(3)[:,None]))

print(normalized(np.arange(3)))

If you want to unleash your potential in this competitive field, please visit the Machine Learning course page for more information, where you can find the Machine Learning tutorials and Machine Learning frequently asked interview questions and answers as well.

This topic has been locked/unapproved. No replies allowed

Login to participate in this discussion.