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]]

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM