Donbeo - 1 year ago 305

Python Question

I would like to have a norm 1 numpy array.

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 skearn or numpy?

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

If you're using scikit-learn you can use `sklearn.preprocessing.normalize`

:

```
import numpy as np
from sklearn.preprocessing import normalize
x = np.random.rand(1000)*10
norm1 = x / np.linalg.norm(x)
norm2 = normalize(x[:,np.newaxis], axis=0).ravel()
print np.all(norm1 == norm2)
# True
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**