Preprocessing data数据预处理

Standardization,or mean removal and variance scaling

from sklearn import preprocessing
import numpy as np
X = np.array([[ 1., -1.,  2.],
              [ 2.,  0.,  0.],
              [ 0.,  1., -1.]])
X_scaled = preprocessing.scale(X)

[[ 0.         -1.22474487  1.33630621]
 [ 1.22474487  0.         -0.26726124]
 [-1.22474487  1.22474487 -1.06904497]]

print(X_scaled.mean(axis=0)) #均值为0
print(X_scaled.std(axis=0)) #标准差为1

[ 0.  0.  0.]
[ 1.  1.  1.]

使用StandardScaler使标准化应用在测试集上:保存标准化参数
一般我们的标准化现在训练集上进行,在测试集上也应该做同样mean和variance的标准化,这样就应该将训练集上的标准化参数保存下来
scaler = prepeocessing.StandardScaler().fit(X)
print(scaler)
print(scaler.mean_)
print(scaler.scale_)

StandardScaler(copy=True, with_mean=True, with_std=True)
[ 1.          0.          0.33333333]
[ 0.81649658  0.81649658  1.24721913]

scale_X=scaler.transform(X)
print(scale_X)

[[ 0.         -1.22474487  1.33630621]
 [ 1.22474487  0.         -0.26726124]
 [-1.22474487  1.22474487 -1.06904497]]

The scaler instance can then be used on new data to transform it the same way it did on the training set

print(scaler.transform([[-1.,  1., 0.]]))

[[-2.44948974  1.22474487 -0.26726124]]

Scaling features to a range(将特征的取值缩小到一个范围,如0到1)
目的:
对于方差非常小的属性可以增强稳定性
维持稀疏矩阵中为0的条目
X_train = np.array([[ 1., -1.,  2.],
                    [ 2.,  0.,  0.],
                    [ 0.,  1., -1.]])
min_max_scaler = preprocessing.MinMaxScaler()
X_train_minmax = min_max_scaler.fit_transform(X_train)
print(X_train_minmax)

[[ 0.5         0.          1.        ]
 [ 1.          0.5         0.33333333]
 [ 0.          1.          0.        ]]

有大量异常值的归一化

sklearn.preprocessing.robust_scale()

Normalization
正则化的过程是将每个样本缩放发哦单位范数(每个样本的范数为1),如果要使用如二次型(点积)或者其他核方法计算两个样本之间的相似性,这个方法会很有用
该方法是文本分类和聚类分析中经常使用的向量空间模型(Vector Space Model)的基础
axis=0,表明在列方向上进行处理;axis=1,表明在行方向上进行处理

X = [[ 1., -1.,  2.],
      [ 2.,  0.,  0.],
      [ 0.,  1., -1.]]

X_normalized = preprocessing.normalize(X,norm='l2') #axis默认为1


[[ 0.40..., -0.40...,  0.81...],
 [ 1.  ...,  0.  ...,  0.  ...],
 [ 0.  ...,  0.70..., -0.70...]]

Binarization二值化
特征的二值化主要是为了将数据特征转变成boolean变量

from sklearn.preprocessing import Binarizer
binarizer = preprocessing.Binarizer(threshold=0.0).fit(X)
print(Binarizer())
print(binarizer.transform(X))

Binarizer(copy=True, threshold=0.0)
[[ 1.  0.  1.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]]

缺失值处理Imputation of missing values
由于不同的原因,许多现实中的数据集都包含缺失值,不能用分类器直接训练,所以需要进行处理。

import numpy as np
from sklearn.preprocessing import Imputer
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
imp.fit([[1, 2], [np.nan, 3], [7, 6]])
X = [[np.nan, 2], [6, np.nan], [7, 6]]
print(imp.transform(X))

[[ 4.          2.        ]
 [ 6.          3.66666667]
 [ 7.          6.        ]]

猜你喜欢

转载自blog.csdn.net/lengxiaomo123/article/details/68924724