【发布时间】:2022-01-23 18:40:58
【问题描述】:
我在 Visual Studio 代码中有这段代码:
import pandas as pd
import numpy as np
import shap
import matplotlib.pyplot as plt
import xgboost as xgb
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_validate, cross_val_score
from sklearn.metrics import classification_report, ConfusionMatrixDisplay, accuracy_score
df = pd.read_csv("./mydataset.csv")
target=df.pop('target')
X_train, X_test, y_train, y_test = train_test_split(df, target, test_size=0.2, random_state=22)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=22)
xgb_model = xgb.XGBClassifier(eval_metric='mlogloss',use_label_encoder =False)
xgb_fitted = xgb_model.fit(X_train, y_train)
explainer = shap.TreeExplainer(xgb_fitted)
shap_values = explainer.shap_values(X_test)
shap.summary_plot(shap_values[1], X_test)
shap.summary_plot(shap_values[1], X_test, plot_type="bar")
当我运行这段代码时,我收到了这个错误:
Summary plots need a matrix of shap_values, not a vector.
在shap.summary_plot 线上。
问题是什么,我该如何解决?
以上代码基于此代码示例:https://github.com/slundberg/shap。
数据集如下:
Cat1,Cat2,Age,Cat3,Cat4,target
0,0,18,1,0,1
0,0,17,1,0,1
0,0,15,1,1,1
0,0,15,1,0,1
0,0,16,1,0,1
0,1,16,1,1,1
0,1,16,1,1,1
0,0,17,1,0,1
0,1,15,1,1,1
0,1,15,1,0,1
0,0,15,1,0,1
0,0,15,1,0,1
0,1,15,1,1,1
0,1,15,1,0,1
0,1,15,1,0,1
0,0,16,1,0,1
0,0,16,1,0,1
0,0,16,1,0,1
0,1,17,1,0,0
0,1,16,1,1,1
0,1,15,1,0,1
0,1,15,1,0,1
0,1,16,1,1,1
0,1,16,1,1,1
0,0,15,0,0,1
0,0,16,1,0,1
0,1,15,1,0,1
请注意,实际数据有 700 行,但我复制了一小部分只是为了展示数据的样子。
编辑 1
这个问题的主要原因是要了解在使用不同的分类时应该如何更改代码。
我最初有一个带有 lgmb 的示例代码,但当我将其更改为 xgboost 时,它会在摘要图上产生错误。
为了说明我的意思,我开发了以下示例代码:
import pandas as pd
import shap
import lightgbm as lgb
import xgboost as xgb
from sklearn.model_selection import train_test_split
df = pd.read_csv("./mydataset.csv")
target=df.pop('target')
X_train, X_test, y_train, y_test = train_test_split(df, target, test_size=0.2, random_state=22)
# select one of the two models
model = xgb.XGBClassifier()
#model = lgb.LGBMClassifier()
model_fitted = model.fit(X_train, y_train)
explainer = shap.Explainer(model_fitted)
shap_values = explainer.shap_values(X_test)
shap.summary_plot(shap_values[1], X_test)
shap.summary_plot(shap_values[1], X_test, plot_type="bar")
如果我使用 LGBM 模型,它运行良好,如果我使用 XGBoost,它会失败。有什么区别以及我应该如何更改 XGBoost 行为类似于 LGBM 和应用程序工作的代码。
【问题讨论】:
-
什么是
mydataset.csv? -
@SergeyBushmanov 该文件包含具有一些特征和目标的示例数据集。我不认为问题出在数据集上。
-
@mans 你能提供一些示例数据吗?可能会发生此错误,因为
shap_values可能是 (m, n) 维,shap_values[1]可能是一维向量。 -
@mans 我熟悉 DS 流程。问题是“显示您的数据”,或提供minimal reproducible example。附注:
target=df['target']应为target=df.pop['target']。请向我们展示您的数据。 -
@MiguelTrejo,请在编辑后的问题中找到所需的信息。需要注意的是,如果我使用shap.plot.bar(),那么我没有任何问题。
标签: python scikit-learn artificial-intelligence shap xai