python - XGBoost 中的绘图编号格式plot_importance()

标签 python matplotlib plot xgboost boosting

我已经训练了一个 XGBoost 模型,并使用plot_importance() 来绘制训练模型中最重要的特征。尽管如此,图中的数字有几个小数值,这些值淹没了绘图并且不适合绘图。

我搜索了绘图格式选项,但我只找到了如何格式化轴(尝试格式化 X 轴,希望它也能格式化相应的轴)

我在 Jupyter Notebook 中工作(如果这有什么区别的话)。代码如下:

xg_reg = xgb.XGBClassifier(
                objective = 'binary:logistic',
                colsample_bytree = 0.4,
                learning_rate = 0.01,
                max_depth = 15, 
                alpha = 0.1, 
                n_estimators = 5,
                subsample = 0.5,
                scale_pos_weight = 4
                )
xg_reg.fit(X_train, y_train) 
preds = xg_reg.predict(X_test)

ax = xgb.plot_importance(xg_reg, max_num_features=3, importance_type='gain', show_values=True) 

fig = ax.figure
fig.set_size_inches(10, 3)

我有什么遗漏的吗?是否有任何格式化函数或参数要传递?

我希望能够格式化特征重要性分数,或者至少删除小数部分(例如“25”而不是“25.66521”)。 下面附上当前图。

xgboost_feature_importance_scores

最佳答案

无需编辑 xgboost 绘图函数即可获得您想要的结果。绘图函数可以将重要性字典作为其第一个参数,您可以直接从 xgboost 模型创建该字典,然后进行编辑。如果您想为功能名称制作更友好的标签,这也很方便。

# Get the booster from the xgbmodel
booster = xg_reg.get_booster()

# Get the importance dictionary (by gain) from the booster
importance = booster.get_score(importance_type="gain")

# make your changes
for key in importance.keys():
    importance[key] = round(importance[key],2)

# provide the importance dictionary to the plotting function
ax = plot_importance(importance, max_num_features=3, importance_type='gain', show_values=True)

关于python - XGBoost 中的绘图编号格式plot_importance(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56061712/

相关文章:

python - 如何验证 django 设置是否正确应用?

Python 绘图库

Python:如何使 'anchor' 文本始终可见和 set_text 方法 Matplotlib

python - 在 matplotlib 图上绘制裁剪后的背景图像

python - 使用 Matloptlib 将图像(只有内容,没有坐标轴或其他任何东西)保存到文件中

python - 如何使用pywinauto模拟游戏中的按键

python - 删除了默认用户,如何找回

python - 无法使用基于 python 的库 ftplib 连接到本地 FTP 服务器

python - 带有错误栏的空圆圈

python - 在 matplotlib 中格式化日期时间 xlabels(pandas df.plot() 方法)