ความสำคัญของ Feature ใน Gradient Boosting
เช่นเดียวกับ random forest เราสามารถดึงค่าความสำคัญของ feature (feature importances) จากโมเดล gradient boosting เพื่อทำความเข้าใจว่า feature ใดเป็นตัวทำนายที่ดีที่สุด บางครั้งการลองใช้โมเดลแบบ tree หลายๆ โมเดล แล้วเปรียบเทียบค่าความสำคัญของ feature จากทุกโมเดลก็เป็นประโยชน์ เพราะช่วยปรับสมดุลความผิดปกติที่อาจเกิดขึ้นจากโมเดลใดโมเดลหนึ่ง
ค่าความสำคัญของ feature จะถูกเก็บในรูปแบบ numpy array ที่ property .feature_importances_ ของโมเดล gradient boosting เราจะต้องหา index ที่เรียงลำดับแล้วของค่าความสำคัญโดยใช้ np.argsort() เพื่อสร้างกราฟที่อ่านง่าย และเนื่องจากต้องการแสดง feature จากมากไปน้อย จึงใช้การ indexing ของ Python เพื่อกลับลำดับดังนี้: feat_importances[::-1]
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Machine Learning สำหรับการเงินด้วย Python
คำแนะนำการฝึกหัด
- กลับลำดับตัวแปร
sorted_indexจากมากไปน้อยโดยใช้การ indexing ของ Python - สร้างรายการ label ของ feature ที่เรียงลำดับแล้วในชื่อ
labelsโดยแปลงfeature_namesเป็น numpy array แล้ว index ด้วยsorted_index - สร้างกราฟแท่ง (bar plot) โดยใช้ค่า xticks,
feature_importancesที่ index ด้วยsorted_indexและใช้labelsเป็น label ของ xtick
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Extract feature importances from the fitted gradient boosting model
feature_importances = gbr.feature_importances_
# Get the indices of the largest to smallest feature importances
sorted_index = np.argsort(feature_importances)[::____]
x = range(features.shape[1])
# Create tick labels
labels = np.array(feature_names)[____]
plt.bar(____, feature_importances[____], tick_label=____)
# Set the tick lables to be the feature names, according to the sorted feature_idx
plt.xticks(rotation=90)
plt.show()