可视化单棵 XGBoost 决策树
到目前为止,您已经使用 XGBoost 构建并评估了回归和分类模型。接下来,您需要学会如何直观地探索模型。在本练习中,您将从使用完整房价数据集训练得到的全量提升模型中,分别可视化其中的单棵树。
XGBoost 提供了 plot_tree() 函数,能方便地完成这类可视化。使用 XGBoost 学习 API 训练好模型后,您可以将模型对象传给 plot_tree(),并通过参数 num_trees 指定要绘制的树编号。
本练习是课程的一部分
使用 XGBoost 的极端梯度提升
练习说明
- 创建一个参数字典,其中
"objective"设为"reg:squarederror","max_depth"设为2。 - 使用
10轮提升和您创建的参数字典训练模型。将结果保存为xg_reg。 - 使用
xgb.plot_tree()绘制第一棵树。它需要两个参数——模型(此处为xg_reg)和num_trees,且索引从 0 开始。因此要绘制第一棵树,请设定num_trees=0。 - 绘制第 5 棵树。
- 将最后一棵(第 10 棵)树横向绘制。为此,请额外指定关键字参数
rankdir="LR"。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create the DMatrix: housing_dmatrix
housing_dmatrix = xgb.DMatrix(data=X, label=y)
# Create the parameter dictionary: params
params = {"objective":"reg:squarederror", "max_depth":2}
# Train the model: xg_reg
xg_reg = xgb.train(params=params, dtrain=housing_dmatrix, num_boost_round=10)
# Plot the first tree
____
plt.show()
# Plot the fifth tree
____
plt.show()
# Plot the last tree sideways
____
plt.show()