-1

我嘗試從我的數據框中獲取每個特徵的重要性權重。 我用這個代碼scikit文檔:使用RandomClassifier獲取重要特徵Scikit

names=['Class label', 'Alcohol', 
'Malic acid', 'Ash', 
'Alcalinity of ash', 'Magnesium', 
'Total phenols', 'Flavanoids', 
'Nonflavanoid phenols', 
'Proanthocyanins', 
'Color intensity', 'Hue', 
'OD280/OD315 of diluted wines', 
'Proline'] 
df_wine = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data', header=None,names=names) 



from sklearn.ensemble import RandomForestClassifier 
forest = RandomForestClassifier(n_estimators=10000, 
random_state=0, 
n_jobs=-1) 
forest.fit(X_train, y_train) 

feat_labels = df_wine.columns[1:] 
importances = forest.feature_importances_ 
indices = np.argsort(importances)[::-1] 
for f in range(X_train.shape[1]): 
    print("%2d) %-*s %f" % (f + 1, 30,feat_labels[f], importances[indices[f]])) 

但是,儘管我明白np.argsort方法,我還是不理解這個for循環。 爲什麼我們使用索引來索引「重要性」數組?爲什麼我們不能簡單地使用這樣的代碼:

for f in range(X_train.shape[1]): 
print("%2d) %-*s %f" % (f + 1, 30,feat_labels[f], importances[f])) 

輸出的情況下,使用 「重要度[指數並[f]]」(前5行)的:

1) Alcohol      0.182483 
2) Malic acid      0.158610 
3) Ash       0.150948 
4) Alcalinity of ash    0.131987 
5) Magnesium      0.106589 

輸出中的情況下,「重要性有關[F]「(第5行):

1) Alcohol      0.106589 
2) Malic acid      0.025400 
3) Ash       0.013916 
4) Alcalinity of ash    0.032033 
5) Magnesium      0.022078 
+0

請添加一個鏈接到你引用的例子。 –

+0

http://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html – mokebe

回答

0

這不是什麼被放置在文檔,仔細一看,上面寫着

# FROM DOCS 
for f in range(X.shape[1]): 
    print("%d. feature %d (%f)" % (f + 1, indices[f], importances[indices[f]])) 

這是正確的,而不是

# FROM YOUR QUESTION 
for f in range(X_train.shape[1]): 
    print("%2d) %-*s %f" % (f + 1, 30,feat_labels[f], importances[indices[f]])) 

這是不對的。如果你想使用feat_labels你應該做

# CORRECT SOLUTION 
for f in range(X_train.shape[1]): 
    print("%2d) %-*s %f" % (f + 1, 30,feat_labels[indices[f]], importances[indices[f]])) 

他們的做法是使用,因爲他們希望在降低功能重要度的順序重複,不使用「指數」將使用的功能,而不是排序。兩者都很好,唯一不正確的是你提出的第一個 - 這是兩種方法的混合,並且錯誤地將重要性賦予特徵。

相關問題