TreeSHAP

Also known as: Tree SHAP

On this page 7

TreeSHAP (also written Tree SHAP) is an algorithm that computes exact Shapley value feature attributions for tree-based models, such as decision trees, random forests and gradient-boosted ensembles, in polynomial rather than exponential time. In Explainable AI, it is the standard method for explaining individual predictions of models built with libraries such as XGBoost, LightGBM, CatBoost and scikit-learn.

Shapley values distribute a prediction fairly among input features by averaging each feature’s marginal contribution over all possible feature coalitions. Computing them naively requires evaluating 2 to the power of M coalitions for M features. TreeSHAP avoids that cost by exploiting the structure of the trees, which makes exact attributions practical for models with hundreds of features and millions of rows.

How TreeSHAP computes exact attributions

TreeSHAP works by tracking feature subsets along decision paths instead of enumerating them. As the algorithm walks a tree from root to leaves, it maintains a compact record of which features have been encountered and what proportion of all possible coalitions would follow each path.

When a split uses a feature that belongs to the coalition, the algorithm follows the branch selected by the instance. When the feature is absent, it follows both branches, weighted either by the share of training samples that reached each branch or by background data. Combining these weights at the leaves yields each feature’s exact Shapley contribution.

The resulting complexity is about O(T L D squared) for T trees, L leaves per tree and maximum depth D, compared with exponential cost for brute-force Shapley values. The following table summarizes the main properties that the algorithm guarantees.

PropertyMeaningPractical consequence
Local accuracyAttributions sum to prediction minus base valueEvery explanation reconciles with the output
ConsistencyA feature’s attribution never drops when its true effect growsRankings are more trustworthy than split-gain importance
MissingnessFeatures unused by the model receive zeroNo spurious credit to irrelevant inputs
ExactnessNo sampling error for the chosen value functionRepeated runs give identical results
Properties guaranteed by TreeSHAP

Path-dependent and interventional variants

TreeSHAP has two main variants that differ in how they simulate a missing feature. The choice changes what question the explanation answers, so it is the most consequential configuration decision.

VariantHow missing features are handledData neededInterpretation
Path-dependentWeights branches by training sample coverOnly the trained modelApproximates conditional expectations
InterventionalReplaces features with background samplesA background dataset, often 100 to 1,000 rowsTrue to the model, breaks feature correlations
TreeSHAP variants compared

The path-dependent variant is fast and requires no extra data, but it can assign credit to features that the model never uses directly when they correlate with used features through the tree structure. The interventional variant answers how the model output changes when a feature is set independently of the others; its cost grows linearly with the background set size.

TreeSHAP also computes SHAP interaction values, which split each attribution into main effects and pairwise interactions. They cost roughly M times more than ordinary attributions and are useful for detecting interactions that a summary plot would hide.

TreeSHAP compared with other attribution methods

TreeSHAP is model-specific: it applies only to tree ensembles but is exact and fast there. Model-agnostic methods work with any model but rely on sampling or approximation.

MethodModel scopeExact or approximateTypical speed on trees
TreeSHAPTree ensembles onlyExact for its value functionMilliseconds per row
KernelSHAPAny modelSampling approximationSeconds to minutes per row
Permutation feature importanceAny model, global onlyEstimate with varianceDepends on dataset size
Split-gain importanceTree ensembles onlyHeuristic, not additiveInstant
LIMEAny modelLocal surrogate approximationSeconds per row
TreeSHAP and related explanation methods

Compared with built-in gain or split-count importance, TreeSHAP offers per-prediction explanations and consistency, while gain importance can rank features inconsistently across models of equal accuracy. Compared with KernelSHAP, it removes sampling noise and is typically several orders of magnitude faster on the same ensemble.

Using TreeSHAP in practice

A typical TreeSHAP workflow computes attributions for every row of a validation or production sample and then aggregates them. Local explanations show why a single prediction occurred, while the mean absolute attribution across rows provides a global feature ranking.

GoalRecommended settingReason
Explain model mechanics faithfullyInterventional variant with representative backgroundReflects the function the model computes
Fast explanations without data accessPath-dependent variantNeeds only the trained ensemble
Detect feature interactionsSHAP interaction valuesSeparates main and pairwise effects
Explain probabilities, not log-oddsInterventional with probability outputRaw margin attributions are in log-odds units
Very large ensembles or datasetsGPU implementationParallelizes path computations
Choosing settings for TreeSHAP analyses

Attributions for classifiers trained with logistic loss are by default expressed in log-odds units, not probability. Analysts should state the output space in every report, because a contribution of 0.5 in log-odds is not a 50 percent change in probability.

Limitations and common misreadings

TreeSHAP explains what the model does, not what causes the outcome in the real world. A high attribution means the model relies on a feature, which may reflect a proxy, leakage or bias rather than a genuine mechanism.

  • Correlated features share or shift credit depending on the variant, so rankings of correlated inputs are unstable.
  • Base value choice affects interpretation, because attributions explain the difference from the expected model output.
  • Rashomon effect: equally accurate ensembles can yield different attributions for the same data.
  • Path-dependent artifacts can give nonzero credit to features with no direct effect.
  • Explanation faithfulness applies only to the model; it does not validate the data or labels.

Understanding it simply

TreeSHAP answers a simple question: which inputs pushed this prediction up or down, and by how much. It works for models made of many decision trees.

Imagine a team project that earned a score. You want to split the credit fairly among team members. A fair split needs to consider every possible combination of members. That is slow. TreeSHAP finds the same fair split quickly by following how each tree makes its decisions. The shares always add up to the final score.

Applied in practice

A consumer lender uses a gradient-boosted model with about 120 features to estimate default risk for loan applications. Regulators expect the lender to give declined applicants the principal reasons for the decision, so the model risk team runs interventional TreeSHAP with a background sample of 500 approved applications.

For one declined applicant, the attributions show that a high debt-to-income ratio and two recent missed payments account for most of the increase in predicted risk, while a long employment history lowers it. The team maps the top negative contributors to standard reason codes in the adverse action notice. During validation, the same analysis reveals that a postal-code feature carries unexpectedly high attribution, which prompts a fairness review and its eventual removal from the model.