我已经训练了一个 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 绘图函数即可获得您想要的结果。绘图函数可以将重要性字典作为其第一个参数,您可以直接从 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/