如何对矩阵进行标准化?

26

基本上,取一个矩阵并将其更改为平均值等于0且方差等于1。我正在使用numpy的数组,所以如果它已经可以做到,那就更好了,但只要我能找到算法,我也可以自己实现。

编辑:算了,nimrodm有一个更好的实现。


1
定义“变换”。假设我们只是将矩阵替换为单位矩阵或其他东西,那怎么办?哪些变换是可以的? - Karl Knechtel
只是出于好奇,你为什么需要这样做呢? - Drew Hall
我正在尝试实现一个计算机视觉算法,该算法要求在中间步骤执行此操作。我认为这是PCA的要求,但我不确定。 - pnodbnda
你是否考虑采纳 @nimrodm 的答案,这样我就可以删除我的回答了吗? - John Alexiou
5个回答

77
以下代码从A的每个元素中减去平均值(新平均值为0),然后将结果归一化为标准偏差。
import numpy as np
A = (A - np.mean(A)) / np.std(A)

以上是为了统一整个矩阵的标准化,如果A具有多个维度并且您想单独将每一列标准化,请指定 axis

import numpy as np
A = (A - np.mean(A, axis=0)) / np.std(A, axis=0)

在将这些一行代码集成到您的代码之前,请通过手动验证确保它们的功能。 方向或尺寸的简单更改可能会极大地(悄无声息地)改变numpy对它们执行的操作。


2
你可能需要仅在 std(A) > 0 的情况下更新 A,以避免除以零和 NaN 值。 - Ciprian Tomoiagă
这是否可能,其中A表示为列表的列表? - Nematode7
@Neamah 为什么不直接转换成numpy数组呢? - kingledion
补充@nimrodm的答案,可以使用numpy实现如下: import numpy as np meanArr = np.mean(A) standardized_arr = (A-meanArr)/np.std(A) - user3585984

13
import scipy.stats as ss

A = np.array(ss.zscore(A))

5
from sklearn.preprocessing import StandardScaler

standardized_data = StandardScaler().fit_transform(your_data)

例子:

示例:

>>> import numpy as np
>>> from sklearn.preprocessing import StandardScaler

>>> data = np.random.randint(25, size=(4, 4))
>>> data
array([[17, 12,  4, 17],
       [ 1, 16, 19,  1],
       [ 7,  8, 10,  4],
       [22,  4,  2,  8]])

>>> standardized_data = StandardScaler().fit_transform(data)
>>> standardized_data
array([[ 0.63812398,  0.4472136 , -0.718646  ,  1.57786412],
       [-1.30663482,  1.34164079,  1.55076242, -1.07959124],
       [-0.57735027, -0.4472136 ,  0.18911737, -0.58131836],
       [ 1.24586111, -1.34164079, -1.02123379,  0.08304548]])

在大型数据集上表现良好。


你可以使用 Ctrl+K 缩进所有内容,而不是使用反引号。 - Jean-François Fabre

2
使用 sklearn.preprocessing.scale。以下是一个示例。http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.scale.html
>>> from sklearn import preprocessing
>>> import numpy as np
>>> X_train = np.array([[ 1., -1.,  2.],
...                     [ 2.,  0.,  0.],
...                     [ 0.,  1., -1.]])
>>> X_scaled = preprocessing.scale(X_train)
>>> X_scaled
array([[ 0.  ..., -1.22...,  1.33...],
       [ 1.22...,  0.  ..., -0.26...],
       [-1.22...,  1.22..., -1.06...]])

http://scikit-learn.org/stable/modules/preprocessing.html#standardization-or-mean-removal-and-variance-scaling


0
import numpy as np

A = np.array([[1,2,6], [3000,1000,2000]]).T  

A_means = np.mean(A, axis=0)
A_centr = A - A_means
A_norms = np.linalg.norm(A_centr, axis=0)

A_std = A_centr / A_norms

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接