StackOverflow

### Answer rating: 204

I would like to convert a NumPy array to a unit vector. 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 `skearn`

or `numpy`

?

This function works in a situation where `v`

is the 0 vector.

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
```

In the summer of 2008, after three decades of building software in corporate data centers, I walked away from corporate America to take a stab at building a technology company from the ground up based...

10/07/2020

I have developed this book to investigate Mesos-based cluster development and integration. I found that data center operating system (DCOS; and it’s command-line interface [CLI]) was a natural progr...

10/07/2020

While there is no arguing about the staying power of the cloud model and the benefits it can bring to any organization or government, mainstream adoption depends on several key variables falling into ...

10/07/2020

Learn how data literacy is changing the world and giving you a better understanding of life's biggest problems in this "Important and Comprehensive" Guide to Statistical Thinking (New York). The bi...

28/08/2021

X
# Submit new EBook