1 feature importance
gradient boosting 有一個優點是可以給出訓練好的模型的特征重要性,這樣就可以知道哪些變量需要被保留,哪些可以舍棄。
首先要進入兩個類:
from xgboost import plot_importance
from matplotlib import pyplot
然后在model fit后面添加打印或繪制特征重要性:
model.fit(X, y)
plot_importance(model)
pyplot.show()
2 參數優化
XGBoost中提供GridSearchCV方法來對一些重要的超參進行調整,例如:
learning_rate
tree_depth
subsample
n_estimators
max_depth
當然,大多時候學習率的大小一定程度上很影響模型的穩定性,學習率較小容易過擬合,學習率較大又容易欠擬合,所以很多時候都會先考慮對學習率進行調整。
引入如下兩個類:
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedKFold
將要嘗試的學習率的值放在一個list中即可:
learning_rate = [0.005, 0.001, 0.01, 0.1, 0.2, 0.3]
model = XGBClassifier()
learning_rate = [0.005, 0.001, 0.01, 0.1, 0.2, 0.3]
param_grid = dict(learning_rate=learning_rate)
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=7)
grid_search = GridSearchCV(model, param_grid, scoring="neg_log_loss", n_jobs=-1, cv=kfold)
grid_result = grid_search.fit(X, Y)