sklearn 会发生什么类型的规范化

What type of normalization happens with sklearn

我有一个矩阵,我试图通过将每个特征列转换为零均值和单位标准差来对其进行归一化。

我有以下正在使用的代码,但我想知道该方法是否真的能达到我的目的,或者它是否使用了不同的方法。

from sklearn import preprocessing

mat_normalized = preprocessing.normalize(mat_from_df)

the documentation 状态:

sklearn.preprocessing.normalize(X, norm='l2',
                                axis=1, copy=True,
                                return_norm=False)

Scale input vectors individually to unit norm (vector length).

所以它采用范数(默认情况下是 L2 范数),然后确保向量是单位的。

因此,如果我们将 n×m 矩阵作为输入,则输出为 n×m 矩阵。每个 m-向量都被归一化了。对于 norm='l2'(默认值),这意味着计算长度(通过分量平方和的平方根),每个元素除以该长度,结果是长度为 1.

的向量

sklearn.preprocessing.normalize 将每个样本向量缩放到单位范数。 (默认轴是 1,而不是 0。)证明如下:

from sklearn.preprocessing import normalize

np.random.seed(444)
data = np.random.normal(loc=5, scale=2, size=(15, 2))
np.linalg.norm(normalize(data), axis=1)
# array([ 1.,  1.,  1.,  1.,  1.,  1., ...

听起来您正在寻找 sklearn.preprocessing.scale 将每个特征向量缩放到 ~N(0, 1)。

from sklearn.preprocessing import scale

# Are the scaled column-wise means approx. 0.?
np.allclose(scale(data).mean(axis=0), 0.)
# True

# Are the scaled column-wise stdevs. approx. 1.?
np.allclose(scale(data).std(axis=0), 1.)
# True