最近读到了一本书,《Python机器学习经典实例》,里面有很多的机器学习实例,入门干货满满啊~
其中,有段代码,能够将重要特征可视化,并且降序排列,如下所示:
def plot_feature_importances(feature_importances,title,feature_names):
# 将重要性值标准化
feature_importances = 100.0*(feature_importances/max(feature_importances))
# 将得分从高到低排序
index_sorted = np.flipud(np.argsort(feature_importances))
# 让X坐标轴上的标签居中显示
pos = np.arange(index_sorted.shape[0])+0.5
plt.figure(figsize=(16,4))
plt.bar(pos,feature_importances[index_sorted],align='center')
plt.xticks(pos,feature_names[index_sorted])
plt.ylabel('Relative Importance')
plt.title(title)
plt.show()
执行这段代码:
plot_feature_importances(rfr.feature_importances_,'Random Forest regressor',feature_names)
输出如图所示: