視覺化單一 XGBoost 決策樹
現在你已經用 XGBoost 建立並評估了回歸與分類模型,接下來要學習如何用視覺化方式探索你的模型。這裡,你會從使用完整房價資料集訓練出的、已經完成提升(boosting)的模型中,視覺化單一樹。
XGBoost 提供 plot_tree() 函式,能輕鬆完成這類視覺化。當你用 XGBoost 的學習 API 訓練好模型後,可以將模型傳入 plot_tree(),並透過 num_trees 參數指定要繪製的樹編號。
本練習屬於課程
使用 XGBoost 的極端梯度提升
練習說明
- 建立一個參數字典,其中
"objective"設為"reg:squarederror","max_depth"設為2。 - 使用
10次提升迭代和你建立的參數字典來訓練模型。將結果存成xg_reg。 - 使用
xgb.plot_tree()繪製第一棵樹。此函式需要兩個引數:模型(此處為xg_reg)以及 0 起始的num_trees。因此要繪製第一棵樹,請指定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()