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

如何在SHAP摘要图中绘制全部特征并显示SHAP值?

解决方案

1. 显示全部28个特征

shap.summary_plot 提供了 max_display 参数,默认值为20,直接将其设置为28即可强制展示所有目标特征。

2. 在条形图上标注SHAP值

由于你的模型是多输出(5个响应变量),shap_values 会返回一个包含5个数组的列表(每个数组对应一个响应变量的SHAP值)。需要先计算每个特征在所有输出上的平均绝对SHAP值,再通过Matplotlib的API在条形图上标注具体数值。

修改后的完整代码

import shap
import numpy as np
import matplotlib.pyplot as plt

# 创建解释器
explainer = shap.DeepExplainer(model, PRED_train)
# 计算SHAP值
shap_values = explainer.shap_values(PRED_test)

# 计算每个特征在所有输出上的平均绝对SHAP值
mean_abs_shap = np.mean([np.abs(sv).mean(axis=0) for sv in shap_values], axis=0)

# 绘制摘要条形图,设置显示全部28个特征
fig, ax = plt.subplots()
shap.summary_plot(shap_values, features=PRED_test, plot_type='bar', max_display=28, ax=ax)

# 在每个条形右侧标注SHAP值(保留4位小数,可按需调整)
for p in ax.patches:
    width = p.get_width()
    ax.text(width + 0.01, p.get_y() + p.get_height()/2, 
            f'{width:.4f}', ha='left', va='center')

plt.show()

补充说明

  • 如果你的 PRED_test 没有特征名称,条形图x轴会显示索引。可以手动传入特征名列表优化显示:
    # 示例:生成29个特征名称
    feature_names = [f'Feature_{i+1}' for i in range(29)]
    # 绘图时传入feature_names参数
    shap.summary_plot(shap_values, features=PRED_test, feature_names=feature_names, plot_type='bar', max_display=28, ax=ax)
    

内容的提问来源于stack exchange,提问作者Ellie Moh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:04:55