Preprocessing data-sklearn数据预处理

1. Standardization, or mean removal and variance scaling

Standardization即标准化,尽量将数据转化为均值为零,方差为一的数据。
实际中我们会忽略数据的分布情况,仅仅是通过改变均值来集中数据,然后将非连续特征除以他们的标准差。
sklearn中   scale函数提供了简单 快速的 single array-like数据集操作
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)
print x_scaled
output
[[ 0.         -1.22474487  1.33630621]
 [ 1.22474487  0.         -0.26726124]
 [-1.22474487  1.22474487 -1.06904497]]

  scale处理之后为零均值和单位方差:
 
 
X_scaled.mean(axis=0)array([ 0.,  0.,  0.])
X_scaled.std(axis=0)array([ 1.,  1.,  1.])
StandardScaler 计算平均值和标准偏差在一个训练集,可以以后再申请相同的转换测试集。
scaler=preprocessing.StandardScaler().fit(X)
scalerStandardScaler(copy=True, with_mean=True, with_std=True)
scaler.mean_array([ 1. ...,  0. ...,  0.33...])
scaler.scale_array([ 0.81...,  0.81...,  1.24...])
scaler.transform(X)array([[ 0.  ..., -1.22...,  1.33...],       [ 1.22...,  0.  ..., -0.26...],       [-1.22...,  1.22..., -1.06...]])
同样的,将相同的转化应用到测试集合。
 
 
scaler.transform([[-1.,1.,0.]])array([[-2.44...,  1.22..., -0.26...]])
对于StandardScaler你也可以改变它的一些参数,例如
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]之间
X_train=np.array([[1.,-1.,2.],... [2.,0.,0.],... [0.,1.,-1.]])...
min_max_scaler=preprocessing.MinMaxScaler(copy=True, feature_range=(0, 1))
X_train_minmax=min_max_scaler.fit_transform(X_train)
X_train_minmaxarray([[ 0.5       ,  0.        ,  1.        ],       [ 1.        ,  0.5       ,  0.33333333],       [ 0.        ,  1.        ,  0.        ]])
同理,它也可以直接用到后续的测试集中
 
 
 
 
X_test=np.array([[-3.,-1.,4.]])
X_test_minmax=min_max_scaler.transform(X_test)
X_test_minmaxarray([[-1.5       ,  0.        ,  1.66666667]])
如果MinMaxScaler给定了feature_range,其公式为
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两个标准
X=[[1.,-1.,2.],... [2.,0.,0.],... [0.,1.,-1.]]
X_normalized=preprocessing.normalize(X,norm='l2')
X_normalizedarray([[ 0.40..., -0.40...,  0.81...],       [ 1.  ...,  0.  ...,  0.  ...],       [ 0.  ...,  0.70..., -0.70...]])
它也可以像前面一样的方式使用:
normalizer=preprocessing.Normalizer().fit(X)# fit does nothing
normalizer.transform(X)
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

特征二值化阈值的过程即转化为布尔值数值特性。
 
  
X=[[1.,-1.,2.],... [2.,0.,0.],... [0.,1.,-1.]]
binarizer=preprocessing.Binarizer().fit(X)# fit does nothing
binarizerBinarizer(copy=True, threshold=0.0)
binarizer.transform(X)array([[ 1.,  0.,  1.],       [ 1.,  0.,  0.],       [ 0.,  1.,  0.]])
调整threshold之后:
 
  
binarizer=preprocessing.Binarizer(threshold=1.1)
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可能值转换成二进制特征,只有一个有效。
 
  
enc = preprocessing.OneHotEncoder()
enc.fit([[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])  
OneHotEncoder(categorical_features='all', dtype=<... 'float'>,
       handle_unknown='error', n_values='auto', sparse=True)
enc.transform([[0, 1, 3]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  1.]])
其实可以通过从字典加载特征来实现上面的思想:
 
  
 
  
measurements = [
    {'city': 'Dubai', 'temperature': 33.},
    {'city': 'London', 'temperature': 12.},
    {'city': 'San Fransisco', 'temperature': 18.},
]
from sklearn.feature_extraction import DictVectorizer
vec = DictVectorizer()
vec.fit_transform(measurements).toarray()array([[  1.,   0.,   0.,  33.],       [  0.,   1.,   0.,  12.],       [  0.,   0.,   1.,  18.]])
vec.get_feature_names()['city=Dubai', 'city=London', 'city=San Fransisco', 'temperature']

5. Imputation of missing values

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


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

6. Generating polynomial features

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

7. Custom transformers

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

CSDN博客原文:

授人以鱼不如授人以渔:
广义线性模型--Generalized Linear Models: http://blog.csdn.net/shine19930820/article/details/50997645





  • 3
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百川AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值