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

如何自定义shap.summary_plot中特征的显示顺序?

自定义SHAP summary_plot的特征显示顺序

可以手动指定特征的显示顺序,核心是按自定义顺序重新排列SHAP值、输入数据的特征列以及特征名称列表,以此覆盖默认的按重要性排序逻辑。

结合你的代码,具体实现步骤如下:

  1. 定义自定义特征顺序:明确你想要的特征展示顺序
  2. 映射特征索引:根据原特征名称列表,获取自定义顺序对应的特征索引
  3. 重排数据:按索引重新排列SHAP值和输入数据X的特征维度
  4. 调用绘图函数:传入重排后的数据和自定义特征名称

修改后的完整代码示例:

import matplotlib.pyplot as plt
import numpy as np
import shap
from tensorflow import keras
from tensorflow.keras import layers

X = np.array([[(1,2,3,3,1),(3,2,1,3,2),(3,2,2,3,3),(2,2,1,1,2),(2,1,1,1,1)],
              [(4,5,6,4,4),(5,6,4,3,2),(5,5,6,1,3),(3,3,3,2,2),(2,3,3,2,1)],
              [(7,8,9,4,7),(7,7,6,7,8),(5,8,7,8,8),(6,7,6,7,8),(5,7,6,6,6)],
              [(7,8,9,8,6),(6,6,7,8,6),(8,7,8,8,8),(8,6,7,8,7),(8,6,7,8,8)],
              [(4,5,6,5,5),(5,5,5,6,4),(6,5,5,5,6),(4,4,3,3,3),(5,5,4,4,5)],
              [(4,5,6,5,5),(5,5,5,6,4),(6,5,5,5,6),(4,4,3,3,3),(5,5,4,4,5)],
              [(1,2,3,3,1),(3,2,1,3,2),(3,2,2,3,3),(2,2,1,1,2),(2,1,1,1,1)]])
y = np.array([0, 1, 2, 2, 1, 1, 0])

# Updated model with correct input shape
model = keras.Sequential([
    layers.Conv1D(128, kernel_size=3, activation='relu',input_shape=(5,5)),
    layers.MaxPooling1D(pool_size=2),
    layers.LSTM(128, return_sequences=True),
    layers.Flatten(),
    layers.Dense(128, activation='relu'),
    layers.Dense(5, activation='softmax')  # Adjust the number of output units based on your problem (3 for 3 classes)
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Train the model
model.fit(X, y, epochs=10)

explainer = shap.GradientExplainer(model, X)
shap_values = explainer.shap_values(X)

cls = 0
idx = 0
feature_names = ["Feature1","Feature2","Feature4","Prova4","Feature5"]

# ---------------------- 新增自定义顺序处理代码 ----------------------
# 定义你想要的特征显示顺序
custom_feature_order = ["Feature5", "Prova4", "Feature2", "Feature1", "Feature4"]
# 获取自定义顺序对应的特征索引
feature_indices = [feature_names.index(name) for name in custom_feature_order]
# 重新排列SHAP值和X的特征维度
shap_values_custom = shap_values[cls][:, idx, :][:, feature_indices]
X_custom = X[:, idx, :][:, feature_indices]
# ---------------------- 自定义顺序处理结束 ----------------------

# 使用重排后的数据绘图
shap.summary_plot(shap_values_custom, X_custom, plot_type="bar", feature_names=custom_feature_order)

说明

  • 如果想直接使用feature_names的原始顺序(而非默认重要性排序),只需将custom_feature_order设为feature_names即可
  • 该方法适用于plot_type="bar"和其他类型的summary_plot,核心都是保证SHAP值、X数据、特征名称三者的顺序完全对应

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 22:06:07