shapiq.explainer.TreeExplainer¶

class shapiq.explainer.TreeExplainer(model, *, mode='pathdependent', reference_dataset=None, max_order=1, min_order=0, index='SV', class_index=None, backend='auto', **kwargs)[source]¶

Bases: Explainer

The TreeExplainer class for tree-based models.

The TreeExplainer is the model-specific explainer for tree-based models, capable of computing attributions and interactions for both path-dependent and interventional modes (details below). It supports various interaction indices and can leverage the optional Woodelf package for efficient computation on large datasets. We support the following model types: scikit-learn decision trees, random forests, and gradient-boosted ensembles, as well as XGBoost, LightGBM, and CatBoost models, for both regression and classification tasks. The model may be fitted both on categorical and numerical features (except for CatBoost, which requires categorical features to be encoded as integers). Attributions and interactions are returned as InteractionValues objects. That object is indexed by feature tuples — values[(1,)] is the attribution of feature 1, values[(1, 2)] the interaction of features 1 and 2 — carries the expected model output as baseline_value, and offers plotting shortcuts such as plot_force() and plot_network().

explain_X() explains a whole data matrix at once, where we return a InteractionValuesBatch object, for which values[(1,)] is a 1D array of the attributions of feature 1 for all explained instances, and values[(1, 2)] is a 1D array of the interactions of features 1 and 2 for all explained instances.

Two established tree-explanation modes Lundberg et al. [2020] differ in what “feature \(i\) is absent” means:

  • In "pathdependent" mode (the default) an absent feature follows both children of its split nodes, weighted by the share of training samples that went each way — the background distribution is the one already stored in the tree, so no data is needed. The computation uses Quadrature-TreeSHAP Wettenstein et al. [2026] (whose first-order case was independently derived in TreeGrad-Ranker Li et al. [2026]), implemented in QuadratureTreeSHAP: values and interactions are Gauss-Legendre integrals of weighted Banzhaf interaction polynomials, numerically exact in float64 at any tree depth. The algorithm descends from Linear TreeSHAP Yu et al. [2022] and computes any-order Shapley interactions as introduced for trees by TreeSHAP-IQ Muschalik et al. [2024]; Banzhaf indices fall out of the same polynomials by evaluation at participation probability 1/2. Supported indices: "SV", "SII", "k-SII", "BV", and "BII".

  • In "interventional" mode an absent feature takes the values it has in a reference_dataset (background SHAP), computed by InterventionalTreeSHAPIQ, which additionally supports the "STII", "FSII", and "FBII" indices. Large interventional inputs are routed to the vectorized Woodelf and WOODELF-HD algorithms Nadel and Wettenstein [2026] Wettenstein et al. [2026] when the optional woodelf-explainer package is installed (pip install shapiq[tree]); the backend parameter overrides this routing.

The two computation classes (QuadratureTreeSHAP and InterventionalTreeSHAPIQ) live in shapiq.tree and can be used directly, as can the standalone reference algorithms TreeSHAPIQ and LinearTreeSHAP.

Examples

Shapley values for a random forest — the attributions sum to the prediction (efficiency):

>>> import numpy as np
>>> from sklearn.ensemble import RandomForestRegressor
>>> from shapiq import TreeExplainer
>>> rng = np.random.default_rng(0)
>>> X = rng.normal(size=(500, 5))
>>> y = X[:, 0] + 2 * X[:, 1] * X[:, 2]
>>> model = RandomForestRegressor(n_estimators=20, random_state=0).fit(X, y)
>>> explainer = TreeExplainer(model, index="SV", max_order=1)
>>> shapley_values = explainer.explain(X[0])
>>> shapley_values[(1,)]  # contribution of feature 1 to this prediction
-0.0993...
>>> float(shapley_values.values.sum())  # equals model.predict(X[:1])[0]
-0.2279...

Pairwise Shapley interactions (k-SII of order 2) separate the learned X1 * X2 synergy from the additive effects:

>>> explainer = TreeExplainer(model, index="k-SII", max_order=2)
>>> interactions = explainer.explain(X[0])
>>> abs(interactions[(1, 2)]) > 10 * abs(interactions[(0, 1)])
True

Interventional Shapley values against a background dataset:

>>> explainer = TreeExplainer(
...     model,
...     mode="interventional",
...     reference_dataset=X[:100],
... )
>>> shapley_values = explainer.explain(X[0])

Initializes the TreeExplainer.

Parameters:
  • model (dict | TreeModel | list[TreeModel] | Any) – A tree-based model to explain.

  • mode (Literal['pathdependent', 'interventional']) – The mode of the explainer, either "pathdependent" or "interventional". In "pathdependent" mode, the explainer computes path-dependent interaction values with the Quadrature-TreeSHAP algorithm; in "interventional" mode, it computes interventional interaction values against the reference_dataset. Defaults to "pathdependent".

  • max_order (int) – The maximum order of interactions to be computed. Set to 1 for no interactions (i.e, for Shapley values "SV" or Banzhaf values "BV"). Any value higher than 1 computes interaction values up to that order. Defaults to 1.

  • min_order (int) – The minimum interaction order to keep in the returned InteractionValues. Must satisfy 0 <= min_order <= max_order. When min_order == 0 the empty interaction () is included with the baseline value. When min_order >= 1 all interactions of order below min_order are filtered out of the result; the underlying algorithm still computes them internally when required by aggregated indices such as "k-SII". Defaults to 0.

  • index (Literal['SV', 'SII', 'k-SII', 'BV', 'BII', 'STII', 'FSII', 'FBII']) – The type of interaction to be computed. In "pathdependent" mode, the indices ["SV", "SII", "k-SII", "BV", "BII"] are supported. In "interventional" mode, further indices such as "STII", "FSII", or "FBII" can be computed. Defaults to "SV".

  • class_index (int | None) – The class index of the model to explain. Defaults to None, which will set the class index to 1 per default for classification models and is ignored for regression models.

  • reference_dataset (ndarray | None) – A dataset to be used for reference in the explanation. Required when mode="interventional". Defaults to None.

  • backend (Literal['auto', 'woodelf', 'shapiq']) – Which implementation computes the explanations. With "auto" the explainer computes path-dependent explanations with shapiq’s QuadratureTreeSHAP and routes larger interventional inputs to Woodelf (falling back to shapiq with a WoodelfNotAvailableWarning if the optional woodelf dependency is missing). "woodelf" forces Woodelf and raises if it is not installed or cannot handle the configuration; "shapiq" forces the shapiq implementation. Defaults to "auto".

  • **kwargs (Any) – Additional keyword arguments are ignored.

explain_X(X, *, n_jobs=None, random_state=None, verbose=False, **kwargs)[source]¶

Explain multiple instances at once, using Woodelf on larger interventional inputs.

The whole batch is computed in a single vectorized Woodelf run when the input crosses the cut-offs (see _should_use_woodelf()), and by the per-instance shapiq computation otherwise. Either way the result is an InteractionValuesBatch: a sequence of one InteractionValues per instance (materialized lazily on access), whose values attribute exposes the memory-efficient vectorized format {interaction_tuple: ndarray of shape (n_instances,)} directly.

Parameters:
  • X (ndarray) – A 2-dimensional matrix of inputs to be explained with shape (n_instances, n_features).

  • n_jobs (int | None) – Number of jobs for the shapiq fallback’s joblib.Parallel. Defaults to None (no parallelization).

  • random_state (int | None) – The random state to re-initialize the shapiq fallback with. Defaults to None.

  • verbose (bool) – Whether to print a progress bar in the shapiq fallback. Defaults to False.

  • **kwargs (Any) – Additional keyword-only arguments passed to the shapiq fallback.

Return type:

InteractionValuesBatch

Returns:

The interaction values of all instances in X as a batch.

explain_function(x, *args, **kwargs)[source]¶

Computes the interaction index for a single instance.

The method used for computing the explanation depends on the specified mode and the parameters of the explainer.

Parameters:
  • x (ndarray) – The instance to explain as a 1-dimensional array.

  • *args (Any) – Additional positional arguments are ignored.

  • **kwargs (Any) – Additional keyword arguments forwarded to the per-mode explain function.

Return type:

InteractionValues

Returns:

The computed interaction index for the instance.

property baseline_value: float¶

The empty prediction of the explained model, matching the explanation mode.

Computed lazily on first access and cached. In "pathdependent" mode this is the sum of the per-tree (coverage-weighted) empty predictions; in "interventional" mode it is the mean ensemble prediction over the reference dataset.

property mode: Literal['interventional', 'pathdependent']¶

The mode of the explainer.