การแสดงผลต้นไม้ XGBoost แต่ละต้น
หลังจากที่ใช้ XGBoost สร้างและประเมินทั้งโมเดล regression และ classification แล้ว ถึงเวลาเรียนรู้วิธีสำรวจโมเดลในเชิงภาพ ในแบบฝึกหัดนี้ จะได้แสดงผลต้นไม้แต่ละต้นจากโมเดลที่ XGBoost สร้างขึ้นโดยใช้ชุดข้อมูลบ้านทั้งหมด
XGBoost มีฟังก์ชัน plot_tree() ที่ช่วยให้การแสดงผลประเภทนี้ทำได้ง่าย เมื่อเทรนโมเดลด้วย XGBoost learning API แล้ว สามารถส่งโมเดลนั้นเข้าไปใน plot_tree() พร้อมกับระบุจำนวนต้นไม้ที่ต้องการพล็อตผ่าน argument num_trees
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Extreme Gradient Boosting with XGBoost
คำแนะนำการฝึกหัด
- สร้าง parameter dictionary โดยกำหนด
"objective"เป็น"reg:squarederror"และ"max_depth"เป็น2 - เทรนโมเดลด้วย
10รอบการ boosting โดยใช้ parameter dictionary ที่สร้างไว้ แล้วบันทึกผลลัพธ์ไว้ในxg_reg - พล็อตต้นไม้ต้นแรกด้วย
xgb.plot_tree()ซึ่งรับ argument 2 ตัว ได้แก่ โมเดล (ในที่นี้คือxg_reg) และnum_treesที่นับเริ่มจาก 0 ดังนั้นในการพล็อตต้นไม้ต้นแรก ให้ระบุnum_trees=0 - พล็อตต้นไม้ต้นที่ 5
- พล็อตต้นไม้ต้นสุดท้าย (ต้นที่ 10) ในแนวนอน โดยระบุ keyword argument เพิ่มเติมเป็น
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()