python网格搜索、贝叶斯调参实战
????????
目錄
一、交叉驗證
二、網格搜索
三、貝葉斯優化
????????建模的整個過程中最耗時的部分是特征工程(含變量分析),其次可能是調參,所以今天來通過代碼實戰介紹調參的相關方法:網格搜索、貝葉斯調參。
一、交叉驗證
????????工作中最常用的訓練集測試集劃分方法主要是隨機比例分割和(分層)交叉驗證,隨機比例分割可以按照7-3、8-2的比例劃分訓練集、測試集,但是這樣的數據劃分存在一定隨機性,不如使用交叉驗證來的嚴謹。
1、導包、設定初始參數
# 導包 import re import os from sqlalchemy import create_engine import pandas as pd import numpy as np import warnings warnings.filterwarnings('ignore') import sklearn from sklearn.model_selection import train_test_split from sklearn.metrics import roc_curve,roc_auc_score import xgboost as xgb from xgboost.sklearn import XGBClassifier import matplotlib.pyplot as plt import gc from sklearn import metrics from sklearn.model_selection import cross_val_predict,cross_validate# 設定xgb參數 params={'objective':'binary:logistic','eval_metric':'auc','n_estimators':500,'eta':0.03,'max_depth':3,'min_child_weight':100,'scale_pos_weight':1,'gamma':5,'reg_alpha':10,'reg_lambda':10,'subsample':0.7,'colsample_bytree':0.7,'seed':123 }2、初始化模型對象、5折交叉驗證,交叉驗證函數cross_validate可以設定多個目標(此處使用AUC)、而cross_val_score只能設置一個
xgb = XGBClassifier(**params) scoring=['roc_auc'] scores=cross_validate(xgb,df[col_list],df.y,cv=5,scoring=scoring,return_train_score=True ) scores3、Xgb、lgb的原生接口可用自帶的cv函數
xgb.cv(params,df,num_boost_round=10,nfold=5,stratified=True,metrics='auc' ,as_pandas=True)?
二、網格搜索
? ? ? ? 通過遍歷全部的參數組合,尋找測試集效果最優的參數組
1、設定調參參數及范圍,使用網格搜索
from sklearn.model_selection import GridSearchCV train=df_train.head(60000) test=df_train.tail(10000)param_value_dics={'n_estimators':range(100,900,500),'eta':np.arange(0.02,0.2,0.1),'max_depth':range(3,5,1), # 'num_leaves':range(10,30,10), # 'min_child_weight':range(300,1500,500),}xgb_model=XGBClassifier(**params) clf=GridSearchCV(xgb_model,param_value_dics,scoring='roc_auc',n_jobs=-1,cv=5,return_train_score=True) clf.fit(df[col_list], df.y)2、返回最優參數
clf.best_params_3、返回最優參數的模型
clf.best_estimator_4、返回最優參數下的測試集評估指標(此處設定的AUC)?
clf.best_score_?????????網格搜索在設定的參數范圍中全局遍歷尋找最優參數、即全局最優解,但是這樣的計算量下程序運行簡直是龜速,而且它網格搜索的目標是測試集效果最優、在這種目標下調參訓練仍然存在過擬合的風險;針對這些問題,有了貝葉斯優化調參。
三、貝葉斯優化
????????貝葉斯調參需要自定義目標函數,可根據實際情況靈活選擇,而且運行速度快、在運行的同時就能展示每次當下參數的模型結果,確實是很好用的方法
1、導包
from bayes_opt import BayesianOptimization import warnings warnings.filterwarnings("ignore") from sklearn import metrics from sklearn.model_selection import cross_val_predict,cross_validate from xgboost import XGBClassifier2、自定義調參目標,此處使用cv下測試集的AUC均值為調參目標
def xgb_cv(n_estimators,max_depth,eta,subsample,colsample_bytree):params={'objective':'binary:logistic','eval_metric':'auc','n_estimators':10,'eta':0.03,'max_depth':3,'min_child_weight':100,'scale_pos_weight':1,'gamma':5,'reg_alpha':10,'reg_lambda':10,'subsample':0.7,'colsample_bytree':0.7,'seed':123,}params.update({'n_estimators':int(n_estimators),'max_depth':int(max_depth),'eta':eta,'sub sample':subsample,'colsample_bytree':colsample_bytree})model=XGBClassifier(**params)cv_result=cross_validate(model,df_train.head(10000)[col_list],df_train.head(10000).y, cv=5,scoring='roc_auc',return_train_score=True)return cv_result.get('test_score').mean()3、設定調參范圍,注意數值范圍的固定格式:(left,right),貝葉斯調參會在該范圍內隨機選取實數點,對于n_estimators、max_depth等參數,隨即出來的結果一樣是浮點數、所以在模型部分要將這些參數轉化為整型:int(n_estimators)
param_value_dics={'n_estimators':(100, 500),'max_depth':(3, 6),'eta':(0.02,0.2),'subsample':(0.6, 1.0),'colsample_bytree':(0.6, 1.0)}4、 建立貝葉斯調參對象,迭代20次
lgb_bo = BayesianOptimization(xgb_cv,param_value_dics) lgb_bo.maximize(init_points=1,n_iter=20) #init_points-調參基準點,n_iter-迭代次數5、查看最優參數結果?
lgb_bo.max6、查看全部調參結果
lgb_bo.res7、將全部調參結果轉化為DataFrame,便于觀察和展示?
result=pd.DataFrame([res.get('params') for res in lgb_bo.res]) result['target']=[res.get('target') for res in lgb_bo.res] result[['max_depth','n_estimators']]=result[['max_depth','n_estimators']].astype('int') result8、在當前調參的結果下,可以再次細化設定或修改參數范圍、進一步調參
lgb_bo.set_bounds({'n_estimators':(400, 450)}) lgb_bo.maximize(init_points=1,n_iter=20)更多知識及代碼分享,關注公眾號Python風控模型與數據分析
?
總結
以上是生活随笔為你收集整理的python网格搜索、贝叶斯调参实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring boot mqtt客户端
- 下一篇: websocket python爬虫_p