Skill Tracer
Skills › Scientific Agent Skills › shap › theory.md

theory.md

357 lines · skills/shap/references/theory.md at 5f2bc03

Open on GitHub
1# SHAP Theory and Interpretation
2
3SHAP applies Shapley-style credit allocation to model explanations. The numerical result is defined by more than the fitted model: it also depends on the model output, background distribution, masking rule, and any coalition constraints.
4

SHAP Theory and Interpretation

SHAP applies Shapley-style credit allocation to model explanations. The numerical result is defined by more than the fitted model: it also depends on the model output, background distribution, masking rule, and any coalition constraints.

Raw lines 1 to 4
5## Additive Explanation
6
7For one scalar model output and one row `x`, SHAP constructs an additive decomposition:
8
9```text
10f_explained(x) = base_value + sum_i phi_i(x)
11```
13- `f_explained` is the exact output selected for explanation.
14- `base_value` is the expected output under the explainer's reference game.
15- `phi_i` is the attribution assigned to feature `i`.
17For modern tabular `shap.Explanation` objects:
19```python
20reconstructed = explanation.base_values + explanation.values.sum(axis=1)
21```
23The equation is meaningful only when the output units are known. A raw margin, probability, log loss, and logit are different quantities.

Additive Explanation

For one scalar model output and one row x, SHAP constructs an additive decomposition:

f_explained(x) = base_value + sum_i phi_i(x)
  • f_explained is the exact output selected for explanation.
  • base_value is the expected output under the explainer's reference game.
  • phi_i is the attribution assigned to feature i.

For modern tabular shap.Explanation objects:

reconstructed = explanation.base_values + explanation.values.sum(axis=1)

The equation is meaningful only when the output units are known. A raw margin, probability, log loss, and logit are different quantities.

Raw lines 5 to 24
25## Cooperative-Game Formulation
27Let `F` be the set of features and `v(S)` the value assigned to coalition `S`. A Shapley value for feature `i` is:
29```text
30phi_i =
31 sum over S subset of F \ {i}
32 [ |S|! (|F|-|S|-1)! / |F|! ]
33 * [v(S union {i}) - v(S)]
34```
36This averages the marginal contribution of `i` over all feature orderings.
38In machine learning, defining `v(S)` is the hard part because a model normally requires all inputs. The masker and background distribution specify how hidden features are integrated or imputed.

Cooperative-Game Formulation

Let F be the set of features and v(S) the value assigned to coalition S. A Shapley value for feature i is:

phi_i =
  sum over S subset of F \ {i}
  [ |S|! (|F|-|S|-1)! / |F|! ]
  * [v(S union {i}) - v(S)]

This averages the marginal contribution of i over all feature orderings.

In machine learning, defining v(S) is the hard part because a model normally requires all inputs. The masker and background distribution specify how hidden features are integrated or imputed.

Raw lines 25 to 39
40## What the Axioms Mean
42Classic Shapley values satisfy:
44- **Efficiency:** all feature values sum to the coalition payoff difference.
45- **Symmetry:** interchangeable players receive equal credit.
46- **Dummy/null player:** a player with no marginal contribution receives zero.
47- **Additivity:** values for combined games are sums of values for component games.
49The SHAP paper describes related properties for additive feature-attribution methods:
51- **Local accuracy:** the additive explanation reconstructs the selected output.
52- **Missingness:** absent simplified inputs receive zero attribution under the formulation.
53- **Consistency:** if a feature's marginal contribution increases for every coalition, its attribution does not decrease.
55These are mathematical allocation properties. They do **not** mean:
57- ethical or legal fairness;
58- causal correctness;
59- robustness to distribution shift;
60- truthfulness of the fitted model;
61- stability under a different background or masker.
63Avoid calling SHAP values "fair" without specifying that the term refers only to a cooperative-game allocation axiom.

What the Axioms Mean

Classic Shapley values satisfy:

  • Efficiency: all feature values sum to the coalition payoff difference.
  • Symmetry: interchangeable players receive equal credit.
  • Dummy/null player: a player with no marginal contribution receives zero.
  • Additivity: values for combined games are sums of values for component games.

