使用随机森林训练模型
from sklearn.ensemble import RandomForestClassifier
feat_lables = trainx.columns
forest = RandomForestClassifier(n_estimators=10000, random_state=0,n_jobs=1)
forest.fit(trainx, trainy)
importance = forest.feature_importances_
imp_result = np.argsort(importance)[::-1]
imp_result [0:5]
输出特征排序
for i in range(trainx.shape[1]):
print("%2d. %-*s %f"%(f+1, 30, feat_labels[f], importance[imp_result[f]]) )
特征重要性绘图
plt.title('Feature Importance')
plt.bar(range(trainx.shape[1]), importances[indices], color='lightblue', align='center')
plt.xticks(range(trainx.shape[1]), feat_labels, rotation=90)
plt.xlim([-1, trainx.shape[1]])
plt.tight_layout()
plt.show()