异常:传递的模型不可调用,无法使用给定的掩码直接分析



我正在处理一个回归问题,我使用StackingRegressor来训练数据,然后在测试集上进行预测。为了模型的可解释性,我使用了如下SHAP:

import xgboost
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import StackingRegressor
import shap
# train a model
X, y = shap.datasets.boston()
stkr = StackingRegressor(
estimators = [('xgbr', xgboost.XGBRegressor()), ('rfr', RandomForestRegressor())],
final_estimator = xgboost.XGBRegressor(),
cv = 3
)

model = stkr.fit(X, y)
explainer = shap.Explainer(model)
shap_values = explainer(X)
shap.summary_plot(explainer(X), X)

运行此代码后,我面临以下错误:

Exception: The passed model is not callable and cannot be analyzed directly with the given masker! Model: StackingRegressor

我不知道为什么我会出现The passed model is not callable and cannot be analyzed directly with the given masker! Model: StackingRegressor错误,而我可以使用相同的代码,用RandomForestRegressorXGBoostRegressor替换StackingRegressor,并毫无问题地运行它。

有人知道吗?

我在不同的模型中遇到了同样的问题。对我有效的解决方案是使用KernelExplainer而不是explainer。此外,您需要使用model.prpredict函数,而不仅仅是模型。请注意,要获得shaps值,您需要使用KernelExplainer。shap_values((使用函数

所以我认为这应该有效:

explainer = shap.KernelExplainer(model.predict, X)
shap_values = explainer.shap_values(X)
shap.summary_plot(shap_values, X_train, plot_type="bar")

您使用的是哪种版本的shap?我刚刚发现了这个错误,并通过将版本从0.39.0升级到0.40.0 来修复它

不确定可以帮助。

我遇到了完全相同的问题,发现一些模型不受SHAP的支持,对我有效的方法要简单得多,取代

explainer = shap.Explainer(model)

带有:

explainer = shap.Explainer(model.predict)

您可以阅读本期以了解更多详细信息,以了解modelmodel.predict之间的差异。使用Shap获得预测解释的正确方法是什么?

最新更新