The SHAP paper describes related properties for additive feature-attribution methods:

  • Local accuracy: the additive explanation reconstructs the selected output.
  • Missingness: absent simplified inputs receive zero attribution under the formulation.
  • Consistency: if a feature's marginal contribution increases for every coalition, its attribution does not decrease.

These are mathematical allocation properties. They do not mean:

  • ethical or legal fairness;
  • causal correctness;
  • robustness to distribution shift;
  • truthfulness of the fitted model;
  • stability under a different background or masker.

Avoid calling SHAP values "fair" without specifying that the term refers only to a cooperative-game allocation axiom.

Raw lines 40 to 64
65## The Value Function Is Part of the Result
67Common tabular games include:

The Value Function Is Part of the Result

Common tabular games include:

Raw lines 65 to 68
69### Marginal/interventional game
71Hidden features are sampled from a background distribution independently of the observed features.
73Conceptually:
75```text
76v(S) = E_background[f(x_S, X_not_S)]
77```
79Advantages:
81- clear reference population;
82- preserves the dummy property with respect to direct model use;
83- straightforward model-agnostic masking.
85Limitations:
87- can evaluate unrealistic combinations;
88- can be sensitive to the selected background;
89- "interventional" in the API name does not make the resulting predictive explanation a causal effect.

Marginal/interventional game

Hidden features are sampled from a background distribution independently of the observed features.

Conceptually:

v(S) = E_background[f(x_S, X_not_S)]

Advantages:

  • clear reference population;
  • preserves the dummy property with respect to direct model use;
  • straightforward model-agnostic masking.

Limitations:

  • can evaluate unrealistic combinations;
  • can be sensitive to the selected background;
  • "interventional" in the API name does not make the resulting predictive explanation a causal effect.
Raw lines 69 to 90
91### Conditional game
93Hidden features are drawn from a distribution conditional on observed features:
95```text
96v(S) = E[f(X) | X_S = x_S]
97```
99Advantages:
101- can stay closer to the observed data manifold;
102- incorporates statistical dependence.
104Limitations:
106- requires estimating conditional distributions;
107- can assign credit to a feature the model does not directly use;
108- dependence can be mistaken for causation;
109- estimates can be unstable in sparse regions.

Conditional game

Hidden features are drawn from a distribution conditional on observed features:

v(S) = E[f(X) | X_S = x_S]

Advantages:

  • can stay closer to the observed data manifold;
  • incorporates statistical dependence.

Limitations:

  • requires estimating conditional distributions;
  • can assign credit to a feature the model does not directly use;
  • dependence can be mistaken for causation;
  • estimates can be unstable in sparse regions.
Raw lines 91 to 110
111### Partitioned game
113Only coalitions compatible with a hierarchy are considered. The resulting allocations are Owen values.
115Advantages:
117- respects semantic or statistical groups;
118- makes structured high-dimensional problems more tractable;
119- reduces arbitrary competition among related features.
121Limitation: the hierarchy is an assumption and changes the game.
123There is no universal answer to "the SHAP value" without specifying the game.

Partitioned game

Only coalitions compatible with a hierarchy are considered. The resulting allocations are Owen values.

Advantages:

  • respects semantic or statistical groups;
  • makes structured high-dimensional problems more tractable;
  • reduces arbitrary competition among related features.

Limitation: the hierarchy is an assumption and changes the game.

There is no universal answer to "the SHAP value" without specifying the game.

Raw lines 111 to 124
125## Background and Baseline
127The base value is the reference-game expectation, not automatically:
129- the overall target mean;
130- the model intercept;
131- class prevalence;
132- a neutral patient/customer;
133- a decision threshold.
135Different backgrounds can change:
137- base values;
138- signed local attributions;
139- mean absolute global rankings;
140- cohort comparisons.
142Treat background sensitivity as a substantive analysis, not just a runtime check.

Background and Baseline

