我想将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中是否提供了类似的函数?
当前回答
我同意,如果这样的函数是包含的库的一部分,那就太好了。但据我所知,不是这样的。这是一个任意轴都能给出最佳性能的版本。
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)))
其他回答
如果你有多维数据,并希望每个轴都归一化到最大值或总和:
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
如果你在使用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
如果你想将存储在3D张量中的n维特征向量归一化,你也可以使用PyTorch:
import numpy as np
from torch import FloatTensor
from torch.nn.functional import normalize
vecs = np.random.rand(3, 16, 16, 16)
norm_vecs = normalize(FloatTensor(vecs), dim=0, eps=1e-16).numpy()
我同意,如果这样的函数是包含的库的一部分,那就太好了。但据我所知,不是这样的。这是一个任意轴都能给出最佳性能的版本。
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)))
如果你使用多维数组,快速解决是可能的。
假设我们有一个二维数组,我们想用最后一个轴归一化,而有些行有零范数。
import numpy as np
arr = np.array([
[1, 2, 3],
[0, 0, 0],
[5, 6, 7]
], dtype=np.float)
lengths = np.linalg.norm(arr, axis=-1)
print(lengths) # [ 3.74165739 0. 10.48808848]
arr[lengths > 0] = arr[lengths > 0] / lengths[lengths > 0][:, np.newaxis]
print(arr)
# [[0.26726124 0.53452248 0.80178373]
# [0. 0. 0. ]
# [0.47673129 0.57207755 0.66742381]]