如何将 NumPy 中的数组归一化为单位向量? [英] How to normalize an array in NumPy to a unit vector?
本文介绍了如何将 NumPy 中的数组归一化为单位向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将 NumPy 数组转换为单位向量.更具体地说,我正在寻找此功能的等效版本
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
skearn
或 numpy
中是否有类似的东西?
Is there something like that in skearn
or numpy
?
此函数适用于 v
为 0 向量的情况.
This function works in a situation where v
is the 0 vector.
推荐答案
如果你使用 scikit-learn 你可以使用 sklearn.preprocessing.normalize
:
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
这篇关于如何将 NumPy 中的数组归一化为单位向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文