The base value is the reference-game expectation, not automatically:

  • the overall target mean;
  • the model intercept;
  • class prevalence;
  • a neutral patient/customer;
  • a decision threshold.

Different backgrounds can change:

  • base values;
  • signed local attributions;
  • mean absolute global rankings;
  • cohort comparisons.

Treat background sensitivity as a substantive analysis, not just a runtime check.

Raw lines 125 to 143
144## Output Scale
146SHAP values use the additive scale selected by the explainer.
148Examples:
150- regression prediction in target units;
151- binary tree margin in log-odds;
152- class probability;
153- per-row log loss;
154- transformed output under a link function.
156A display transform such as `link="logit"` on a force plot changes labels, not the computed SHAP game. If probability-space additivity is required for supported trees, configure `TreeExplainer(model_output="probability", feature_perturbation="interventional", data=...)`.
158Do not compare mean absolute SHAP magnitudes across models or outputs on different scales.

Output Scale

SHAP values use the additive scale selected by the explainer.

Examples:

  • regression prediction in target units;
  • binary tree margin in log-odds;
  • class probability;
  • per-row log loss;
  • transformed output under a link function.

A display transform such as link="logit" on a force plot changes labels, not the computed SHAP game. If probability-space additivity is required for supported trees, configure TreeExplainer(model_output="probability", feature_perturbation="interventional", data=...).

Do not compare mean absolute SHAP magnitudes across models or outputs on different scales.

Raw lines 144 to 159
160## Local and Global Quantities
162Local attribution:
164```text
165phi_i(x)
166```
168Global mean absolute attribution:
170```text
171E_x[abs(phi_i(x))]
172```
174Mean absolute attribution:
176- discards direction;
177- depends on the evaluated sample distribution;
178- is not normalized predictive performance;
179- is not a causal effect size.
181Mean signed attribution can cancel heterogeneous effects. Plot the distribution before summarizing.

Local and Global Quantities

Local attribution:

phi_i(x)

Global mean absolute attribution:

E_x[abs(phi_i(x))]

Mean absolute attribution:

  • discards direction;
  • depends on the evaluated sample distribution;
  • is not normalized predictive performance;
  • is not a causal effect size.

Mean signed attribution can cancel heterogeneous effects. Plot the distribution before summarizing.

Raw lines 160 to 182
183## Exact and Approximate Algorithms
185Unconstrained exact Shapley computation grows exponentially with feature count. SHAP uses model-specific algorithms or sampling:
187- **Tree SHAP:** exploits tree structure and is exact for the selected tree game.
188- **Linear SHAP:** closed-form or transformation-based allocation for supported linear games.
189- **ExactExplainer:** optimized enumeration for small or hierarchically constrained inputs.
190- **PermutationExplainer:** averages forward/reverse feature orderings.
191- **KernelExplainer:** estimates values through a weighted linear regression over coalitions.
192- **DeepExplainer:** combines DeepLIFT-style rules with multiple background samples.
193- **GradientExplainer:** uses expected gradients.
194- **PartitionExplainer:** exploits a coalition hierarchy.
196"Exact" always means exact under a specified output, background, masker, and coalition game.

Exact and Approximate Algorithms

Unconstrained exact Shapley computation grows exponentially with feature count. SHAP uses model-specific algorithms or sampling:

  • Tree SHAP: exploits tree structure and is exact for the selected tree game.
  • Linear SHAP: closed-form or transformation-based allocation for supported linear games.
  • ExactExplainer: optimized enumeration for small or hierarchically constrained inputs.
  • PermutationExplainer: averages forward/reverse feature orderings.
  • KernelExplainer: estimates values through a weighted linear regression over coalitions.
  • DeepExplainer: combines DeepLIFT-style rules with multiple background samples.
  • GradientExplainer: uses expected gradients.
  • PartitionExplainer: exploits a coalition hierarchy.

"Exact" always means exact under a specified output, background, masker, and coalition game.

