剪枝引數

調參策略
波士頓房價資料集實戰
import datetime
import xgboost as xgb
import matplotlib.pyplot as plt
from time import time
from sklearn.datasets import load_boston
# 加載資料
data = load_boston()
X = data.data
y = data.target
# 讀取全資料
dfull = xgb.DMatrix(X,y)
# 引數設定
param1 = {'silent':True
,'obj':'reg:linear'
,"subsample":1
,"max_depth":6
,"eta":0.3
,"gamma":0
,"lambda":1
,"alpha":0
,"colsample_bytree":1
,"colsample_bylevel":1
,"colsample_bynode":1
,"nfold":5
,'verbosity':0}
num_round = 200
# 計算模型訓練時間
time0 = time()
cvresult1 = xgb.cv(param1, dfull, num_round)
print(datetime.datetime.fromtimestamp(time()-time0).strftime("%M:%S:%f"))
# 繪制迭代程序的均方誤差
fig,ax = plt.subplots(1,figsize=(15,10))
ax.grid()
ax.plot(range(1,201),cvresult1.iloc[:,0],c="red",label="train,original")
ax.plot(range(1,201),cvresult1.iloc[:,2],c="orange",label="test,original")
ax.legend(fontsize="xx-large")
plt.show()

# 調參結果1
param2 = {'silent':True
,'obj':'reg:linear'
,"subsample":1
,"max_depth":4
,"eta":0.05
,"gamma":20
,"lambda":3.5
,"alpha":0.2
,"colsample_bytree":0.4
,"colsample_bylevel":0.6
,"colsample_bynode":1
,"nfold":5
,'verbosity':0}
# 調參結果2
param3 = {'silent':True
,'obj':'reg:linear'
,"subsample":1
,"max_depth":2
,"eta":0.05
,"gamma":0
,"lambda":1
,"alpha":0
,"colsample_bytree":1
,"colsample_bylevel":0.4
,"colsample_bynode":1
,"nfold":5
,'verbosity':0}
# 繪制對比圖
fig,ax = plt.subplots(1,figsize=(15,8))
ax.set_ylim(top=5)
ax.grid()
ax.plot(range(1,201),cvresult1.iloc[:,0],c="red",label="train,original")
ax.plot(range(1,201),cvresult1.iloc[:,2],c="orange",label="test,original")
ax.plot(range(1,201),cvresult2.iloc[:,0],c="green",label="train,last")
ax.plot(range(1,201),cvresult2.iloc[:,2],c="blue",label="test,last")
ax.plot(range(1,201),cvresult3.iloc[:,0],c="gray",label="train,this")
ax.plot(range(1,201),cvresult3.iloc[:,2],c="pink",label="test,this")
ax.legend(fontsize="xx-large")
plt.show()

從上圖可以看到,XGBoost模型通過剪枝,模型的過擬合被削弱,泛化能力增強,且模型的復雜度降低!!!
調參建議
- 可以使用網格搜索進行調參,但是建議至少先使用xgboost.cv來確認引數的范圍,否則很可能花很長的時間做了無用功,并且,在使用網格搜索的時候,最好不要一次性將所有的引數都放入進行搜索,最多一次兩三個,有一些互相影響的引數需要放在一起使用,比如學習率eta和樹的數量n_estimators(num_round),
- 調參的時候引數的順序也會影響調參結果,因此在現實中,我們會優先調整那些對模型影響巨大的引數,在這里,我建議的剪枝上的調參順序是:n_estimators(num_round)與eta共同調節,gamma或者max_depth,采樣和抽樣引數(縱向抽樣影響更大),最后才是正則化的兩個引數,當然,可以根據自己的需求來進行調整,
- 若調參之后測驗集上的效果還沒有原始設定上的效果好,但交叉驗證曲線確實顯示測驗集和訓練集上的模型評估效果是更加接近的,推薦使用調參之后的效果,我們希望增強模型的泛化能力,然而泛化能力的增強并不代表著在新資料集上模型的結果一定優秀,因為未知資料集并非一定符合全資料的分布,在一組未知資料上表現十分優秀,也不一定就能夠在其他的未知資料集上表現優秀,因此不必過于糾結在現有的測驗集上是否表現優秀,當然了,在現有資料上如果能夠實作訓練集和測驗集都非常優秀,那模型的泛化能力自然也會是很強的,
繼續加油,我們一定會成功的!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/423313.html
標籤:AI
上一篇:Machine Learning Lecture Notes
下一篇:論文寫作技巧總結
