ShapleyExplainer#

class sdm.explain.ShapleyExplainer(**kwargs: Any)#

Bases: object

Compute Shapley values of preprocessed feature columns from the “A Unified Approach to Interpreting Model Predictions” paper.

A fitted model is evaluated on subsets of the columns of each query row, and the columns outside a subset are removed by imputation. The resulting attributions describe each feature’s contribution to the difference between the row’s prediction and the baseline prediction.

Note

ShapleyExplainer requires shapiq>=1.8. See here on how to install.

import sdm
import torch

x_context = sdm.TableTensor.from_tensor(
    torch.tensor([
        [-3., 0.],
        [-2., 1.],
        [-1., 2.],
        [ 1., 0.],
        [ 2., 1.],
        [ 3., 2.],
    ], device="cuda"),
    columns=["signal", "noise"],
)
y_context = sdm.TableTensor.from_tensor(
    2 * x_context["signal"].numerical,
    columns=["target"],
)
x_query = sdm.TableTensor.from_tensor(
    torch.tensor([[-0.5, 1.], [0., 1.], [0.5, 1.]], device="cuda"),
    columns=["signal", "noise"],
)

model = sdm.models.TabICLv2(device="cuda")
model.fit(x_context, y_context)

explainer = sdm.explain.ShapleyExplainer()
out = explainer(
    model,
    x_query,
    output="q500",
    background=x_context,
    budget=4,
)

# Feature attributions for the first query row:
dict(zip(out[0].feature_names, out[0].get_n_order_values(1)))
# {"signal": -1.7216, "noise": -0.0402}
out[0].plot_waterfall(out[0].feature_names)
Parameters:

kwargs (Any) – Additional keyword arguments passed to shapiq.explainer.TabularExplainer, e.g., imputer, index or max_order.

__call__(model: ICLModel, x: TableTensor, *, output: str, background: TableTensor, budget: int, generator: torch.Generator | None = None) → list[InteractionValues]#

Explain the contributions of preprocessed features.

Parameters:
  • model (ICLModel) – The fitted model.

  • x (TableTensor) – The feature tensor of query examples with shape [R, D] with R rows and D columns.

  • output (str) – The name of the predicted column to explain.

  • background (TableTensor) – The feature tensor of reference rows with shape [R_background, D], e.g., the in-context examples.

  • budget (int) – The budget to use for the approximation.

  • generator (torch.Generator | None) – Pseudorandom number generator used for sampling column subsets and reference rows.

Returns:

The InteractionValues of each query row.

Return type:

list[InteractionValues]