Raw lines 183 to 197
198## Interaction Values
200Tree SHAP can decompose attribution into a symmetric interaction matrix.
202For one row:
204- diagonal entries are main effects;
205- off-diagonal entries are pairwise interaction allocations;
206- each row sums to that feature's ordinary SHAP value;
207- the full matrix sums to the prediction difference from baseline.
209```python
210interaction_explainer = shap.TreeExplainer(
211 model, model_output="raw", feature_perturbation="tree_path_dependent",
213interaction = interaction_explainer.shap_interaction_values(X_eval)
214```
216In 0.52.0, do not reuse an interventional/probability explainer for this operation; that path either rejects it or does not implement interactions. Each symmetric off-diagonal entry is half the pair contribution. Validate row sums against the same path-dependent ordinary SHAP values.
218An interaction value describes non-additivity in the fitted model under the chosen game. It does not prove biological, physical, or causal interaction.
220Scatter-plot vertical dispersion is only a clue; compute or test interactions before labeling them.

Interaction Values

Tree SHAP can decompose attribution into a symmetric interaction matrix.

For one row:

  • diagonal entries are main effects;
  • off-diagonal entries are pairwise interaction allocations;
  • each row sums to that feature's ordinary SHAP value;
  • the full matrix sums to the prediction difference from baseline.
interaction_explainer = shap.TreeExplainer(
    model, model_output="raw", feature_perturbation="tree_path_dependent",
)
interaction = interaction_explainer.shap_interaction_values(X_eval)

In 0.52.0, do not reuse an interventional/probability explainer for this operation; that path either rejects it or does not implement interactions. Each symmetric off-diagonal entry is half the pair contribution. Validate row sums against the same path-dependent ordinary SHAP values.

An interaction value describes non-additivity in the fitted model under the chosen game. It does not prove biological, physical, or causal interaction.

Scatter-plot vertical dispersion is only a clue; compute or test interactions before labeling them.

Raw lines 198 to 221
222## Correlation and Credit Sharing
224When two features contain similar information, multiple allocations can be defensible:
226- marginal values emphasize direct functional use by the model;
227- conditional values share credit through dependence;
228- grouped values assign credit to the coalition.
230Instability across folds, seeds, backgrounds, or equivalent model fits is evidence that individual attribution is not uniquely supported by the problem. Report grouped results or sensitivity rather than selecting one convenient ranking.

Correlation and Credit Sharing

When two features contain similar information, multiple allocations can be defensible:

  • marginal values emphasize direct functional use by the model;
  • conditional values share credit through dependence;
  • grouped values assign credit to the coalition.

Instability across folds, seeds, backgrounds, or equivalent model fits is evidence that individual attribution is not uniquely supported by the problem. Report grouped results or sensitivity rather than selecting one convenient ranking.

Raw lines 222 to 231
232## SHAP Is Not Causal
234SHAP makes predictive relationships visible. A positive attribution does not imply that increasing the feature would increase the real-world outcome.
236Confounding, mediation, reverse causality, selection bias, and feature redundancy can all make predictive patterns unsuitable for intervention.
238Use causal language only when:
240- the model and estimand are explicitly causal;
241- identification assumptions are stated;
242- data collection supports those assumptions;
243- the SHAP use is integrated into that causal analysis.
245Even then, describe exactly what quantity is attributed.

SHAP Is Not Causal

SHAP makes predictive relationships visible. A positive attribution does not imply that increasing the feature would increase the real-world outcome.

Confounding, mediation, reverse causality, selection bias, and feature redundancy can all make predictive patterns unsuitable for intervention.

Use causal language only when:

  • the model and estimand are explicitly causal;
  • identification assumptions are stated;
  • data collection supports those assumptions;
  • the SHAP use is integrated into that causal analysis.

Even then, describe exactly what quantity is attributed.

