1、隨機划分訓練集和測試集
sklearn.model_selection.train_test_split
一般形式:
train_test_split是交叉驗證中常用的函數,功能是從樣本中隨機的按比例選取train data和testdata,形式為:
X_train,X_test, y_train, y_test = cross_validation.train_test_split(train_data,train_target,test_size=0.4, random_state=0)
參數解釋:
- train_data:所要划分的樣本特征集
- train_target:所要划分的樣本結果
- test_size:樣本占比,如果是整數的話就是樣本的數量
- random_state:是隨機數的種子。
- 隨機數種子:其實就是該組隨機數的編號,在需要重復試驗的時候,保證得到一組一樣的隨機數。比如你每次都填1,其他參數一樣的情況下你得到的隨機數組是一樣的。但填0或不填,每次都會不一樣。
隨機數的產生取決於種子,隨機數和種子之間的關系遵從以下兩個規則:
- 種子不同,產生不同的隨機數;種子相同,即使實例不同也產生相同的隨機數。
from sklearn.cross_validation import train_test_split train= loan_data.iloc[0: 55596, :] test= loan_data.iloc[55596:, :] # 避免過擬合,采用交叉驗證,驗證集占訓練集20%,固定隨機種子(random_state) train_X,test_X, train_y, test_y = train_test_split(train, target, test_size = 0.2, random_state = 0) train_y= train_y['label'] test_y= test_y['label']
2.將離散變量數值化分類(labelencoder),和虛擬(dummy)變量的轉換
sklearn.preprocessing.LabelEncoder\OneHotEncoder
我們一般用LabelEncoder來講series轉換為不同的整數分類,然后將其轉化為有序的數字編號
encoder = LabelEncoder() y = encoder.fit_transform(y) #這里也可以先進行fit(),然后在進行transform() #fit()是將樣本集數字分類,transform()是將樣本集轉化為數字分類
onehot的方法則是將數據離散成為無序的離散數據,但是轉換的需是整數所以和labelencoder搭配使用
from numpy import array from numpy import argmax from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import OneHotEncoder # define example data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm', 'hot'] values = array(data) print(values) # integer encode label_encoder = LabelEncoder() integer_encoded = label_encoder.fit_transform(values) print(integer_encoded,integer_encoded.shape) # binary encode onehot_encoder = OneHotEncoder(sparse=False) integer_encoded = integer_encoded.reshape(-1, 1) print(integer_encoded.reshape(-1, 1)) onehot_encoded = onehot_encoder.fit_transform(integer_encoded) print(onehot_encoded) # invert first example inverted = label_encoder.inverse_transform([argmax(onehot_encoded[0, :])]) print(inverted)
3.數據的規范化/標准化
sklearn.preprocessing
標准化:
公式為:(X-mean)/std 計算時對每個屬性/每列分別進行。
將數據按期屬性(按列進行)減去其均值,並處以其方差。得到的結果是,對於每個屬性/每列來說所有數據都聚集在0附近,方差為1。
實現時,有兩種不同的方式:
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.mean(axis=0) array([ 0., 0., 0.]) X_scaled.std(axis=0) array([ 1., 1., 1.])
使用sklearn.preprocessing.StandardScaler類,使用該類的好處在於可以保存訓練集中的參數(均值、方差)直接使用其對象轉換測試集數據。
scaler = preprocessing.StandardScaler().fit(X) StandardScaler(copy=True, with_mean=True, with_std=True) 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...]])
將屬性縮放到一個指定范圍:
另一種常用的方法是將屬性縮放到一個指定的最大和最小值(通常是1-0)之間,這可以通過preprocessing.MinMaxScaler類實現。
使用這種方法的目的包括:
1、對於方差非常小的屬性可以增強其穩定性。
2、維持稀疏矩陣中為0的條目。
X_train = np.array([[ 1., -1., 2.], ... [ 2., 0., 0.], ... [ 0., 1., -1.]]) ... min_max_scaler = preprocessing.MinMaxScaler() X_train_minmax = min_max_scaler.fit_transform(X_train) >>> #將相同的縮放應用到測試集數據中 >>> X_test = np.array([[ -3., -1., 4.]]) >>> X_test_minmax = min_max_scaler.transform(X_test) >>> #縮放因子等屬性 >>> min_max_scaler.scale_ array([ 0.5 , 0.5 , 0.33...]) >>> min_max_scaler.min_ array([ 0. , 0.5 , 0.33...])
4.模型參數的選擇
sklearn.grid_search
可以用來調節模型的參數:
tree_param_grid={'min_samples_split':list((3,6,9)),'n_estimators':list(10,50,100)} grid=GridSearchCV(RandomForestRegressor(),param_grid,=tree)param_gridcv=5) grid.fit(train_x,train_y) grid.beat_params