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

SHAP瀑布图基准值异常及柱状图无特征值显示问题求助

问题解决方案

一、瀑布图基准值与预测概率不符的问题

原因分析

你设置了scale_pos_weight=50处理类别不平衡,同时使用过采样后的X_train_ada作为TreeExplainer的背景数据,导致基准值(背景数据的平均预测概率)被拉高,和测试集原始分布的预测概率(0.11)不匹配。另外,TreeExplainer在model_output='probability'模式下,基准值是模型对背景数据的平均预测概率,若背景数据是过采样后的不平衡数据,自然会偏向正类概率。

解决步骤

  1. 更换背景数据为原始训练集:将TreeExplainer的背景数据从X_train_ada改为未过采样的X_train,确保基准值反映原始数据的模型平均输出:
explainer = shap.TreeExplainer(mod_choice, X_train, model_output='probability')
  1. 验证基准值合理性:重新计算后,基准值应该接近训练集正类的平均预测概率,和测试集分布对齐。如果仍有偏差,检查X_train是否和Y_train的分布匹配,确保没有数据泄露或预处理不一致的问题。

二、bar图y轴仅显示特征名、无特征值的问题

原因分析

shap.plots.bar()默认仅展示特征的SHAP值绝对值排序,不会显示样本的具体特征取值,这是该函数的默认行为。

解决步骤

若需在bar图中同时显示特征名和对应样本的特征值,可通过以下两种方式实现:

  1. 改用瀑布图(推荐):shap.plots.waterfall(shap_values[19])本身会在每个特征条右侧显示该样本的具体取值,直接满足需求。

  2. 自定义bar图添加特征值:结合matplotlib手动绘制并添加标签,示例代码如下:

import matplotlib.pyplot as plt

# 获取单个样本的SHAP值和对应特征
sample_shap = shap_values[19]
feature_names = sample_shap.feature_names
feature_values = X_validation.iloc[19].values
shap_values_abs = abs(sample_shap.values)

# 按SHAP值绝对值排序
sorted_idx = shap_values_abs.argsort()[::-1]
sorted_features = [feature_names[i] for i in sorted_idx]
sorted_values = [feature_values[i] for i in sorted_idx]
sorted_shap = shap_values_abs[sorted_idx]

# 绘制bar图
plt.figure(figsize=(10, 8))
bars = plt.barh(range(len(sorted_features)), sorted_shap)
plt.yticks(range(len(sorted_features)), [f"{feat} = {val:.2f}" for feat, val in zip(sorted_features, sorted_values)])
plt.xlabel("|SHAP Value|")
plt.title("Feature SHAP Values for Sample 19")
plt.gca().invert_yaxis()
plt.show()

内容的提问来源于stack exchange,提问作者Giant Steps

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:13:43