Raw lines 232 to 246
247## SHAP Is Not a Fairness Certificate
249Attribution can help investigate:
251- whether a model directly uses a protected feature;
252- whether potential proxies have large or heterogeneous attributions;
253- how explanation distributions differ across groups;
254- which features contribute to errors or loss.
256It cannot alone establish:
258- demographic parity;
259- equalized odds/opportunity;
260- calibration by group;
261- absence of proxy discrimination;
262- individual fairness;
263- compliant recourse.
265Protected-feature attribution can be small while proxies drive disparities. Conditional attributions can also assign protected-feature credit even when the model does not directly consume it. Pair SHAP with outcome, error, calibration, threshold, and data-quality analyses.

SHAP Is Not a Fairness Certificate

Attribution can help investigate:

  • whether a model directly uses a protected feature;
  • whether potential proxies have large or heterogeneous attributions;
  • how explanation distributions differ across groups;
  • which features contribute to errors or loss.

It cannot alone establish:

  • demographic parity;
  • equalized odds/opportunity;
  • calibration by group;
  • absence of proxy discrimination;
  • individual fairness;
  • compliant recourse.

Protected-feature attribution can be small while proxies drive disparities. Conditional attributions can also assign protected-feature credit even when the model does not directly consume it. Pair SHAP with outcome, error, calibration, threshold, and data-quality analyses.

Raw lines 247 to 266
267## SHAP Is Not Recourse
269A waterfall answers "how this model output is allocated relative to this reference." It does not answer:
271- which feature can feasibly be changed;
272- what the outcome would be after intervention;
273- whether downstream features would change;
274- what the minimal safe action is.
276Use dedicated counterfactual/recourse methods with feasibility and causal constraints.

SHAP Is Not Recourse

A waterfall answers "how this model output is allocated relative to this reference." It does not answer:

  • which feature can feasibly be changed;
  • what the outcome would be after intervention;
  • whether downstream features would change;
  • what the minimal safe action is.

Use dedicated counterfactual/recourse methods with feasibility and causal constraints.

Raw lines 267 to 277
278## Uncertainty and Stability
280A standard SHAP plot usually shows point estimates, not uncertainty.
282Sources of variation include:
284- model fitting sample and seed;
285- hyperparameters;
286- background sample;
287- evaluation cohort;
288- approximation seed and budget;
289- conditional-distribution estimation;
290- preprocessing and feature grouping.
292Useful stability analyses:
2941. bootstrap or cross-fit the model;
2952. repeat background sampling;
2963. repeat approximation seeds;
2974. compare rankings and signed distributions;
2985. report intervals or rank stability;
2996. separate model uncertainty from explainer approximation uncertainty.

Uncertainty and Stability

A standard SHAP plot usually shows point estimates, not uncertainty.

Sources of variation include:

  • model fitting sample and seed;
  • hyperparameters;
  • background sample;
  • evaluation cohort;
  • approximation seed and budget;
  • conditional-distribution estimation;
  • preprocessing and feature grouping.

Useful stability analyses:

  1. bootstrap or cross-fit the model;
  2. repeat background sampling;
  3. repeat approximation seeds;
  4. compare rankings and signed distributions;
  5. report intervals or rank stability;
  6. separate model uncertainty from explainer approximation uncertainty.
Raw lines 278 to 300
301## Comparisons With Other Importance Measures

Comparisons With Other Importance Measures

Raw lines 301 to 302
303### Permutation importance
305Measures predictive performance degradation after shuffling a feature.
307- global, metric-dependent;
308- can be distorted by correlated features;
309- does not decompose individual predictions.

Permutation importance

Measures predictive performance degradation after shuffling a feature.

  • global, metric-dependent;
  • can be distorted by correlated features;
  • does not decompose individual predictions.
Raw lines 303 to 310
311### Split/gain importance
313Summarizes how a tree used features during fitting.
315- fast;
316- can favor high-cardinality or frequently split features;
317- does not provide local output decomposition.

Split/gain importance

Summarizes how a tree used features during fitting.

  • fast;
  • can favor high-cardinality or frequently split features;
  • does not provide local output decomposition.
Raw lines 311 to 318
319### Linear coefficients
321Describe change per input unit on the model's linear scale.
323- depend on feature scale and parameterization;
324- do not include how far a row is from the reference.

