SHAP中使用shap.summary_plot对多分类任务模型中特征重要性绘图

在文心一言中输入:

使用shap.summary_plot展示各个特征对模型输出类别的重要性

其输出的代码为(不正确):

python 复制代码
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
import shap

# 加载数据集(这里使用iris数据集作为例子)
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化SVM模型并进行训练
clf = svm.SVC(kernel='linear', probability=True, random_state=42)
clf.fit(X_train, y_train)

# 初始化SHAP解释器
explainer = shap.Explainer(clf.predict_proba, X_train)

# 计算测试集上每个预测的SHAP值
# 注意:这里我们使用predict_proba方法,因为它返回了每个类别的概率
shap_values = explainer(X_test)

# 使用summary_plot可视化特征重要性
shap.summary_plot(shap_values, X_test, feature_names=iris.feature_names)

以上代码没有静态错误,但是运行报错:

Traceback (most recent call last):

File "D:\Ethan\Projects\fattyLiver\test_shap_iris.py", line 27, in <module>

shap.summary_plot(shap_values, X_test, feature_names=iris.feature_names)

File "D:\Ethan\Projects\fattyLiver\venv\lib\site-packages\shap\plots\_beeswarm.py", line 605, in summary_legacy

feature_names=feature_namessort_inds,

TypeError: only integer scalar arrays can be converted to a scalar index

修改为如下代码(正确):

python 复制代码
import numpy as np
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm
import shap

# 加载数据集(这里使用iris数据集作为例子)
iris = datasets.load_iris()
X = iris.data
y = iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

# 初始化SVM模型并进行训练
clf = svm.SVC(kernel='linear', probability=True, random_state=42)
clf.fit(X_train, y_train)

# 初始化SHAP解释器
explainer = shap.Explainer(clf.predict_proba, X_train)

# 计算测试集上每个预测的SHAP值
# 注意:这里我们使用predict_proba方法,因为它返回了每个类别的概率
shap_values = explainer(X_test)

# 使用summary_plot可视化特征重要性
# shap.summary_plot(shap_values, X_test, feature_names=iris.feature_names)
list_of_2d_arrays = [shap_values.values[:, :, i] for i in range(3)]
shap.summary_plot(list_of_2d_arrays, X_test, feature_names=iris.feature_names, class_names=iris.target_names)

输出图片:

相关推荐
math_hongfan14 小时前
鸿蒙AI应用性能高级评测:推理延迟/内存占用/功耗/准确率四维指标评测体系与极致调优方案
人工智能·学习·华为·harmonyos·鸿蒙
苏灿烤鱼14 小时前
GitHub #1 拆解|它说自己在进化,但 worker 跑的是你本机权限,不是沙箱
人工智能·typescript·agent
火山引擎开发者社区16 小时前
漫话火山 Milvus|为 Agent、RAG 、语义搜索而生,AI 时代的极致性价比之选
人工智能
小趴蔡ha1 天前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda
jikemaoshiyanshi1 天前
AWS 中国峰会 2026 有哪些 AI Agent 相关演讲可以看?按业务、研发与生产阶段选看
大数据·人工智能
网易易盾1 天前
AI互动产品安全合规体系架构:制度/技术/运营/证据四层落地
人工智能·安全·aigc·内容安全
新知图书1 天前
4.3 链接速读
人工智能·语音识别·ai助手·千问
江苏久众新视1 天前
SOP-AI实战:基于AI视觉与视频检测,精准管控空调管件装配防漏防错
人工智能
u0103055271 天前
Java AWT鼠标事件全解析
人工智能·1024程序员节
tuanxiang1 天前
中英文AI检测的跨语系误判问题排查与修复
人工智能