開始使用免費開始

梯度提升的特徵重要性

就像隨機森林一樣,我們可以從梯度提升模型中擷取特徵重要性,來了解哪些特徵最能預測目標。有時候比較不同的樹狀模型,並查看它們各自的特徵重要性,也是不錯的做法。這有助於平均化某個特定模型可能出現的特殊情況。

特徵重要性會以 numpy 陣列的形式,存放在梯度提升模型的 .feature_importances_ 屬性中。我們需要用 np.argsort() 取得特徵重要性的排序索引,才能畫出清晰的圖。我們想要從大到小排列特徵,因此會用 Python 的索引把排序後的結果反轉,如 feat_importances[::-1]

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 反轉 sorted_index 變數,使用 Python 索引由大到小排序。
  • 建立排序後的特徵標籤清單 labels:先把 feature_names 轉成 numpy 陣列,再用 sorted_index 索引。
  • 繪製長條圖:以 xticks 與用 sorted_index 索引過的 feature_importances 作為資料,並以 labels 作為 x 軸刻度標籤。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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()
編輯並執行程式碼