data-sklearn数据预处理 Preprocessing

1. Standardization, or mean removal and variance scaling

Standardization即标准化,尽量将数据转化为均值为零,方差为一的数据。
实际中我们会忽略数据的分布情况,仅仅是通过改变均值来集中数据,然后将非连续特征除以他们的标准差。
sklearn中   scale函数提供了简单 快速的 single array-like数据集操作
[python]
  1. from sklearn import preprocessing  
  2. import numpy as np  
  3. x = np.array([[ 1., -1.,  2.],[ 2.,  0.,  0.],[ 0.,  1., -1.]])  
  4. x_scaled = preprocessing.scale(x)  
  5. print x_scaled  
output
[[ 0.         -1.22474487  1.33630621]
 [ 1.22474487  0.         -0.26726124]
 [-1.22474487  1.22474487 -1.06904497]]

  scale处理之后为零均值和单位方差:
[python]
  1. X_scaled.mean(axis=0)array([ 0.,  0.,  0.])  
  2. X_scaled.std(axis=0)array([ 1.,  1.,  1.])  
StandardScaler 计算平均值和标准偏差在一个训练集,可以以后再申请相同的转换测试集。
[python]
  1. scaler=preprocessing.StandardScaler().fit(X)  
  2. scalerStandardScaler(copy=True, with_mean=True, with_std=True)  
  3. scaler.mean_array([ 1. ...,  0. ...,  0.33...])  
  4. scaler.scale_array([ 0.81...,  0.81...,  1.24...])  
  5. scaler.transform(X)array([[ 0.  ..., -1.22...,  1.33...],       [ 1.22...,  0.  ..., -0.26...],       [-1.22...,  1.22..., -1.06...]])  
同样的,将相同的转化应用到测试集合。
[python]
  1. scaler.transform([[-1.,1.,0.]])array([[-2.44...,  1.22..., -0.26...]])  
对于StandardScaler你也可以改变它的一些参数,例如
[python]
  1. scaler = preprocessing.StandardScaler(copy=True, with_mean=True, with_std=True).fit(X)  

1.1 Scaling features to a range

另一种标准化可以使用scal将特征标准化到指定的最大值和最小值之间,有连个函数: MinMaxScaler  or  MaxAbsScaler
例如转化到[0,1]之间
[python]
  1. X_train=np.array([[1.,-1.,2.],... [2.,0.,0.],... [0.,1.,-1.]])...  
  2. min_max_scaler=preprocessing.MinMaxScaler(copy=True, feature_range=(01))  
  3. X_train_minmax=min_max_scaler.fit_transform(X_train)  
  4. X_train_minmaxarray([[ 0.5       ,  0.        ,  1.        ],       [ 1.        ,  0.5       ,  0.33333333],       [ 0.        ,  1.        ,  0.        ]])  
同理,它也可以直接用到后续的测试集中
[python]
  1. X_test=np.array([[-3.,-1.,4.]])  
  2. X_test_minmax=min_max_scaler.transform(X_test)  
  3. X_test_minmaxarray([[-1.5       ,  0.        ,  1.66666667]])  
如果MinMaxScaler给定了feature_range,其公式为
[python]
  1. X_std=(X-X.min(axis=0))/(X.max(axis=0)-X.min(axis=0))X_scaled=X_std*(max-min)+min  

MaxAbsScaler 和scales工作很相似,但是 scales是将特征调整到特定值,而MaxAbsScaler对于本来中心店就是零或者稀疏的数据,是不会改变的。

1.2 Scaling sparse data

定心稀疏数据的稀疏结构会破坏数据,因此很少是一个明智的做法。然而,它可以合理规模稀疏的输入,特别是特性在不同的尺度上。

1.3 Scaling data with outliers

如果您的数据包含了许多异常值,扩展使用数据的均值和方差可能不能很好地工作。在这些情况下,您可以使用robust_scale和RobustScaler作为替代。他们使用更健壮的中心和范围的估计数据。
是否应该标准化数据:

据使用sklearn.decomposition.PCA or sklearn.decomposition.RandomizedPCA with whiten=True深入的移除特征中的线性相关性。

2. Normalization

正常化的过程是缩放单个样本的单位标准。这个过程可能是有用的,如果你打算使用二次形式如点积或任何其他内核量化任何一对样本的相似性。
normalize 有l1 or l2两个标准
[python]
  1. X=[[1.,-1.,2.],... [2.,0.,0.],... [0.,1.,-1.]]  
  2. X_normalized=preprocessing.normalize(X,norm='l2')  
  3. X_normalizedarray([[ 0.40..., -0.40...,  0.81...],       [ 1.  ...,  0.  ...,  0.  ...],       [ 0.  ...,  0.70..., -0.70...]])  
它也可以像前面一样的方式使用:
[python]
  1. normalizer=preprocessing.Normalizer().fit(X)# fit does nothing  
  2. normalizer.transform(X)  
  3. array([[ 0.40..., -0.40...,  0.81...],       [ 1.  ...,  0.  ...,  0.  ...],       [ 0.  ...,  0.70..., -0.70...]])normalizer.transform([[-1.,1.,0.]])array([[-0.70...,  0.70...,  0.  ...]])  

Sparse input

normalize and Normalizer接受scipy密集的数组类和稀疏矩阵.

3. Binarization

