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:
ExplainerThe TreeExplainer class for tree-based models.
The
TreeExplaineris 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-learndecision trees, random forests, and gradient-boosted ensembles, as well asXGBoost,LightGBM, andCatBoostmodels, 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 asInteractionValuesobjects. 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 asbaseline_value, and offers plotting shortcuts such asplot_force()andplot_network().explain_X()explains a whole data matrix at once, where we return aInteractionValuesBatchobject, for whichvalues[(1,)]is a 1D array of the attributions of feature 1 for all explained instances, andvalues[(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 inQuadratureTreeSHAP: 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 areference_dataset(background SHAP), computed byInterventionalTreeSHAPIQ, 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 optionalwoodelf-explainerpackage is installed (pip install shapiq[tree]); thebackendparameter overrides this routing.
The two computation classes (
QuadratureTreeSHAPandInterventionalTreeSHAPIQ) live inshapiq.treeand can be used directly, as can the standalone reference algorithmsTreeSHAPIQandLinearTreeSHAP.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-SIIof order 2) separate the learnedX1 * X2synergy 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 thereference_dataset. Defaults to"pathdependent".max_order (
int) – The maximum order of interactions to be computed. Set to1for no interactions (i.e, for Shapley values"SV"or Banzhaf values"BV"). Any value higher than1computes interaction values up to that order. Defaults to1.min_order (
int) – The minimum interaction order to keep in the returnedInteractionValues. Must satisfy0 <= min_order <= max_order. Whenmin_order == 0the empty interaction()is included with the baseline value. Whenmin_order >= 1all interactions of order belowmin_orderare filtered out of the result; the underlying algorithm still computes them internally when required by aggregated indices such as"k-SII". Defaults to0.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 toNone, which will set the class index to1per 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 whenmode="interventional". Defaults toNone.backend (
Literal['auto','woodelf','shapiq']) – Which implementation computes the explanations. With"auto"the explainer computes path-dependent explanations with shapiq’sQuadratureTreeSHAPand routes larger interventional inputs to Woodelf (falling back to shapiq with aWoodelfNotAvailableWarningif 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 anInteractionValuesBatch: a sequence of oneInteractionValuesper instance (materialized lazily on access), whosevaluesattribute 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’sjoblib.Parallel. Defaults toNone(no parallelization).random_state (
int|None) – The random state to re-initialize the shapiq fallback with. Defaults toNone.verbose (
bool) – Whether to print a progress bar in the shapiq fallback. Defaults toFalse.**kwargs (
Any) – Additional keyword-only arguments passed to the shapiq fallback.
- Return type:
- Returns:
The interaction values of all instances in
Xas 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:
- Return type:
- 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.