如何根据 python 中 xgboost 的变量重要性绘制前 k 个变量?

How to plot top k variables by variables importance of xgboost in python?

在 python 中,如何按变量重要性绘制前 k 个变量?

当我使用 xgb.plot_importance 时,它总是绘制模型中训练的所有变量。

但是,我有超过 3000 个特征,我不想将它们全部绘制出来;我只关心影响力大的前100个变量。

我知道我可以从 xgb_model.get_score() 中提取变量重要性,returns 一个存储对(特征,重要性)的字典。也许这就是我可以从字典中提取前k个重要变量的方向。

但是我不知道如何创建一个像xgb.plot_importance一样风格的图片(直方图),如果我根据top k字典手动绘制。

或者有什么方法可以绘制前 k 个变量取决于 xgboost 内置 API?

只需使用 xgb.plot_importance() 中的 'max_num_features' 参数即可。

来自the documentation

max_num_features (int, default None) – Maximum number of top features displayed on plot. If None, all features will be displayed.

所以这样使用它:

xgb.plot_importance(..., ..., ..., max_num_features = 100)