特征二值化阈值的过程即转化为布尔值数值特性。
[python]
  1. X=[[1.,-1.,2.],... [2.,0.,0.],... [0.,1.,-1.]]  
  2. binarizer=preprocessing.Binarizer().fit(X)# fit does nothing  
  3. binarizerBinarizer(copy=True, threshold=0.0)  
  4. binarizer.transform(X)array([[ 1.,  0.,  1.],       [ 1.,  0.,  0.],       [ 0.,  1.,  0.]])  
调整threshold之后:
[python]
  1. binarizer=preprocessing.Binarizer(threshold=1.1)  
  2. binarizer.transform(X)array([[ 0.,  0.,  1.],       [ 1.,  0.,  0.],       [ 0.,  0.,  0.]])  
支持Sparse input

4. Encoding categorical features

经常会有些特征并不是连续的数值化的特征,例如["male", "female"],它可以被表示成[1,2],当然,sklearn是不能直接做到这样的。
但是,它可以做到将这个估计将每个分类特性与m可能值转换成二进制特征,只有一个有效。
[python]
  1. enc = preprocessing.OneHotEncoder()  
  2. enc.fit([[003], [110], [021], [102]])    
  3. OneHotEncoder(categorical_features='all', dtype=<... 'float'>,  
  4.        handle_unknown='error', n_values='auto', sparse=True)  
  5. enc.transform([[013]]).toarray()  
  6. array([[ 1.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.]])  
其实可以通过从字典加载特征来实现上面的思想:
[python]
  1. measurements = [  
  2.     {'city''Dubai''temperature'33.},  
  3.     {'city''London''temperature'12.},  
  4.     {'city''San Fransisco''temperature'18.},  
  5. ]  
  6. from sklearn.feature_extraction import DictVectorizer  
  7. vec = DictVectorizer()  
  8. vec.fit_transform(measurements).toarray()array([[  1.,   0.,   0.,  33.],       [  0.,   1.,   0.,  12.],       [  0.,   0.,   1.,  18.]])  
  9. vec.get_feature_names()['city=Dubai''city=London''city=San Fransisco''temperature']  

5. Imputation of missing values

由于各种原因,会导致真实世界中数据集会丢失部分值,如银行等。一种解决办法是去掉这些包含丢失值的行,当然,这样的话就会丢弃掉许多数据,因此可以采取更好的策略来填充丢失的数据,例如通过他们已知的数据来推测。   
Imputer 提供基本的填充方法,例如使用均值或者中位数填充。当然还有许多其他的方法。
[python]
  1. import numpy as np  
  2. from sklearn.preprocessing import Imputer  
  3. imp = Imputer(missing_values='NaN', strategy='mean', axis=0)  
  4. imp.fit([[12], [np.nan, 3], [76]])  
  5. Imputer(axis=0, copy=True, missing_values='NaN', strategy='mean', verbose=0)  
  6. X = [[np.nan, 2], [6, np.nan], [76]]  
  7. print(imp.transform(X))            
  8.                    
  9. [[ 4.          2.        ]  
  10.  [ 6.          3.666...]  
  11.  [ 7.          6.        ]]  


缺失值也可以使用0表示:
[python]
  1. import scipy.sparse as sp  
  2. X = sp.csc_matrix([[12], [03], [76]])  
  3. imp = Imputer(missing_values=0, strategy='mean', axis=0)  
  4. imp.fit(X)  
  5. Imputer(axis=0, copy=True, missing_values=0, strategy='mean', verbose=0)  
  6. X_test = sp.csc_matrix([[02], [60], [76]])  
  7. print(imp.transform(X_test))                        
  8. [[ 4.          2.        ]  
  9.  [ 6.          3.666...]  
  10.  [ 7.          6.        ]]  

6. Generating polynomial features

使用多项式特征,可以建立高阶特征和相互关联的特征:
[python]
  1. import numpy as np  
  2. from sklearn.preprocessing import PolynomialFeatures  
  3. X = np.arange(6).reshape(32)  
  4. X                                                   
  5. array([[01],  
  6.        [23],  
  7.        [45]])  
  8. poly = PolynomialFeatures(2)  
  9. poly.fit_transform(X)                               
  10. array([[  1.,   0.,   1.,   0.,   0.,   1.],  
  11.        [  1.,   2.,   3.,   4.,   6.,   9.],  
  12.        [  1.,   4.,   5.,  16.,  20.,  25.]])  
转换
设置 interaction_only=True, 时只使用交互作用项
[python]
  1. X = np.arange(9).reshape(33)  
  2. X                                                   
  3. array([[012],  
  4.        [345],  
  5.        [678]])  
  6. poly = PolynomialFeatures(degree=3, interaction_only=True)  
  7. poly.fit_transform(X)                               
  8. array([[   1.,    0.,    1.,    2.,    0.,    0.,    2.,    0.],  
  9.        [   1.,    3.,    4.,    5.,   12.,   15.,   20.,   60.],  
  10.        [   1.,    6.,    7.,    8.,   42.,   48.,   56.,  336.]])  
转换为:
扩展维度之后的效果。

7. Custom transformers

FunctionTransformer . 可以在传递途径( pipeline )中使用转换。
以下是使用 log transformation情况。
[python]
  1. import numpy as np  
  2. from sklearn.preprocessing import FunctionTransformer  
  3. transformer = FunctionTransformer(np.log1p)  
  4. X = np.array([[01], [23]])  
  5. transformer.transform(X)  
  6. array([[ 0.        ,  0.69314718],  
  7.        [ 1.09861229,  1.38629436]])  

CSDN博客原文:

猜你喜欢

转载自blog.csdn.net/Leonis_v/article/details/78789432