XGBoost 重要参数、方法、函数理解及调参思路(附例子)
文章目錄
- 一、xgboost 原生接口
- 重要參數(shù)
- 訓(xùn)練參數(shù)
- 預(yù)測函數(shù)
- 繪制特征重要性
- 分類例子
- 回歸例子
- 二、xgboost 的 sklearn 風(fēng)格接口
- XGBClassifier
- 基本使用
- 例子
- XGBRegressor
- 基本使用
- 例子
- 三、xgboost 調(diào)參思路
xgboost 包含原生接口和 sklearn 風(fēng)格接口兩種,并且二者都實現(xiàn)了分類和回歸的功能。如果想了解一些理論性的內(nèi)容,可以看看之前的文章: XGBoost算法的相關(guān)知識
一、xgboost 原生接口
重要參數(shù)
1,booster
用于指定弱學(xué)習(xí)器的類型,默認(rèn)值為 ‘gbtree’,表示使用基于樹的模型進(jìn)行計算。還可以選擇為 ‘gblinear’ 表示使用線性模型作為弱學(xué)習(xí)器。
推薦設(shè)置為 ‘gbtree’,本文后面的相關(guān)參數(shù)設(shè)置都以booster設(shè)置為’gbtree’為前提。
2,eta / learning_rate
如果你看了我之前發(fā)的XGBoost算法的相關(guān)知識,不難發(fā)現(xiàn)XGBoost為了防止過擬合,引入了"Shrinkage"的思想,即不完全信任每個弱學(xué)習(xí)器學(xué)到的殘差值。為此需要給每個弱學(xué)習(xí)器擬合的殘差值都乘上取值范圍在(0, 1] 的 eta,設(shè)置較小的 eta 就可以多學(xué)習(xí)幾個弱學(xué)習(xí)器來彌補(bǔ)不足的殘差。
在XGBClassifier與XGBRegressor中,對應(yīng)參數(shù)名為 learning_rate。
推薦的候選值為:[0.01, 0.015, 0.025, 0.05, 0.1]
3,gamma
指定葉節(jié)點進(jìn)行分支所需的損失減少的最小值,默認(rèn)值為0。設(shè)置的值越大,模型就越保守。
**推薦的候選值為:[0, 0.05 ~ 0.1, 0.3, 0.5, 0.7, 0.9, 1] **
4,alpha / reg_alpha
L1正則化權(quán)重項,增加此值將使模型更加保守。
在XGBClassifier與XGBRegressor中,對應(yīng)參數(shù)名為 reg_alpha 。
推薦的候選值為:[0, 0.01~0.1, 1]
5,lambda / reg_lambda
L2正則化權(quán)重項,增加此值將使模型更加保守。
在XGBClassifier與XGBRegressor中,對應(yīng)參數(shù)名為 reg_lambda。
推薦的候選值為:[0, 0.1, 0.5, 1]
6,max_depth
指定樹的最大深度,默認(rèn)值為6,合理的設(shè)置可以防止過擬合。
推薦的數(shù)值為:[3, 5, 6, 7, 9, 12, 15, 17, 25]。
7,min_child_weight
指定孩子節(jié)點中最小的樣本權(quán)重和,如果一個葉子節(jié)點的樣本權(quán)重和小于min_child_weight則拆分過程結(jié)束,默認(rèn)值為1。
推薦的候選值為:[1, 3, 5, 7]
8,subsample
默認(rèn)值1,指定采樣出 subsample * n_samples 個樣本用于訓(xùn)練弱學(xué)習(xí)器。注意這里的子采樣和隨機(jī)森林不一樣,隨機(jī)森林使用的是放回抽樣,而這里是不放回抽樣。 取值在(0, 1)之間,設(shè)置為1表示使用所有數(shù)據(jù)訓(xùn)練弱學(xué)習(xí)器。如果取值小于1,則只有一部分樣本會去做GBDT的決策樹擬合。選擇小于1的比例可以減少方差,即防止過擬合,但是會增加樣本擬合的偏差,因此取值不能太低。
推薦的候選值為:[0.6, 0.7, 0.8, 0.9, 1]
9,colsample_bytree
構(gòu)建弱學(xué)習(xí)器時,對特征隨機(jī)采樣的比例,默認(rèn)值為1。
推薦的候選值為:[0.6, 0.7, 0.8, 0.9, 1]
10,objective
用于指定學(xué)習(xí)任務(wù)及相應(yīng)的學(xué)習(xí)目標(biāo),常用的可選參數(shù)值如下:
- “reg:linear”,線性回歸(默認(rèn)值)。
- “reg:logistic”,邏輯回歸。
- “binary:logistic”,二分類的邏輯回歸問題,輸出為概率。
- “multi:softmax”,采用softmax函數(shù)處理多分類問題,同時需要設(shè)置參數(shù)num_class用于指定類別個數(shù)
11,num_class
用于設(shè)置多分類問題的類別個數(shù)。
12,eval_metric
用于指定評估指標(biāo),可以傳遞各種評估方法組成的list。常用的評估指標(biāo)如下:
-
‘rmse’,用于回歸任務(wù)
-
‘mlogloss’,用于多分類任務(wù)
-
‘error’,用于二分類任務(wù)
-
‘a(chǎn)uc’,用于二分類任務(wù)
13,silent
數(shù)值型,表示是否輸出運行過程的信息,默認(rèn)值為0,表示打印信息。設(shè)置為1時,不輸出任何信息。
推薦設(shè)置為 0 。
14,seed / random_state
指定隨機(jī)數(shù)種子。
在XGBClassifier與XGBRegressor中,對應(yīng)參數(shù)名為 random_state 。
訓(xùn)練參數(shù)
以xgboost.train為主,參數(shù)及默認(rèn)值如下:
xgboost.train(params, dtrain, num_boost_round=10, evals=(),obj=None, feval=None, maximize=False, early_stopping_rounds=None, evals_result=None, verbose_eval=True, xgb_model=None, callbacks=None)1,params
字典類型,用于指定各種參數(shù),例如:{‘booster’:‘gbtree’,‘eta’:0.1}
2,dtrain
用于訓(xùn)練的數(shù)據(jù),通過給下面的方法傳遞數(shù)據(jù)和標(biāo)簽來構(gòu)造:
dtrain = xgb.DMatrix(data, label=label)3,num_boost_round
指定最大迭代次數(shù),默認(rèn)值為10
4,evals
列表類型,用于指定訓(xùn)練過程中用于評估的數(shù)據(jù)及數(shù)據(jù)的名稱。例如:[(dtrain,‘train’),(dval,‘val’)]
5,obj
可以指定二階可導(dǎo)的自定義目標(biāo)函數(shù)。
6,feval
自定義評估函數(shù)。
7,maximize
是否對評估函數(shù)最大化,默認(rèn)值為False。
8,early_stopping_rounds
指定迭代多少次沒有得到優(yōu)化則停止訓(xùn)練,默認(rèn)值為None,表示不提前停止訓(xùn)練。如果設(shè)置了此參數(shù),則模型會生成三個屬性:
-
best_score
-
best_iteration
-
best_ntree_limit
注意:evals 必須非空才能生效,如果有多個數(shù)據(jù)集,則以最后一個數(shù)據(jù)集為準(zhǔn)。
9,verbose_eval
可以是bool類型,也可以是整數(shù)類型。如果設(shè)置為整數(shù),則每間隔verbose_eval次迭代就輸出一次信息。
10,xgb_model
加載之前訓(xùn)練好的 xgb 模型,用于增量訓(xùn)練。
預(yù)測函數(shù)
主要是下面的兩個函數(shù):
1,predict(data),返回每個樣本的預(yù)測結(jié)果
2,predict_proba(data),返回每個樣本屬于每個類別的概率
注意:data 是由 DMatrix 函數(shù)封裝后的數(shù)據(jù)。
繪制特征重要性
代碼如下:
from xgboost import plot_importance # 顯示重要特征,model 為訓(xùn)練好的xgb模型 plot_importance(model) plt.show()分類例子
from sklearn.datasets import load_iris import xgboost as xgb from xgboost import plot_importance import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score# 加載鳶尾花數(shù)據(jù)集 iris = load_iris() X,y = iris.data,iris.target # 數(shù)據(jù)集分割 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=123457)# 參數(shù) params = {'booster': 'gbtree','objective': 'multi:softmax','num_class': 3,'gamma': 0.1,'max_depth': 6,'lambda': 2,'subsample': 0.7,'colsample_bytree': 0.7,'min_child_weight': 3,'slient': 1,'eta': 0.1 }# 構(gòu)造訓(xùn)練集 dtrain = xgb.DMatrix(X_train,y_train) num_rounds = 500 # xgboost模型訓(xùn)練 model = xgb.train(params,dtrain,num_rounds)# 對測試集進(jìn)行預(yù)測 dtest = xgb.DMatrix(X_test) y_pred = model.predict(dtest)# 計算準(zhǔn)確率 accuracy = accuracy_score(y_test,y_pred) print('accuarcy:%.2f%%'%(accuracy*100))# 顯示重要特征 plot_importance(model) plt.show()輸出結(jié)果:
accuarcy: 93.33%
回歸例子
import xgboost as xgb from xgboost import plot_importance from matplotlib import pyplot as plt from sklearn.model_selection import train_test_split from sklearn.datasets import load_boston from sklearn.metrics import mean_squared_error# 加載波士頓房價預(yù)測數(shù)據(jù)集 boston = load_boston() X,y = boston.data,boston.target# 數(shù)據(jù)集分割 X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)# 參數(shù) params = {'booster': 'gbtree','objective': 'reg:gamma','gamma': 0.1,'max_depth': 5,'lambda': 3,'subsample': 0.7,'colsample_bytree': 0.7,'min_child_weight': 3,'slient': 1,'eta': 0.1,'seed': 1000,'nthread': 4, }dtrain = xgb.DMatrix(X_train,y_train) num_rounds = 300 plst = params.items() model = xgb.train(plst,dtrain,num_rounds)# 對測試集進(jìn)行預(yù)測 dtest = xgb.DMatrix(X_test) ans = model.predict(dtest) print('mse:', mean_squared_error(y_test, ans))# 顯示重要特征 plot_importance(model) plt.show()輸出:
mse: 25.48099643587081
二、xgboost 的 sklearn 風(fēng)格接口
XGBClassifier
基本使用
XGBClassifier的引入以及重要參數(shù)的默認(rèn)值如下:
from xgboost import XGBClassifier # 重要參數(shù): xgb_model = XGBClassifier(max_depth=3,learning_rate=0.1,n_estimators=100, # 使用多少個弱分類器objective='binary:logistic',booster='gbtree',gamma=0,min_child_weight=1,max_delta_step=0,subsample=1,colsample_bytree=1,reg_alpha=0,reg_lambda=1,seed=0 # 隨機(jī)數(shù)種子)其中絕大多數(shù)的參數(shù)在上文已經(jīng)說明,不再贅述。
與原生的xgboost相比,XGBClassifier并不是調(diào)用train方法進(jìn)行訓(xùn)練,而是使用fit方法:
xgb_model.fit(X, # array, DataFrame 類型y, # array, Series 類型eval_set=None, # 用于評估的數(shù)據(jù)集,例如:[(X_train, y_train), (X_test, y_test)]eval_metric=None, # 評估函數(shù),字符串類型,例如:'mlogloss'early_stopping_rounds=None, verbose=True, # 間隔多少次迭代輸出一次信息xgb_model=None )預(yù)測的方法有兩種:
xgb_model.predict(data) # 返回預(yù)測值 xgb_model.predict_proba(data) # 返回各個樣本屬于各個類別的概率例子
from xgboost import XGBClassifier from sklearn.datasets import load_iris from xgboost import plot_importance import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score# 加載樣本數(shù)據(jù)集 iris = load_iris() X,y = iris.data,iris.target X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=12343)model = XGBClassifier(max_depth=3,learning_rate=0.1,n_estimators=100, # 使用多少個弱分類器objective='multi:softmax',num_class=3,booster='gbtree',gamma=0,min_child_weight=1,max_delta_step=0,subsample=1,colsample_bytree=1,reg_alpha=0,reg_lambda=1,seed=0 # 隨機(jī)數(shù)種子 ) model.fit(X_train,y_train, eval_set=[(X_train, y_train), (X_test, y_test)], eval_metric='mlogloss', verbose=50, early_stopping_rounds=50)# 對測試集進(jìn)行預(yù)測 y_pred = model.predict(X_test) #計算準(zhǔn)確率 accuracy = accuracy_score(y_test,y_pred) print('accuracy:%2.f%%'%(accuracy*100))# 顯示重要特征 plot_importance(model) plt.show()輸出:
[0] validation_0-mlogloss:0.967097 validation_1-mlogloss:0.971479
Multiple eval metrics have been passed: ‘validation_1-mlogloss’ will
be used for early stopping.
Will train until validation_1-mlogloss hasn’t improved in 50 rounds.
[50] validation_0-mlogloss:0.035594 validation_1-mlogloss:0.204737
Stopping. Best iteration:
[32] validation_0-mlogloss:0.073909 validation_1-mlogloss:0.182504
accuracy:97%
XGBRegressor
基本使用
XGBRegressor與XGBClassifier類似,其引入以及重要參數(shù)的默認(rèn)值如下:
from xgboost import XGBRegressor # 重要參數(shù) xgb_model = XGBRegressor(max_depth=3,learning_rate=0.1,n_estimators=100,objective='reg:linear', # 此默認(rèn)參數(shù)與 XGBClassifier 不同booster='gbtree',gamma=0,min_child_weight=1,subsample=1,colsample_bytree=1,reg_alpha=0,reg_lambda=1,random_state=0 )其 fit 方法、predict方法與 XGBClassifier 幾乎相同,不再重復(fù)說明。
例子
import xgboost as xgb from xgboost import plot_importance import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.datasets import load_boston from sklearn.metrics import mean_squared_error# 導(dǎo)入數(shù)據(jù)集 boston = load_boston() X ,y = boston.data,boston.target X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.2,random_state=0)model = xgb.XGBRegressor(max_depth=3,learning_rate=0.1,n_estimators=100,objective='reg:linear', # 此默認(rèn)參數(shù)與 XGBClassifier 不同booster='gbtree',gamma=0,min_child_weight=1,subsample=1,colsample_bytree=1,reg_alpha=0,reg_lambda=1,random_state=0) model.fit(X_train,y_train, eval_set=[(X_train, y_train), (X_test, y_test)], eval_metric='rmse', verbose=50, early_stopping_rounds=50)# 對測試集進(jìn)行預(yù)測 ans = model.predict(X_test) mse = mean_squared_error(y_test,ans) print('mse:', mse)# 顯示重要特征 plot_importance(model) plt.show()輸出:
[0] validation_0-rmse:21.687 validation_1-rmse:21.3558
[50] validation_0-rmse:1.8122 validation_1-rmse:4.8143
[99] validation_0-rmse:1.3396 validation_1-rmse:4.63377
mse: 21.471843729261288
三、xgboost 調(diào)參思路
(1)選擇較高的學(xué)習(xí)率,例如0.1,這樣可以減少迭代用時。
(2)然后對 max_depth , min_child_weight , gamma , subsample, colsample_bytree 這些參數(shù)進(jìn)行調(diào)整。這些參數(shù)的合適候選值為:
-
max_depth:[3, 5, 6, 7, 9, 12, 15, 17, 25]
-
min_child_weight:[1, 3, 5, 7]
-
gamma:[0, 0.05 ~ 0.1, 0.3, 0.5, 0.7, 0.9, 1]
-
subsample:[0.6, 0.7, 0.8, 0.9, 1]
-
colsample_bytree:[0.6, 0.7, 0.8, 0.9, 1]
(3)調(diào)整正則化參數(shù) lambda , alpha,這些參數(shù)的合適候選值為:
- alpha:[0, 0.01~0.1, 1]
- lambda :[0, 0.1, 0.5, 1]
(4)降低學(xué)習(xí)率,繼續(xù)調(diào)整參數(shù),學(xué)習(xí)率合適候選值為:[0.01, 0.015, 0.025, 0.05, 0.1]
參考文章:
XGBoost Parameters
Python API Reference
Python機(jī)器學(xué)習(xí)筆記:XgBoost算法
總結(jié)
以上是生活随笔為你收集整理的XGBoost 重要参数、方法、函数理解及调参思路(附例子)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: pycharm社区版和专业版的区别
- 下一篇: CTR经典模型串讲:FM / FFM /