xgboost调参指南
?python機器學習-乳腺癌細胞數據挖掘
https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campaign=commission&utm_source=cp-400000000398149&utm_medium=share
歡迎關注博主主頁,學習python視頻資源
xgboost調參思路
xgboost
參數調優的一般步驟
1. 確定學習速率和提升參數調優的初始值
2. max_depth 和 min_child_weight 參數調優
3. gamma參數調優
4. subsample 和 colsample_bytree 參數優
5. 正則化參數alpha調優
6. 降低學習速率和使用更多的決策樹
1.min_child_weight 默認值1
決定最小葉子節點樣本權重和。和 GBM 的 min_child_leaf 參數類似,但不完全一樣。XGBoost 的這個參數是最小樣本權重的和,而 GBM 參數是最小樣本總數。這個參數用于避免過擬合。當它的值較大時,可以避免模型學習到局部的特殊樣本。但是如果這個值過高,會導致欠擬合。這個參數需要使用 CV 來調整。
min_child_weight是一個非常重要的參數直譯即:決定最小葉子節點樣本權重和。如果在一次分裂中,葉子節點上所有樣本的權重和小于min_child_weight則停止分裂,能夠有效的防止過擬合,防止學到特殊樣本。數值越大,算法越保守。
孩子節點中最小的樣本權重和。如果一個葉子節點的樣本權重和小于min_child_weight則拆分過程結束。在現行回歸模型中,這個參數是指建立每個模型所需要的最小樣本數。該成熟越大算法越conservative
取值范圍為: [0,∞]
2.eta [默認 0.3]
和 GBM 中的 learning rate 參數類似。 通過減少每一步的權重,可以提高模型的穩定性。 典型值為 0.01-0.2
3. colsample_bytree [默認 1]
列采樣率,也就是特征采樣率
和 GBM 里面的 max_features 參數類似。用來控制每棵隨機采樣的列數的占比 (每一列是一個特征)。 典型值:0.5-1
4. subsample [默認 1]
和 GBM 中的 subsample 參數一模一樣。這個參數控制對于每棵樹,隨機采樣的比例。 減小這個參數的值,算法會更加保守,避免過擬合。但是,如果這個值設置得過小,它可能會導致欠擬合。 典型值:0.5-1
構建每棵樹對樣本的采樣率,如果設置成0.5,XGBoost會隨機選擇一半的樣本作為訓練集。
5. alpha [默認 1]
權重的 L1 正則化項。(和 Lasso regression 類似)。 可以應用在很高維度的情況下,使得算法的速度更快。
6.lambda [default=1, alias: reg_lambda]
L2正則化,這個參數是用來控制XGBoost的正則化部分的。雖然大部分數據科學家很少用到這個參數,但是這個參數在減少過擬合上還是可以挖掘出更多用處的。
6. gamma [默認 0,alias: min_split_loss]
在節點分裂時,只有分裂后損失函數的值下降了,才會分裂這個節點。Gamma 指定了節點分裂所需的最小損失函數下降值。 這個參數的值越大,算法越保守。這個參數的值和損失函數息息相關,所以是需要調整的。
分裂節點時,損失函數減小值只有大于等于gamma節點才分裂,gamma值越大,算法越保守,越不容易過擬合,但性能就不一定能保證,需要平衡。
7.eval_metric [默認值取決于 objective 參數的取值]
對于有效數據的度量方法。對于回歸問題,默認值是 rmse,對于分類問題,默認值是 error。 典型值有:
rmse 均方根誤差、mae 平均絕對誤差、logloss 負對數似然函數值、error 二分類錯誤率 (閾值為 0.5)、merror 多分類錯誤率、mlogloss 多分類 logloss 損失函數、auc 曲線下面積
8. scale_pos_weight [默認 1]
在類別高度不平衡的情況下,將參數設置大于0,可以加快收斂
在各類別樣本十分不平衡時,把這個參數設定為一個正值,可以使算法更快收斂
9.num_boost_round
xgboost學習率與迭代次數
?xgboost是一種迭代改進的算法,它每次給錯誤分類的實例增加權重,并進入下一次迭代。因此需要指定迭代次數和每次權重改進的程度(學習率)。
?迭代次數通過num_boost_round設置,次數越多,花費時間越長,xgboost除了可以設置固定迭代次數以外,還可以根據評估,判斷如果n次不再改進,則停止迭代(具體見eval部分)。
?學習率通過eta設置,它是每次迭代之后對原模型的改進程度,學習率越高收斂越快,但也可能因為粒度太大,錯過極值點。
調參方法是先粗調再細調:一開始將學習率設大一點,比如0.1-0.3;次數設少一點,比如50次,即能快速改善模型又不花太長時間。后面細調時再變小學習率,增加迭代次數。
10.Early_stopping_rounds: 提前終止程序
如果有評價數據,可以提前終止程序,這樣可以找到最優的迭代次數。如果要提前終止程序必須至少有一個評價數據在參數evals中。 超過一個則使用最后一個。
train(..., evals=evals, early_stopping_rounds=10)
此模型下,機器會一直學習到 validation score 不再增長。每經過 early_stopping_rounds 輪,誤差應該都有所下降,否則不應該繼續學習。
如果出現了提前終止,模型會出現兩個額外情況:bst.best_score 和 bst.best_iteration. 注意此處 train() 會返回最后一次循環的模型,而非最好的循環的模型。
此方法適用于各類最低 (RMSE, log loss, etc.) 或最高 (MAP, NDCG, AUC) 誤差計算。
11. max_depth [default=6]
樹的最大深度,值越大,樹越大,模型越復雜 可以用來防止過擬合,典型值是3-10。
?
?
https://blog.csdn.net/q383700092/article/details/53763328
調參后結果非常理想
from sklearn.model_selection import GridSearchCV from sklearn.datasets import load_breast_cancer from xgboost import XGBClassifier from sklearn.model_selection import train_test_split from sklearn import metricscancer=load_breast_cancer() X, y = cancer.data,cancer.targettrain_x, test_x, train_y, test_y=train_test_split(X,y,test_size=0.3,random_state=0) parameters= [{'learning_rate':[0.01,0.1,0.3],'n_estimators':[1000,1200,1500,2000,2500],'max_depth':range(1,10,1),'gamma':[0.01,0.1,0.3,0.5],'eta': [0.025,0.1,0.2,0.3]}]clf = GridSearchCV(XGBClassifier(min_child_weight=1,subsample=0.6,colsample_bytree=0.6,objective= 'binary:logistic', #邏輯回歸損失函數scale_pos_weight=1,reg_alpha=0,reg_lambda=1,seed=27), param_grid=parameters,scoring='roc_auc') clf.fit(train_x,train_y)y_pred=clf.predict(test_x)print("accuracy on the training subset:{:.3f}".format(clf.score(train_x,train_y))) print("accuracy on the test subset:{:.3f}".format(clf.score(test_x,test_y)))print(clf.best_params_) y_pre= clf.predict(test_x) y_pro= clf.predict_proba(test_x)[:,1] print ("AUC Score : %f" % metrics.roc_auc_score(test_y, y_pro)) print("Accuracy : %.4g" % metrics.accuracy_score(test_y, y_pre)) ''' accuracy on the training subset:1.000 accuracy on the test subset:0.998 {'gamma': 0.5, 'learning_rate': 0.01, 'max_depth': 2, 'n_estimators': 1000} AUC Score : 0.998089 Accuracy : 0.9708 '''best_xgb=XGBClassifier(min_child_weight=1,subsample=0.6,colsample_bytree=0.6,objective= 'binary:logistic', #邏輯回歸損失函數scale_pos_weight=1,reg_alpha=0,reg_lambda=1,seed=27,gamma=0.5,learning_rate=0.01,max_depth=2,n_estimators=1000)best_xgb.fit(train_x,train_y)print("accuracy on the training subset:{:.3f}".format(best_xgb.score(train_x,train_y))) print("accuracy on the test subset:{:.3f}".format(best_xgb.score(test_x,test_y)))''' accuracy on the training subset:0.995 accuracy on the test subset:0.979 '''
?
?
?
?
?
github:https://github.com/dmlc/xgboost?
論文參考:http://www.kaggle.com/blobs/download/forum-message-attachment-files/4087/xgboost-paper.pdf
基本思路及優點
http://blog.csdn.net/q383700092/article/details/60954996?
參考http://dataunion.org/15787.html?
http://blog.csdn.net/china1000/article/details/51106856?
在有監督學習中,我們通常會構造一個目標函數和一個預測函數,使用訓練樣本對目標函數最小化學習到相關的參數,然后用預測函數和訓練樣本得到的參數來對未知的樣本進行分類的標注或者數值的預測。?
1. Boosting Tree構造樹來擬合殘差,而Xgboost引入了二階導來進行求解,并且引入了節點的數目、參數的L2正則來評估模型的復雜度,構造Xgboost的預測函數與目標函數。?
2. 在分裂點選擇的時候也以目標函數最小化為目標。?
優點:?
1. 顯示的把樹模型復雜度作為正則項加到優化目標中。?
2. 公式推導中用到了二階導數,用了二階泰勒展開。(GBDT用牛頓法貌似也是二階信息)?
3. 實現了分裂點尋找近似算法。?
4. 利用了特征的稀疏性。?
5. 數據事先排序并且以block形式存儲,有利于并行計算。?
6. 基于分布式通信框架rabit,可以運行在MPI和yarn上。(最新已經不基于rabit了)?
7. 實現做了面向體系結構的優化,針對cache和內存做了性能優化。
原理推導及與GBDT區別
http://blog.csdn.net/q383700092/article/details/60954996?
參考http://dataunion.org/15787.html?
https://www.zhihu.com/question/41354392
參數說明
參考http://blog.csdn.net/han_xiaoyang/article/details/52665396?
參數?
booster:默認 gbtree效果好 (linear booster很少用到)?
gbtree:基于樹的模型?
gbliner:線性模型?
silent[默認0]?
nthread[默認值為最大可能的線程數]?
eta[默認0.3] 學習率 典型值為0.01-0.2?
min_child_weight[默認 1 ] 決定最小葉子節點樣本權重和 值較大,避免過擬合 值過高,會導致欠擬合?
max_depth[默認6]?
gamma[默認0] 指定了節點分裂所需的最小損失函數下降值。 這個參數的值越大,算法越保守?
subsample[默認1] 對于每棵樹,隨機采樣的比例 減小,算法保守,避免過擬合。值設置得過小,它會導致欠擬合 典型值:0.5-1?
colsample_bytree[默認1] 每棵隨機采樣的列數的占比?
colsample_bylevel[默認1] 樹的每一級的每一次分裂,對列數的采樣的占比?
lambda[默認1] 權重的L2正則化項?
alpha[默認1] 權重的L1正則化項?
scale_pos_weight[默認1] 在各類別樣本十分不平衡時,參數設定為一個正值,可以使算法更快收斂?
objective[默認reg:linear] 最小化的損失函數?
binary:logistic 二分類的邏輯回歸,返回預測的概率(不是類別)。 multi:softmax 使用softmax的多分類器,返回預測的類別(不是概率)。?
在這種情況下,你還需要多設一個參數:num_class(類別數目)。 multi:softprob 和multi:softmax參數一樣,但是返回的是每個數據屬于各個類別的概率。?
eval_metric[默認值取決于objective參數的取值]?
對于回歸問題,默認值是rmse,對于分類問題,默認值是error。 典型值有:?
rmse 均方根誤差 mae 平均絕對誤差 logloss 負對數似然函數值?
error 二分類錯誤率 merror 多分類錯誤率 mlogloss 多分類logloss損失函數 auc 曲線下面積?
seed(默認0) 隨機數的種子 設置它可以復現隨機數據的結果
sklearn包,XGBClassifier會改變的函數名?
eta ->learning_rate?
lambda->reg_lambda?
alpha->reg_alpha
常用調整參數:
參考?
https://www.analyticsvidhya.com/blog/2016/03/complete-guide-parameter-tuning-xgboost-with-codes-python/
第一步:確定學習速率和tree_based 參數調優的估計器數目
樹的最大深度一般3-10?
max_depth = 5?
節點分裂所需的最小損失函數下降值0.1到0.2?
gamma = 0?
采樣?
subsample= 0.8,?
colsample_bytree = 0.8?
比較小的值,適用極不平衡的分類問題?
min_child_weight = 1?
類別十分不平衡?
scale_pos_weight = 1
?
第二步: max_depth 和 min_weight 參數調優
grid_search參考?
http://scikit-learn.org/stable/modules/generated/sklearn.grid_search.GridSearchCV.html?
http://blog.csdn.net/abcjennifer/article/details/23884761?
網格搜索scoring=’roc_auc’只支持二分類,多分類需要修改scoring(默認支持多分類)
?
第三步:gamma參數調優
param_test3 = {'gamma':[i/10.0 for i in range(0,5)] } gsearch3 = GridSearchCV( estimator = XGBClassifier( learning_rate =0.1, n_estimators=140, max_depth=4, min_child_weight=6, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27), param_grid = param_test3, scoring='roc_auc', n_jobs=4, iid=False, cv=5) gsearch3.fit(train[predictors],train[target]) gsearch3.grid_scores_, gsearch3.best_params_, gsearch3.best_score_?
第四步:調整subsample 和 colsample_bytree 參數
#取0.6,0.7,0.8,0.9作為起始值 param_test4 = {'subsample':[i/10.0 for i in range(6,10)],'colsample_bytree':[i/10.0 for i in range(6,10)] }gsearch4 = GridSearchCV( estimator = XGBClassifier( learning_rate =0.1, n_estimators=177, max_depth=3, min_child_weight=4, gamma=0.1, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27), param_grid = param_test4, scoring='roc_auc', n_jobs=4, iid=False, cv=5) gsearch4.fit(train[predictors],train[target]) gsearch4.grid_scores_, gsearch4.best_params_, gsearch4.best_score_?
第五步:正則化參數調優
param_test6 = {'reg_alpha':[1e-5, 1e-2, 0.1, 1, 100] } gsearch6 = GridSearchCV( estimator = XGBClassifier( learning_rate =0.1, n_estimators=177, max_depth=4, min_child_weight=6, gamma=0.1, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27), param_grid = param_test6, scoring='roc_auc', n_jobs=4, iid=False, cv=5) gsearch6.fit(train[predictors],train[target]) gsearch6.grid_scores_, gsearch6.best_params_, gsearch6.best_score_?
第六步:降低學習速率
xgb4 = XGBClassifier(learning_rate =0.01,n_estimators=5000,max_depth=4,min_child_weight=6,gamma=0, subsample=0.8, colsample_bytree=0.8, reg_alpha=0.005, objective= 'binary:logistic', nthread=4, scale_pos_weight=1, seed=27) modelfit(xgb4, train, predictors)?
python示例
import xgboost as xgb import pandas as pd #獲取數據 from sklearn import cross_validation from sklearn.datasets import load_iris iris = load_iris() #切分數據集 X_train, X_test, y_train, y_test = cross_validation.train_test_split(iris.data, iris.target, test_size=0.33, random_state=42) #設置參數 m_class = xgb.XGBClassifier( learning_rate =0.1, n_estimators=1000, max_depth=5, gamma=0, subsample=0.8, colsample_bytree=0.8, objective= 'binary:logistic', nthread=4, seed=27) #訓練 m_class.fit(X_train, y_train) test_21 = m_class.predict(X_test) print "Accuracy : %.2f" % metrics.accuracy_score(y_test, test_21) #預測概率 #test_2 = m_class.predict_proba(X_test) #查看AUC評價標準 from sklearn import metrics print "Accuracy : %.2f" % metrics.accuracy_score(y_test, test_21) ##必須二分類才能計算 ##print "AUC Score (Train): %f" % metrics.roc_auc_score(y_test, test_2) #查看重要程度 feat_imp = pd.Series(m_class.booster().get_fscore()).sort_values(ascending=False) feat_imp.plot(kind='bar', title='Feature Importances') import matplotlib.pyplot as plt plt.show() #回歸 #m_regress = xgb.XGBRegressor(n_estimators=1000,seed=0) #m_regress.fit(X_train, y_train) #test_1 = m_regress.predict(X_test)?
整理
xgb原始
from sklearn.model_selection import train_test_split from sklearn import metrics from sklearn.datasets import make_hastie_10_2 import xgboost as xgb #記錄程序運行時間 import time start_time = time.time() X, y = make_hastie_10_2(random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)##test_size測試集合所占比例 #xgb矩陣賦值 xgb_train = xgb.DMatrix(X_train, label=y_train) xgb_test = xgb.DMatrix(X_test,label=y_test) ##參數 params={ 'booster':'gbtree', 'silent':1 ,#設置成1則沒有運行信息輸出,最好是設置為0. #'nthread':7,# cpu 線程數 默認最大 'eta': 0.007, # 如同學習率 'min_child_weight':3, # 這個參數默認是 1,是每個葉子里面 h 的和至少是多少,對正負樣本不均衡時的 0-1 分類而言 #,假設 h 在 0.01 附近,min_child_weight 為 1 意味著葉子節點中最少需要包含 100 個樣本。 #這個參數非常影響結果,控制葉子節點中二階導的和的最小值,該參數值越小,越容易 overfitting。 'max_depth':6, # 構建樹的深度,越大越容易過擬合 'gamma':0.1, # 樹的葉子節點上作進一步分區所需的最小損失減少,越大越保守,一般0.1、0.2這樣子。 'subsample':0.7, # 隨機采樣訓練樣本 'colsample_bytree':0.7, # 生成樹時進行的列采樣 'lambda':2, # 控制模型復雜度的權重值的L2正則化項參數,參數越大,模型越不容易過擬合。 #'alpha':0, # L1 正則項參數 #'scale_pos_weight':1, #如果取值大于0的話,在類別樣本不平衡的情況下有助于快速收斂。 #'objective': 'multi:softmax', #多分類的問題 #'num_class':10, # 類別數,多分類與 multisoftmax 并用 'seed':1000, #隨機種子 #'eval_metric': 'auc' } plst = list(params.items()) num_rounds = 100 # 迭代次數 watchlist = [(xgb_train, 'train'),(xgb_test, 'val')] #訓練模型并保存 # early_stopping_rounds 當設置的迭代次數較大時,early_stopping_rounds 可在一定的迭代次數內準確率沒有提升就停止訓練 model = xgb.train(plst, xgb_train, num_rounds, watchlist,early_stopping_rounds=100,pred_margin=1) #model.save_model('./model/xgb.model') # 用于存儲訓練出的模型 print "best best_ntree_limit",model.best_ntree_limit y_pred = model.predict(xgb_test,ntree_limit=model.best_ntree_limit) print ('error=%f' % ( sum(1 for i in range(len(y_pred)) if int(y_pred[i]>0.5)!=y_test[i]) /float(len(y_pred)))) #輸出運行時長 cost_time = time.time()-start_time print "xgboost success!",'\n',"cost time:",cost_time,"(s)......"?
xgb使用sklearn接口(推薦)
官方?
會改變的函數名是:?
eta -> learning_rate?
lambda -> reg_lambda?
alpha -> reg_alpha
?
網格搜索
可以先固定一個參數 最優化后繼續調整?
第一步:確定學習速率和tree_based 給個常見初始值 根據是否類別不平衡調節?
max_depth,min_child_weight,gamma,subsample,scale_pos_weight?
max_depth=3 起始值在4-6之間都是不錯的選擇。?
min_child_weight比較小的值解決極不平衡的分類問題eg:1?
subsample, colsample_bytree = 0.8: 這個是最常見的初始值了?
scale_pos_weight = 1: 這個值是因為類別十分不平衡。?
第二步: max_depth 和 min_weight 對最終結果有很大的影響?
‘max_depth’:range(3,10,2),?
‘min_child_weight’:range(1,6,2)?
先大范圍地粗調參數,然后再小范圍地微調。?
第三步:gamma參數調優?
‘gamma’:[i/10.0 for i in range(0,5)]?
第四步:調整subsample 和 colsample_bytree 參數?
‘subsample’:[i/100.0 for i in range(75,90,5)],?
‘colsample_bytree’:[i/100.0 for i in range(75,90,5)]?
第五步:正則化參數調優?
‘reg_alpha’:[1e-5, 1e-2, 0.1, 1, 100]?
‘reg_lambda’?
第六步:降低學習速率?
learning_rate =0.01,
?
from sklearn.model_selection import GridSearchCV parameters= [{'learning_rate':[0.01,0.1,0.3],'n_estimators':[1000,1200,1500,2000,2500]}] clf = GridSearchCV(XGBClassifier( max_depth=3, min_child_weight=1, gamma=0.5, subsample=0.6, colsample_bytree=0.6, objective= 'binary:logistic', #邏輯回歸損失函數 scale_pos_weight=1, reg_alpha=0, reg_lambda=1, seed=27 ), param_grid=parameters,scoring='roc_auc') clf.fit(X_train, y_train) print(clf.best_params_) y_pre= clf.predict(X_test) y_pro= clf.predict_proba(X_test)[:,1] print "AUC Score : %f" % metrics.roc_auc_score(y_test, y_pro) print"Accuracy : %.4g" % metrics.accuracy_score(y_test, y_pre)?
輸出特征重要性
import pandas as pd import matplotlib.pylab as plt feat_imp = pd.Series(clf.booster().get_fscore()).sort_values(ascending=False) #新版需要轉換成dict or list #feat_imp = pd.Series(dict(clf.get_booster().get_fscore())).sort_values(ascending=False) #plt.bar(feat_imp.index, feat_imp) feat_imp.plot(kind='bar', title='Feature Importances') plt.ylabel('Feature Importance Score') plt.show()python風控評分卡建模和風控常識
https://study.163.com/course/introduction.htm?courseId=1005214003&utm_campaign=commission&utm_source=cp-400000000398149&utm_medium=share
?轉載于:https://www.cnblogs.com/webRobot/p/9221824.html
總結
以上是生活随笔為你收集整理的xgboost调参指南的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: loj2538 「PKUWC2018」S
- 下一篇: Vue 路由的嵌套