Linear coefficients

Describe change per input unit on the model's linear scale.

  • depend on feature scale and parameterization;
  • do not include how far a row is from the reference.
Raw lines 319 to 325
326### Partial dependence
328Averages predictions while varying a feature.
330- describes an average response surface;
331- can evaluate off-manifold combinations;
332- does not allocate each individual prediction.
334These answer different questions. Agreement is reassuring but not proof; disagreement should trigger an assumptions review.

Partial dependence

Averages predictions while varying a feature.

  • describes an average response surface;
  • can evaluate off-manifold combinations;
  • does not allocate each individual prediction.

These answer different questions. Agreement is reassuring but not proof; disagreement should trigger an assumptions review.

Raw lines 326 to 335
336## Interpretation Checklist
338Before making a claim:
340- [ ] Name the model output and units.
341- [ ] Define background and masking semantics.
342- [ ] Identify the selected row/cohort and sampling rule.
343- [ ] Verify additivity where applicable.
344- [ ] State whether estimates are exact or approximate.
345- [ ] Check correlation and grouping sensitivity.
346- [ ] Separate local from global claims.
347- [ ] Avoid causal, fairness, and recourse claims without separate evidence.
348- [ ] Report model performance and relevant uncertainty.

Interpretation Checklist

Before making a claim:

  • [ ] Name the model output and units.
  • [ ] Define background and masking semantics.
  • [ ] Identify the selected row/cohort and sampling rule.
  • [ ] Verify additivity where applicable.
  • [ ] State whether estimates are exact or approximate.
  • [ ] Check correlation and grouping sensitivity.
  • [ ] Separate local from global claims.
  • [ ] Avoid causal, fairness, and recourse claims without separate evidence.
  • [ ] Report model performance and relevant uncertainty.
Raw lines 336 to 349
350## Sources
352- Lundberg & Lee (2017), "A Unified Approach to Interpreting Model Predictions": https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html
353- Lundberg et al. (2020), "From local explanations to global understanding with explainable AI for trees": https://www.nature.com/articles/s42256-019-0138-9
354- SHAP introduction: https://shap.readthedocs.io/en/latest/example_notebooks/overviews/An%20introduction%20to%20explainable%20AI%20with%20Shapley%20values.html
355- Causal interpretation caution: https://shap.readthedocs.io/en/latest/example_notebooks/overviews/Be%20careful%20when%20interpreting%20predictive%20models%20in%20search%20of%20causal%20insights.html
356- Explaining quantitative fairness measures: https://shap.readthedocs.io/en/latest/example_notebooks/overviews/Explaining%20quantitative%20measures%20of%20fairness.html
357- Janzing, Minorics & Blöbaum (2020), "Feature relevance quantification in explainable AI: A causal problem": https://proceedings.mlr.press/v108/janzing20a.html

Sources

  • Lundberg & Lee (2017), "A Unified Approach to Interpreting Model Predictions": https://proceedings.neurips.cc/paper/2017/hash/8a20a8621978632d76c43dfd28b67767-Abstract.html
  • Lundberg et al. (2020), "From local explanations to global understanding with explainable AI for trees": https://www.nature.com/articles/s42256-019-0138-9
  • SHAP introduction: https://shap.readthedocs.io/en/latest/example_notebooks/overviews/An%20introduction%20to%20explainable%20AI%20with%20Shapley%20values.html
  • Causal interpretation caution: https://shap.readthedocs.io/en/latest/example_notebooks/overviews/Be%20careful%20when%20interpreting%20predictive%20models%20in%20search%20of%20causal%20insights.html
  • Explaining quantitative fairness measures: https://shap.readthedocs.io/en/latest/example_notebooks/overviews/Explaining%20quantitative%20measures%20of%20fairness.html
  • Janzing, Minorics & Blöbaum (2020), "Feature relevance quantification in explainable AI: A causal problem": https://proceedings.mlr.press/v108/janzing20a.html
Raw lines 350 to 357