关于sklearn.preprocessing中scale和StandardScaler的使用

标准化(Z-Score),或者去除均值和方差缩放

公式为:(X-mean)/std  计算时对每个属性/每列分别进行。

将数据按期属性(按列进行)减去其均值,并处以其方差。得到的结果是,对于每个属性/每列来说所有数据都聚集在0附近,方差为1。

使用sklearn.preprocessing.scale()函数,可以直接将给定数据进行标准化。

>>> 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)
 
>>> X_scaled                                         
array([[ 0 .  ..., - 1.22 ...,  1.33 ...],
        [ 1.22 ...,  0 .  ..., - 0.26 ...],
        [- 1.22 ...,  1.22 ..., - 1.06 ...]])
 
>>>#处理后数据的均值和方差
>>> X_scaled.mean(axis= 0 )
array([ 0 .,  0 .,  0 .])
 
>>> X_scaled.std(axis= 0 )
array([ 1 .,  1 .,  1 .])

使用sklearn.preprocessing.StandardScaler类,使用该类的好处在于可以保存训练集中的参数(均值、方差)直接使用其对象转换测试集数据。

>>> scaler =  preprocessing.StandardScaler().fit(X)
>>> scaler
StandardScaler(copy = True , with_mean = True , with_std = True )
 
>>> scaler.mean_                                     
array([ 1.  ...,  0.  ...,  0.33 ...])
 
>>> scaler.std_                                      
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 ...]])

猜你喜欢

转载自blog.csdn.net/dengdengma520/article/details/79629186