使用 early_stopping 自动选择 boosting 轮数
现在,您无需手动挑选最佳的 boosting 轮数,可以在 xgb.cv() 中让 XGBoost 自动为您选择。这是通过一种称为 early stopping(提前停止) 的技术实现的。
Early stopping 的做法是:每完成一轮 boosting,就在保留集上评估 XGBoost 模型;如果在给定的若干轮中,保留集上的度量(本题中为 "rmse")不再提升,就停止继续生成新的 boosting 轮(从而提前结束模型训练)。在这里,您将把 early_stopping_rounds 参数与一个较大的潜在 boosting 轮数(50)一起用于 xgb.cv()。请注意,如果保留集度量一直持续提升直到达到 num_boost_rounds,则不会发生提前停止。
此处我们已为您创建好了 DMatrix 和参数字典。您的任务是使用带有提前停止的交叉验证。开始吧!
本练习是课程的一部分
使用 XGBoost 的极端梯度提升
练习说明
- 使用 3 折交叉验证,启用提前停止,并将度量设置为
"rmse"。使用10个提前停止轮数和50个 boosting 轮数。指定seed为123,并确保输出为pandasDataFrame。请记得同时指定dtrain、params和metrics等其他参数。 - 打印
cv_results。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create your housing DMatrix: housing_dmatrix
housing_dmatrix = xgb.DMatrix(data=X, label=y)
# Create the parameter dictionary for each tree: params
params = {"objective":"reg:squarederror", "max_depth":4}
# Perform cross-validation with early stopping: cv_results
cv_results = ____
# Print cv_results
print(____)