【機器學習 模型調參】GridSearchCV模型調參利器

導入模塊sklearn.model_selection

from sklearn.model_selection import GridSearchCV

GridSearchCV 稱爲網格搜索交叉驗證調參,它通過遍歷傳入的參數的所有排列組合,通過交叉驗證的方式,返回所有參數組合下的評價指標得分,GridSearchCV 函數的參數詳細解釋如下:

class sklearn.model_selection.GridSearchCV(estimator,param_grid,scoring = None,n_jobs = None,iid ='deprecated',refit = True,cv = None,verbose = 0,pre_dispatch ='2 * n_jobs',error_score = nan,return_train_score = False )


GridSearchCV官方說明

參數:

estimator:scikit-learn 庫裏的算法模型;
param_grid:需要搜索調參的參數字典;
scoring:評價指標,可以是 auc, rmse,logloss等;
n_jobs:並行計算線程個數,可以設置爲 -1,這樣可以充分使用機器的所有處理器,並行數量越多,有利於縮短調參時間;
iid:如果設置爲True,則默認假設數據在每折中具有相同地分佈,並且最小化的損失是每個樣本的總損失,而不是每折的平均損失。簡單點說,就是如果你可以確定 cv 中每折數據分佈一致就設置爲 True,否則設置爲 False;
cv:交叉驗證的折數,默認爲3折;

常用屬性:
cv_results_:用來輸出cv結果的,可以是字典形式也可以是numpy形式,還可以轉換成DataFrame格式
best_estimator_:通過搜索參數得到的最好的估計器,當參數refit=False時該對象不可用
best_score_:float類型,輸出最好的成績
best_params_:通過網格搜索得到的score最好對應的參數
best_index_:對應於最佳候選參數設置的索引(cv_results_數組)。cv_results _ [‘params’] [search.best_index_]中的dict給出了最佳模型的參數設置,給出了最高的平均分數(search.best_score_)。
scorer_:評分函數
n_splits_:交叉驗證的數量
refit_time_:refit所用的時間,當參數refit=False時該對象不可用


常用函數:

decision_function(X):返回決策函數值(比如svm中的決策距離)
fit(X,y=None,groups=None,fit_params):在數據集上運行所有的參數組合
get_params(deep=True):返回估計器的參數
inverse_transform(Xt):Call inverse_transform on the estimator with the best found params.
predict(X):返回預測結果值(0/1predict_log_proba(X): Call predict_log_proba on the estimator with the best found parameters.
predict_proba(X):返回每個類別的概率值(有幾類就返回幾列值)
score(X, y=None):返回函數
set_params(**params):Set the parameters of this estimator.
transform(X):在X上使用訓練好的參數

屬性grid_scores_已經被刪除,改用:

means = grid_search.cv_results_['mean_test_score']
params = grid_search.cv_results_['params']

GBDT例子:


# -*- coding: utf-8 -*-

# 載入包
import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error,r2_score,mean_absolute_error
import warnings
warnings.filterwarnings('ignore')
from sklearn.externals import joblib
from sklearn.model_selection import GridSearchCV
import numpy as np


# 讀取數據
data_path=r'D:\data.txt'
# 導入數據
data=pd.read_table(data_path)

# 篩選自變量
X=data.iloc[:,1:]
# 篩選因變量
y=data.iloc[:,0]
# 提取特徵名
feature_names=list(X.columns)
# 切分數據,劃分爲訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=33)


param_gbdt3 = {'learning_rate':[0.06,0.07,0.08,0.09,0.1],
               'n_estimators':[100,150,200,250,300]}


gbdt_search2 = GridSearchCV(estimator=GradientBoostingRegressor(loss='ls',max_depth=9,max_features=9,
                                                             subsample=0.8,min_samples_leaf=4, min_samples_split=6),n_jobs=-1,
                            param_grid=param_gbdt3,scoring='neg_mean_squared_error',iid=False,cv=5)
gbdt_search2.fit(X_train,y_train)
print(gbdt_search2.best_params_)

2、xgboost例子:

# -*- coding: utf-8 -*-

# 載入包
import pandas as pd
from sklearn.model_selection import train_test_split
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error,r2_score,mean_absolute_error
import warnings
warnings.filterwarnings('ignore')
from sklearn.externals import joblib
from sklearn.model_selection import GridSearchCV
import numpy as np


# 讀取數據
data_path=r'D:\data.txt'
# 導入數據
data=pd.read_table(data_path)

# 篩選自變量
X=data.iloc[:,1:]
# 篩選因變量
y=data.iloc[:,0]
# 提取特徵名
feature_names=list(X.columns)
# 切分數據,劃分爲訓練集和測試集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=33)


cv_params  = {'n_estimators': [280,290,300,320,330]}


other_params = {
    'learning_rate':0.1,
    'max_depth':8,
    'min_child_weight':1,
    'gamma':0.05,
    'subsample':0.8,
    'colsample_bytree':0.8,
    'reg_alpha':0,
    'reg_lambda':1
}
xgb_model_ = XGBRegressor(**other_params)
xgb_search = GridSearchCV(xgb_model_,
                          param_grid=cv_params ,
                          scoring='r2',
                          iid=False,n_jobs=-1,
                          cv=5)

xgb_search.fit(X_train, y_train)


means = xgb_search.cv_results_['mean_test_score']
params = xgb_search.cv_results_['params']

print(means)
print(params)
print(xgb_search.best_params_)
print(xgb_search.best_score_)


常用參數解讀:

estimator:所使用的分類器,如果比賽中使用的是XGBoost的話,就是生成的model。比如: model = xgb.XGBRegressor(**other_params)
param_grid:值爲字典或者列表,即需要最優化的參數的取值。比如:cv_params = {‘n_estimators’: [550, 575, 600, 650, 675]}
scoring :準確度評價標準,默認None,這時需要使用score函數;或者如scoring=‘roc_auc’,根據所選模型不同,評價準則不同。字符串(函數名),或是可調用對象,需要其函數簽名形如:scorer(estimator, X, y);如果是None,則使用estimator的誤差估計函數。scoring參數選擇如下:
scoring參數 說明:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章