shap.Explainer 构造函数错误要求未记录的位置参数

shap.Explainer constructor error asking for undocumented positional argument

我正在使用 python shap 包来更好地理解我的机器学习模型。 (来自 documentation:“SHAP(SHapley Additive exPlanations)是一种解释任何机器学习模型输出的博弈论方法。”下面是我遇到的错误的一个可重现的小例子:

Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import shap
>>> shap.__version__
'0.37.0'
>>> from sklearn.model_selection import train_test_split
>>> from sklearn.linear_model import LogisticRegression
>>> 
>>> iris = shap.datasets.iris()
>>> X_train, X_test, y_train, y_test = train_test_split(*iris, random_state=1)
>>> model = LogisticRegression(penalty='none', max_iter = 1000, random_state=1)
>>> model.fit(X_train, y_train)
>>> 
>>> explainer = shap.Explainer(model, data=X_train, masker=shap.maskers.Impute(),
...                            feature_names=X_train.columns, algorithm="linear")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() missing 1 required positional argument: 'data'

根据堆栈跟踪,错误似乎发生在顶层函数调用中,而不是在对 Impute() 的调用中。我也试过省略 data= 部分,这会引发同样的错误。这对我来说似乎很奇怪,因为 Explainer 对象的 documentation nor source code 都没有提到任何 data 参数(我验证它来自我正在使用的相同包版本):

__init__(model, masker=None, link=CPUDispatcher(<function identity>), algorithm='auto', output_names=None, feature_names=None, **kwargs)

有什么想法吗?这是一个错误,还是我遗漏了一些明显的东西?

Impute的初始化signature是:

def __init__(self, data, method="linear")

因此你的错误。所以,而不是:

explainer = shap.Explainer(model, data=X_train, masker=shap.maskers.Impute(),
                           feature_names=X_train.columns, algorithm="linear")

你应该 X_train 给掩蔽者:

explainer = shap.Explainer(model, masker=shap.maskers.Impute(data=X_train),
                           feature_names=X_train.columns, algorithm="linear")

因为 masker 负责处理新 API 中的数据。

不幸的是,即使这样也行不通,因为 Impute masker implies feature_perturbation = "correlation_dependent" and it doesn't seem ready

不过,Independent masker 运行良好:

import shap
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

iris = shap.datasets.iris()
X_train, X_test, y_train, y_test = train_test_split(*iris, random_state=1)
model = LogisticRegression(penalty="none", max_iter=1000, random_state=1)
model.fit(X_train, y_train)

masker = shap.maskers.Independent(data=X_test)

explainer = shap.Explainer(
    model, masker=masker, feature_names=X_train.columns, algorithm="linear"
)

sv = explainer(X_test)
sv.base_values[0]

array([-5.0060995 , 13.03460398, -8.02850448])

如果您的数据集中缺少数据,您可以根据自己喜欢的插补策略自行插补数据,并将其提供给 Independent