Search code examples
pythonshap

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


I want to use the python Shap module to interpret user supplied nonlinear functions. I'll take just one simple example as a representative, but it cannot run successfully. I would like to ask if Shap can be used for this simple model and if yes how to implement it.

Here is my code.

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)

Below are the error messages

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

Solution

  • Did you mean this: 10 datapoints, 2 features, 1 outcome?

    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)