我想将 NumPy 数组转换为单位向量。更具体地说,我正在寻找此标准化函数的等效版本:
def normalize(v):
norm = np.linalg.norm(v)
if norm == 0:
return v
return v / norm
此函数处理向量
v
的范数值为 0 的情况。
sklearn
或numpy
有类似的功能吗?
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
我同意,如果这样的函数是包含的库的一部分,那就太好了。但据我所知,事实并非如此。因此,这是一个适用于任意轴的版本,可提供最佳性能。
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
normalized_v = v / np.sqrt(np.sum(v**2))
但是当
v
的长度为 0 时失败。
在这种情况下,引入一个小常数来防止除零可以解决这个问题。
正如评论中所建议的,人们也可以使用
v/np.linalg.norm(v)
为了避免零除,我使用 eps,但这可能不太好。
def normalize(v):
norm=np.linalg.norm(v)
if norm==0:
norm=np.finfo(v.dtype).eps
return v/norm
如果你不需要最高精度,你的函数可以简化为:
v_norm = v / (np.linalg.norm(v) + 1e-16)
如果您有多维数据并希望每个轴标准化为其最大值或其总和:
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 peak topeak 函数。
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 的流行的
transformations模块中还有函数
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))
你提到了 sci-kit learn,所以我想分享另一个解决方案。
MinMaxScaler
在 sci-kit learn 中,有一个名为
MinMaxScaler
的 API,可以根据需要自定义值范围。
它还为我们处理 NaN 问题。
NaN 被视为缺失值:在拟合中忽略,并保留 在变换中。 ...参见参考文献[1]
代码很简单,输入即可
# Let's say X_train is your input dataframe
from sklearn.preprocessing import MinMaxScaler
# call MinMaxScaler object
min_max_scaler = MinMaxScaler()
# feed in a numpy array
X_train_norm = min_max_scaler.fit_transform(X_train.values)
# wrap it up if you need a dataframe
df = pd.DataFrame(X_train_norm)
参考
如果您使用多维数组,可以采用以下快速解决方案。
假设我们有 2D 数组,我们希望通过最后一个轴对其进行标准化,而某些行的范数为零。
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]]
如果你想标准化存储在 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()
如果您正在使用 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 中过于冗长。
不使用
sklearn
,仅使用 numpy
。
只需定义一个函数即可:.
假设行是变量,列是样本(
axis= 1
):
import numpy as np
# Example array
X = np.array([[1,2,3],[4,5,6]])
def stdmtx(X):
means = X.mean(axis =1)
stds = X.std(axis= 1, ddof=1)
X= X - means[:, np.newaxis]
X= X / stds[:, np.newaxis]
return np.nan_to_num(X)
输出:
X
array([[1, 2, 3],
[4, 5, 6]])
stdmtx(X)
array([[-1., 0., 1.],
[-1., 0., 1.]])
对于 2D 数组,您可以使用以下单行代码来标准化各行。要跨列标准化,只需设置
axis=0
。
a / np.linalg.norm(a, axis=1, keepdims=True)
如果你想要[0;中的所有值] 1]
for 1d-array
然后就用
(a - a.min(axis=0)) / (a.max(axis=0) - a.min(axis=0))
哪里
a
是你的1d-array
。
一个例子:
>>> 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])
方法注意事项。为了保存值之间的比例,有一个限制:
1d-array
必须至少有一个0
,并且由0
和positive
数字组成。
一个简单的点积就可以完成这项工作。无需任何额外包装。
x = x/np.sqrt(x.dot(x))
顺便说一下,如果
x
的范数为零,它本质上是一个零向量,并且不能转换为单位向量(其范数为1)。如果你想捕获 np.array([0,0,...0])
的情况,那么使用
norm = np.sqrt(x.dot(x))
x = x/norm if norm != 0 else x
不幸的是,如果
x/numpy.linalg.norm(x)
是向量数组,则简单的解决方案 x
不起作用。但通过简单的 reshape()
,您可以将其强制转换为平面列表,使用列表理解,然后再次使用 reshape()
恢复原始形状。
s=x.shape
np.array([ v/np.linalg.norm(v) for v in x.reshape(-1, s[-1])]).reshape(s)
首先我们存储数组的形状
s=x.shape
然后我们将其重塑为一个简单的(一维)向量数组
x.reshape(-1, s[-1])
通过使用
reshape()
的“-1”参数,本质上意味着“需要多少就拿多少”,例如如果 x
是 (4,5,3) 数组,则 x.reshape(-1,3)
的形状将为 (20,3)。使用 s[-1]
允许向量的任意维度。
然后我们使用列表理解来逐步遍历数组并一次计算一个向量
[ v/np.linalg.norm(v) for v in x.reshape(-1, s[-1])]
最后我们将其转回 numpy 数组并恢复其原始形状
np.array([ v/np.linalg.norm(v) for v in x.reshape(-1, s[-1])]).reshape(s)