如何使用 Shap 解释用户提供的函数(Shapley Additive 解释)?

How to interpret user supplied function using Shap (Shapley Additive explanation)?

我想使用 python Shap 模块来解释用户提供的非线性函数。我就举一个简单的例子作为代表,但不能运行成功。我想问一下Shap是否可以用于这个简单的模型,如果可以如何实现。

这是我的代码。

import numpy as np
import shap

def f(x):
        y = x[0] ** 2.5 + 3 * x[1] + 10
        return np.array(y)
x = np.arange(20).reshape((2, 10))

explainer = shap.Explainer(f)
shap_values = explainer(x)

以下是错误信息

Traceback (most recent call last):
  File "D:\Python\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "E:\PYCHARM\lib\site-packages\shap\explainers\_permutation.py", line 74, in __call__
    return super().__call__(
  File "E:\PYCHARM\lib\site-packages\shap\explainers\_explainer.py", line 258, in __call__
    row_result = self.explain_row(
  File "E:\PYCHARM\lib\site-packages\shap\explainers\_permutation.py", line 132, in explain_row
    outputs = fm(masks, zero_index=0, batch_size=batch_size)
  File "E:\PYCHARM\lib\site-packages\shap\utils\_masked_model.py", line 64, in __call__
    return self._full_masking_call(full_masks, zero_index=zero_index, batch_size=batch_size)
  File "E:\PYCHARM\lib\site-packages\shap\utils\_masked_model.py", line 93, in _full_masking_call
    masked_inputs = self.masker(mask, *self.args)
TypeError: 'NoneType' object is not callable

您是不是这个意思:10 个数据点、2 个特征、1 个结果?

import numpy as np
from shap import KernelExplainer


def f(x):
    y = x[:, 0] ** 2.5 + 3 * x[:, 1] + 10
    return np.array(y)


x = np.arange(20).reshape((10,2))
explainer = KernelExplainer(f, x)
shap_values = explainer.shap_values(x)