我想将NumPy数组转换为单位向量。更具体地说,我正在寻找这个归一化函数的等效版本:
def normalize(v):
norm = np.linalg.norm(v)
if norm == 0:
return v
return v / norm
这个函数处理向量v的范数为0的情况。
在sklearn或numpy中是否提供了类似的函数?
我想将NumPy数组转换为单位向量。更具体地说,我正在寻找这个归一化函数的等效版本:
def normalize(v):
norm = np.linalg.norm(v)
if norm == 0:
return v
return v / norm
这个函数处理向量v的范数为0的情况。
在sklearn或numpy中是否提供了类似的函数?
当前回答
如果你想要[0;1]为1d-array,然后使用
(a - a.min(axis=0)) / (a.max(axis=0) - a.min(axis=0))
a是你的一维数组。
一个例子:
>>> a = np.array([0, 1, 2, 4, 5, 2])
>>> (a - a.min(axis=0)) / (a.max(axis=0) - a.min(axis=0))
array([0. , 0.2, 0.4, 0.8, 1. , 0.4])
注意该方法。对于保存值之间的比例有一个限制:一维数组必须至少有一个0,并且由0和正数组成。
其他回答
如果您正在处理3D向量,您可以使用vg工具带简单地做到这一点。它是numpy之上的一个轻量级层,支持单值和堆叠向量。
import numpy as np
import vg
x = np.random.rand(1000)*10
norm1 = x / np.linalg.norm(x)
norm2 = vg.normalize(x)
print np.all(norm1 == norm2)
# True
我在上次创业时创建了这个库,它的动机是这样的:简单的想法在NumPy中太啰嗦了。
如果你想要[0;1]为1d-array,然后使用
(a - a.min(axis=0)) / (a.max(axis=0) - a.min(axis=0))
a是你的一维数组。
一个例子:
>>> a = np.array([0, 1, 2, 4, 5, 2])
>>> (a - a.min(axis=0)) / (a.max(axis=0) - a.min(axis=0))
array([0. , 0.2, 0.4, 0.8, 1. , 0.4])
注意该方法。对于保存值之间的比例有一个限制:一维数组必须至少有一个0,并且由0和正数组成。
如果你在使用scikit-learn,你可以使用sklearn.预处理。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
如果你有多维数据,并希望每个轴都归一化到最大值或总和:
def normalize(_d, to_sum=True, copy=True):
# d is a (n x dimension) np array
d = _d if not copy else np.copy(_d)
d -= np.min(d, axis=0)
d /= (np.sum(d, axis=0) if to_sum else np.ptp(d, axis=0))
return d
使用numpys的峰对峰函数。
a = np.random.random((5, 3))
b = normalize(a, copy=False)
b.sum(axis=0) # array([1., 1., 1.]), the rows sum to 1
c = normalize(a, to_sum=False, copy=False)
c.max(axis=0) # array([1., 1., 1.]), the max of each row is 1
在Christoph Gohlke编写的流行转换模块中,还有函数unit_vector()用于规范化向量:
import transformations as trafo
import numpy as np
data = np.array([[1.0, 1.0, 0.0],
[1.0, 1.0, 1.0],
[1.0, 2.0, 3.0]])
print(trafo.unit_vector(data, axis=1))