• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

mmschlk / shapiq / 16400353732

20 Jul 2025 01:21PM UTC coverage: 93.901% (+16.3%) from 77.589%
16400353732

push

github

web-flow
🔨 moves `shapiq.benchmark` and `shapiq.games` out of `shapiq`  (#416)

* moves benchmark and games out of shapiq core

* make macos single process test run

* add comment in macos

* updated CHANGELOG.md

* update type imports

25 of 46 new or added lines in 14 files covered. (54.35%)

4 existing lines in 1 file now uncovered.

4927 of 5247 relevant lines covered (93.9%)

0.94 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

86.96
/src/shapiq/explainer/tabular.py
1
"""Tabular Explainer class for the shapiq package."""
2

3
from __future__ import annotations
1✔
4

5
from typing import TYPE_CHECKING, Any, Literal
1✔
6
from warnings import warn
1✔
7

8
from overrides import overrides
1✔
9

10
from shapiq.explainer.base import Explainer
1✔
11
from shapiq.interaction_values import InteractionValues, finalize_computed_interactions
1✔
12

13
from .configuration import setup_approximator
1✔
14
from .custom_types import ExplainerIndices
1✔
15

16
if TYPE_CHECKING:
1✔
17
    import numpy as np
×
18

19
    from shapiq.approximator.base import Approximator
×
NEW
20
    from shapiq.imputer.base import Imputer
×
21
    from shapiq.typing import Model
×
22

23
TabularExplainerApproximators = Literal["spex", "montecarlo", "svarm", "permutation", "regression"]
1✔
24
TabularExplainerImputers = Literal["marginal", "baseline", "conditional"]
1✔
25
TabularExplainerIndices = ExplainerIndices
1✔
26

27

28
class TabularExplainer(Explainer):
1✔
29
    """The tabular explainer as the main interface for the shapiq package.
30

31
    The ``TabularExplainer`` class is the main interface for the ``shapiq`` package and tabular
32
    data. It can be used to explain the predictions of any model by estimating the Shapley
33
    interaction values.
34

35
    Attributes:
36
        index: Type of Shapley interaction index to use.
37
        data: A background data to use for the explainer.
38

39
    Properties:
40
        baseline_value: A baseline value of the explainer.
41

42
    """
43

44
    def __init__(
1✔
45
        self,
46
        model: Model,
47
        data: np.ndarray,
48
        *,
49
        class_index: int | None = None,
50
        imputer: Imputer | TabularExplainerImputers = "marginal",
51
        approximator: Literal["auto"] | TabularExplainerApproximators | Approximator = "auto",
52
        index: TabularExplainerIndices = "k-SII",
53
        max_order: int = 2,
54
        random_state: int | None = None,
55
        verbose: bool = False,
56
        **kwargs: Any,
57
    ) -> None:
58
        """Initializes the TabularExplainer.
59

60
        Args:
61
            model: The model to be explained as a callable function expecting data points as input
62
                and returning 1-dimensional predictions.
63

64
            data: A background dataset to be used for imputation.
65

66
            class_index: The class index of the model to explain. Defaults to ``None``, which will
67
                set the class index to ``1`` per default for classification models and is ignored
68
                for regression models.
69

70
            imputer: Either an :class:`~shapiq.games.imputer.Imputer` as implemented in the
71
                :mod:`~shapiq.games.imputer` module, or a literal string from
72
                ``["marginal", "baseline", "conditional"]``. Defaults to ``"marginal"``, which
73
                initializes the default
74
                :class:`~shapiq.games.imputer.marginal_imputer.MarginalImputer` with its default
75
                parameters or as provided in ``kwargs``.
76

77
            approximator: An :class:`~shapiq.approximator.Approximator` object to use for the
78
                explainer or a literal string from
79
                ``["auto", "spex", "montecarlo", "svarm", "permutation"]``. Defaults to ``"auto"``
80
                which will automatically choose the approximator based on the number of features and
81
                the desired index.
82
                    - for index ``"SV"``: :class:`~shapiq.approximator.KernelSHAP`
83
                    - for index ``"SII"`` or ``"k-SII"``: :class:`~shapiq.approximator.KernelSHAPIQ`
84
                    - for index ``"FSII"``: :class:`~shapiq.approximator.RegressionFSII`
85
                    - for index ``"FBII"``: :class:`~shapiq.approximator.RegressionFBII`
86
                    - for index ``"STII"``: :class:`~shapiq.approximator.SVARMIQ`
87

88
            index: The index to explain the model with. Defaults to ``"k-SII"`` which computes the
89
                k-Shapley Interaction Index. If ``max_order`` is set to 1, this corresponds to the
90
                Shapley value (``index="SV"``). Options are:
91
                    - ``"SV"``: Shapley value
92
                    - ``"k-SII"``: k-Shapley Interaction Index
93
                    - ``"FSII"``: Faithful Shapley Interaction Index
94
                    - ``"FBII"``: Faithful Banzhaf Interaction Index (becomes ``BV`` for order 1)
95
                    - ``"STII"``: Shapley Taylor Interaction Index
96
                    - ``"SII"``: Shapley Interaction Index
97

98
            max_order: The maximum interaction order to be computed. Defaults to ``2``. Set to
99
                ``1`` for no interactions (single feature importance).
100

101
            random_state: The random state to initialize Imputer and Approximator with. Defaults to
102
                ``None``.
103

104
            verbose: Whether to show a progress bar during the computation. Defaults to ``False``.
105

106
            **kwargs: Additional keyword-only arguments passed to the imputers implemented in
107
                :mod:`~shapiq.games.imputer`.
108
        """
109
        from shapiq.imputer import (
1✔
110
            BaselineImputer,
111
            ConditionalImputer,
112
            MarginalImputer,
113
            TabPFNImputer,
114
        )
115

116
        super().__init__(model, data, class_index, index=index, max_order=max_order)
1✔
117

118
        # get class for self
119
        class_name = self.__class__.__name__
1✔
120
        if self._model_type == "tabpfn" and class_name == "TabularExplainer":
1✔
121
            warn(
1✔
122
                "You are using a TabPFN model with the ``shapiq.TabularExplainer`` directly. This "
123
                "is not recommended as it uses missing value imputation and not contextualization. "
124
                "Consider using the ``shapiq.TabPFNExplainer`` instead. For more information see "
125
                "the documentation and the example notebooks.",
126
                stacklevel=2,
127
            )
128

129
        if imputer == "marginal":
1✔
130
            self.imputer = MarginalImputer(
1✔
131
                self.predict,
132
                self._data,
133
                random_state=random_state,
134
                **kwargs,
135
            )
136
        elif imputer == "conditional":
1✔
137
            self.imputer = ConditionalImputer(
1✔
138
                self.predict,
139
                self._data,
140
                random_state=random_state,
141
                **kwargs,
142
            )
143
        elif imputer == "baseline":
1✔
144
            self.imputer = BaselineImputer(
1✔
145
                self.predict,
146
                self._data,
147
                random_state=random_state,
148
                **kwargs,
149
            )
150
        elif isinstance(
1✔
151
            imputer, MarginalImputer | ConditionalImputer | BaselineImputer | TabPFNImputer
152
        ):
153
            self.imputer = imputer
1✔
154
        else:
155
            msg = (
×
156
                f"Invalid imputer {imputer}. "
157
                f'Must be one of ["marginal", "baseline", "conditional"], or a valid Imputer '
158
                f"object."
159
            )
160
            raise ValueError(msg)
×
161
        self._n_features: int = self._data.shape[1]
1✔
162
        self.imputer.verbose = verbose  # set the verbose flag for the imputer
1✔
163

164
        self.approximator = setup_approximator(
1✔
165
            approximator, self._index, self._max_order, self._n_features, random_state
166
        )
167

168
    @overrides
1✔
169
    def explain_function(
1✔
170
        self,
171
        x: np.ndarray,
172
        budget: int,
173
        *,
174
        random_state: int | None = None,
175
    ) -> InteractionValues:
176
        """Explains the model's predictions.
177

178
        Args:
179
            x: The data point to explain as a 2-dimensional array with shape
180
                (1, n_features).
181

182
            budget: The budget to use for the approximation. It indicates how many coalitions are
183
                sampled, thus high values indicate more accurate approximations, but induce higher
184
                computational costs.
185

186
            random_state: The random state to re-initialize Imputer and Approximator with.
187
                Defaults to ``None``, which will not set a random state.
188

189
        Returns:
190
            An object of class :class:`~shapiq.interaction_values.InteractionValues` containing
191
            the computed interaction values.
192
        """
193
        self.set_random_state(random_state)
1✔
194

195
        # initialize the imputer with the explanation point
196
        self.imputer.fit(x)
1✔
197

198
        # explain
199
        interaction_values = self.approximator(budget=budget, game=self.imputer)
1✔
200
        interaction_values.baseline_value = self.baseline_value
1✔
201
        return finalize_computed_interactions(
1✔
202
            interaction_values,
203
            target_index=self._index,
204
        )
205

206
    @property
1✔
207
    def baseline_value(self) -> float:
1✔
208
        """Returns the baseline value of the explainer."""
209
        return self.imputer.empty_prediction
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc