开始使用免费开始使用

梯度提升的特征重要性

与随机森林类似,我们也可以从梯度提升模型中提取特征重要性,以了解哪些特征是最好的预测因子。有时,尝试不同的基于树的模型,并综合查看它们各自的特征重要性,会更有帮助。这有助于平均掉某个模型可能带来的偶然性。

特征重要性保存在梯度提升模型的 .feature_importances_ 属性中,类型为 numpy 数组。为了绘制清晰的图,我们需要使用 np.argsort() 获取特征重要性的排序索引。我们希望特征按从大到小的顺序排列,因此会用 Python 的索引将排序结果反转,例如 feat_importances[::-1]

本练习是课程的一部分

Python 金融机器学习

查看课程

练习说明

  • 使用 Python 索引将 sorted_index 反转,使其从大到小。
  • feature_names 转换为 numpy 数组,并用 sorted_index 进行索引,创建排序后的特征标签列表 labels
  • sorted_index 索引后的 feature_importances 作为柱状图的高度,设置刻度位置为 xticks,并将 labels 作为 x 轴刻度标签,绘制柱状图。

交互式实操练习

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

# Extract feature importances from the fitted gradient boosting model
feature_importances = gbr.feature_importances_

# Get the indices of the largest to smallest feature importances
sorted_index = np.argsort(feature_importances)[::____]
x = range(features.shape[1])

# Create tick labels 
labels = np.array(feature_names)[____]

plt.bar(____, feature_importances[____], tick_label=____)

# Set the tick lables to be the feature names, according to the sorted feature_idx
plt.xticks(rotation=90)
plt.show()
编辑并运行代码