调优提升轮数
我们先从参数调优入手,看看提升轮数(您要构建的树的数量)如何影响 XGBoost 模型的样本外性能。您将把 xgb.cv() 放在 for 循环中,每个 num_boost_round 参数训练一个模型。
这里,您将继续使用 Ames 房价数据集。特征保存在数组 X 中,目标向量在 y 中。
本练习是课程的一部分
使用 XGBoost 的极端梯度提升
练习说明
- 使用
X和y创建名为housing_dmatrix的DMatrix。 - 创建名为
params的参数字典,传入合适的"objective"("reg:squarederror")和"max_depth"(设为3)。 - 在
for循环中遍历num_rounds并执行 3 折交叉验证。每次迭代中,将当前的提升轮数(curr_num_rounds)作为num_boost_round的参数传递给xgb.cv()。 - 将每个交叉验证后的 XGBoost 模型在最终提升轮次上的 RMSE 追加到列表
final_rmse_per_round中。 num_rounds与final_rmse_per_round已经 zip 并转换为 DataFrame,便于您查看模型在不同提升轮数下的表现。点击 "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"]))