开始使用免费开始使用

随机森林的特征重要性

树模型的一个有用特点是可以提取特征重要性分数。这是一种定量方法,用来衡量每个特征对预测的贡献有多大。它能帮助我们聚焦于效果最好的特征,进而增强或调优它们;也能帮助我们去除无用特征,避免模型被干扰。

sklearn 中的树模型在拟合后可以访问 .feature_importances_ 属性,其中保存了特征重要性分数。我们需要使用 np.argsort() 获取特征重要性排序后的索引,以便绘制一个美观的条形图(按重要性从高到低排序)。

本练习是课程的一部分

Python 金融机器学习

查看课程

练习说明

  • 使用随机森林模型(rfr)的 feature_importances_ 属性,将特征重要性提取到变量 importances 中。
  • 使用 numpy 的 argsort 按特征重要性从高到低获取索引,并将排序后的索引保存到变量 sorted_index 中。
  • 将 xtick 标签设置为变量 labels 中的特征名称,顺序使用 sorted_index 列表。需要先将 feature_names 转换为 numpy 数组,才能用 sorted_index 对其进行索引。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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()
编辑并运行代码