開始使用免費開始

隨機森林的特徵重要性

樹狀方法的一大優點是可以擷取特徵重要性。這能以量化方式衡量每個特徵對預測的貢獻。它能幫助你聚焦在表現最好的特徵,進一步強化或調校;也能協助移除對模型造成雜訊的無用特徵。

sklearn 中的樹模型在訓練完成後會提供 .feature_importances_ 屬性,裡面存放各特徵的重要性分數。我們需要用 np.argsort() 取得排序後的索引,才能繪製由高到低排列的特徵重要性長條圖。

本練習屬於課程

Python 金融 Machine Learning

檢視課程

練習說明

  • 使用隨機森林模型(rfr)的 feature_importances_ 屬性,將特徵重要性存入 importances 變數。
  • 使用 numpy 的 argsort,取得特徵重要性由大到小的索引,並將排序後的索引存到 sorted_index 變數。
  • 將 xtick 標籤設定為特徵名稱,存入 labels 變數,並使用 sorted_index 清單。為了能以 sorted_index 清單索引,必須先把 feature_names 轉為 numpy 陣列。

動手互動練習

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

# Get feature importances from our random forest model
importances = rfr.____

# Get the index of importances from greatest importance to least
sorted_index = ____(importances)[::-1]
x = range(len(importances))

# Create tick labels 
labels = np.array(____)[____]
plt.bar(x, importances[sorted_index], tick_label=labels)

# Rotate tick labels to vertical
plt.xticks(rotation=90)
plt.show()
編輯並執行程式碼