You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XGBoost plot_importance无法完整显示长特征名求助

解决XGBoost特征重要性图长特征名截断及图像高度问题

以下是几个实用的解决思路:

1. 合理设置图像尺寸+预留左侧空间

不要只调宽度,根据特征数量设置匹配的高度,同时通过subplots_adjust给左侧留出足够显示长特征名的空间,避免过度拉宽图像:

from xgboost import plot_importance
import matplotlib.pyplot as plt
import os

# 根据特征数量调整figsize,比如20个特征设为宽12、高12
plt.figure(figsize=(12, 12))
plot_importance(search.best_estimator_)
# 左侧预留空间,left值按需调整(比如0.3)
plt.subplots_adjust(left=0.3)
# 自动适配边界避免裁剪
plt.savefig(os.path.join(self.model_save_directory, "feature_importance.png"), bbox_inches='tight')

2. 调整特征名显示样式

通过旋转标签、缩小字体让长名字完整显示:

plt.figure(figsize=(10, 10))
ax = plot_importance(search.best_estimator_)
# 旋转y轴标签45度并右对齐,同时缩小字体
ax.set_yticklabels(ax.get_yticklabels(), rotation=45, ha='right', fontsize=8)
plt.subplots_adjust(left=0.35)
plt.savefig(os.path.join(self.model_save_directory, "feature_importance.png"), bbox_inches='tight')

3. 横向展示特征重要性

将特征名放在x轴,横向布局更适配长文本:

plt.figure(figsize=(15, 8))
# 设置横向展示
plot_importance(search.best_estimator_, orientation='horizontal')
# 旋转x轴标签避免重叠
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
plt.savefig(os.path.join(self.model_save_directory, "feature_importance.png"))

4. 手动处理特征名(可选)

如果上述方法仍不满意,可预处理特征名插入换行符,让长名字自动换行:

import pandas as pd
# 获取特征名并插入换行
feature_names = search.best_estimator_.feature_names
formatted_names = []
for name in feature_names:
    # 每20个字符插入换行,或按空格拆分
    if len(name) > 20:
        split_name = '\n'.join([name[i:i+20] for i in range(0, len(name), 20)])
        formatted_names.append(split_name)
    else:
        formatted_names.append(name)

# 手动绘制特征重要性
importance = search.best_estimator_.feature_importances_
df = pd.DataFrame({'feature': formatted_names, 'importance': importance}).sort_values('importance', ascending=False)

plt.figure(figsize=(10, 12))
plt.barh(df['feature'], df['importance'])
plt.gca().invert_yaxis()  # 保持重要性从高到低的顺序
plt.tight_layout()
plt.savefig(os.path.join(self.model_save_directory, "feature_importance.png"))

内容的提问来源于stack exchange,提问作者Zag Gol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:10:40