調整 boosting 次數
先從參數調整開始,看看 boosting 次數(也就是你要建的樹的數量)如何影響 XGBoost 模型的樣本外效能。你會在 for 迴圈中使用 xgb.cv(),並針對每個 num_boost_round 參數建立一個模型。
這裡你會繼續使用 Ames 房價資料集。特徵已放在陣列 X,目標向量則在 y。
本練習屬於課程
使用 XGBoost 的極端梯度提升
練習說明
- 用
X和y建立一個名為housing_dmatrix的DMatrix。 - 建立名為
params的參數字典,設定合適的"objective"("reg:squarederror")與"max_depth"(設為3)。 - 在
for迴圈中遍歷num_rounds,並進行 3 折交叉驗證。每次迭代時,將目前的 boosting 次數(curr_num_rounds)作為num_boost_round參數傳入xgb.cv()。 - 將每個交叉驗證後的 XGBoost 模型在最後一個 boosting 回合的 RMSE,加入
final_rmse_per_round清單。 num_rounds與final_rmse_per_round已經被 zip 並轉成 DataFrame,讓你可以輕鬆比較每個 boosting 回合的表現。按下「Submit Answer」即可查看結果!
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create the DMatrix: housing_dmatrix
housing_dmatrix = ____
# Create the parameter dictionary for each tree: params
params = {"____":"____", "____":____}
# Create list of number of boosting rounds
num_rounds = [5, 10, 15]
# Empty list to store final round rmse per XGBoost model
final_rmse_per_round = []
# Iterate over num_rounds and build one model per num_boost_round parameter
for curr_num_rounds in num_rounds:
# Perform cross-validation: cv_results
cv_results = ____(dtrain=____, params=____, nfold=3, num_boost_round=____, metrics="rmse", as_pandas=True, seed=123)
# Append final round RMSE
____.____(cv_results["test-rmse-mean"].tail().values[-1])
# Print the resultant DataFrame
num_rounds_rmses = list(zip(num_rounds, final_rmse_per_round))
print(pd.DataFrame(num_rounds_rmses,columns=["num_boosting_rounds","rmse"]))