sklearn——数据标准化

说明:

通过sklearn库进行数据集标准化,对训练数据做预处理,对测试集做同样的标准化。

1、通过函数scale()

函数介绍:

 

函数:

sklearn.preprocessing.scale(X, axis=0, with_mean=True, with_std=True, copy=True)
参数解释:
X : {array-like, sparse matrix} 要标准化的数据,numpy的array类数据。
axis : int (0 by default) 0表示特征的标准化,1表示样本的标准化。默认为0。
with_mean : boolean, True by default 是否中心化。
with_std : boolean, True by default 是否标准化。
copy : boolean, optional, default True 是否复制。

 

代码实例 :

from sklearn.preprocessing import scale
import numpy as np

X = np.array([[ 1.,-1.,2.],[ 2.,0.,0.],[ 0.,1.,-1.]])
x_scale=scale(X=X,with_mean=True,with_std=True,copy=True)
print('原始数据:\n',X)
print('标准化数据:\n',x_scale)

运行结果:

原始数据:
 [[ 1. -1.  2.]
 [ 2.  0.  0.]
 [ 0.  1. -1.]]

标准化数据:
 [[ 0.         -1.22474487  1.33630621]
 [ 1.22474487  0.         -0.26726124]
 [-1.22474487  1.22474487 -1.06904497]]

 

2、通过创建类StandardScaler

在skleran库中除了用函数方法,还可以使用sklearn.preprocessing.StandardScaler类来达到标准化的目的,使用该类的好处在于可以保存训练集中的参数(均值、方差)直接使用其对象转换测试集数据。

代码实例:

from sklearn.preprocessing import StandardScaler
import numpy as np

X = np.array([[ 1.,-1.,2.],[ 2.,0.,0.],[ 0.,1.,-1.]])
scaler=StandardScaler().fit(X)     #声明类,并用fit()方法计算后续标准化的mean与std
print('\n均值:',scaler.mean_)    #类属性:均值
print('方差:',scaler.var_)     #类属性:方差
X_scale=scaler.transform(X)     #转换X
print('\n标准化数据:\n',X_scale)
y=np.array([[1.,1.,1.],[2.,2.,2.]])
y_scale=scaler.transform(y)     #测试集标准化
print('\n测试集标准化数据:\n',y_scale)
X_scale2=scaler.fit_transform(X)     #直接计算并标准化的方法
print('\n原始数据直接标准化:\n',X_scale2)

运行结果:

均值: [1.         0.         0.33333333]
方差: [0.66666667 0.66666667 1.55555556]

标准化数据:
 [[ 0.         -1.22474487  1.33630621]
 [ 1.22474487  0.         -0.26726124]
 [-1.22474487  1.22474487 -1.06904497]]

测试集标准化数据:
 [[0.         1.22474487 0.53452248]
 [1.22474487 2.44948974 1.33630621]]

原始数据直接标准化:
 [[ 0.         -1.22474487  1.33630621]
 [ 1.22474487  0.         -0.26726124]
 [-1.22474487  1.22474487 -1.06904497]]

 

posted @ 2019-04-16 15:06  我不是高斯分布  阅读(2359)  评论(0编辑  收藏  举报