特徵重要性
就算某些糖果屬性(例如是否含巧克力)非常受歡迎,也不代表它們對模型預測一定「重要」。在擬合完隨機森林模型後,你可以查看模型的 .feature_importances_ 屬性,了解哪些變數影響最大。你可以用 enumerate() 迴圈走訪特徵重要性陣列,檢查每個變數在模型中的重要程度。
如果你不熟悉 Python 的 enumerate() 函式,它可以在走訪清單時自動建立計數器。
本練習屬於課程
Python 的模型驗證
練習說明
- 迴圈走訪
rfr輸出的特徵重要性。 - 列印
X_train的欄位名稱,以及該欄位對應的重要性分數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Fit the model using X and y
rfr.fit(X_train, y_train)
# Print how important each column is to the model
for i, item in enumerate(rfr.____):
# Use i and item to print out the feature importance of each column
print("{0:s}: {1:.2f}".format(X_train.columns[____], ____))