6.3.2 · D4Interpretability & Explainability

Exercises — Feature attribution (SHAP, LIME)

3,064 words14 min readBack to topic

The Shapley value we lean on throughout is

where is the set of all features, is a coalition (a subset of features already "present"), is how many features are in it, and is the model's expected output when only the features in are known. Read as " factorial" , with by convention.

The empty coalition's output has its own name: ==== is the base value — the model's average prediction before any feature is revealed. Every attribution is a statement relative to this baseline.

The four axioms that pin the Shapley value down uniquely are:

  • Efficiency: (contributions sum to the whole deviation).
  • Symmetry: features that contribute identically in every coalition receive equal .
  • Dummy: a feature that never changes the output gets .
  • Additivity (Linearity): if , then for every . Explanations of a sum of models are the sum of explanations — crucial for ensembles, where the model is literally a sum of trees.

Level 1 — Recognition

Exercise 1.1

For a single instance, which of these is a local attribution and which is global? (a) "Across the whole dataset, income is the 3rd most useful feature." (b) "For Bob, income pushed the default probability up by ."

Recall Solution

(a) is global, (b) is local. Global statements average behaviour over all inputs (like 5.4.02-Permutation-importance). Local statements — the entire point of SHAP/LIME — describe this one prediction. The tell: (b) names a specific instance ("Bob") and a signed number for that instance.

Exercise 1.2

LIME fits a model near a point . What class of model is , and why is that class chosen?

Recall Solution

is a linear model. Chosen because linear coefficients are directly human-readable: " = change in output per unit of feature ." The bet is that even a wildly non-linear looks approximately straight in a small neighbourhood of .

Exercise 1.3

In the Shapley formula, what does the bracket represent in one phrase?

Recall Solution

The marginal contribution of feature : how much the prediction changes when we add to a coalition that did not already contain it.


Level 2 — Application

Exercise 2.1

A model over features has these coalition outputs (higher = more "default risk"):

Compute the marginal contribution of feature 3 when it is added last, i.e. to the coalition .

Recall Solution

. That is the gain from revealing feature 3 once features 1 and 2 are already known.

Exercise 2.2

Using the full table below, list all feature orderings and, for each ordering, the marginal contribution of feature 1.

Recall Solution

For each ordering, feature 1 arrives after whatever came before it. Its marginal contribution is :

Ordering Before feature 1
1,2,3
1,3,2
2,1,3
2,3,1
3,1,2
3,2,1

Figure — Feature attribution (SHAP, LIME)
Figure (Ex 2.2) — alt text: six horizontal arrows, one per feature ordering, each labelled with feature 1's marginal contribution . Four blue arrows read (feature 1 arrives early, after , , or ); two pink arrows read — these are exactly the orderings 2,3,1 and 3,2,1, where feature 1 arrives last after . The picture makes the point: when a feature joins changes its marginal, and averaging over all join-positions is what the Shapley formula does.

Exercise 2.3

Average the six values from 2.2 to get .

Recall Solution

Averaging over all orderings is exactly what the factorial weights in the Shapley formula do — each of the 6 orderings is equally likely.


Level 3 — Analysis

Exercise 3.1

Verify the efficiency axiom for the game in 2.2 by computing and and checking .

Recall Solution

— marginal of feature 2 by ordering:

  • after : (twice: orderings 2,1,3 and 2,3,1)
  • after : (ordering 1,2,3)
  • after : (ordering 3,2,1)
  • after : (orderings 1,3,2 and 3,1,2)

Sum , so .

— marginal of feature 3:

  • after : (×2)
  • after :
  • after :
  • after : (×2)

Sum , so .

Efficiency check: . And . ✓ They match exactly — no residual.

Exercise 3.2

Feature 4 is a dummy: adding it to any coalition never changes . Without computing all orderings, what is , and which axiom guarantees it?

Recall Solution

, guaranteed by the Dummy axiom. Every marginal , so the weighted average of zeros is zero. Intuition: a player who adds nothing to any team deserves no credit.

Exercise 3.3

Two features and are symmetric: for every coalition containing neither. Show .

Recall Solution

Pair up orderings by swapping the positions of and . In each pair, the coalition that precedes in one ordering is exactly the coalition that precedes in the swapped ordering. By the symmetry premise, for that . Every marginal of has an equal partner marginal of under the same combinatorial weight, so the two weighted sums are identical: . This is the Symmetry axiom.

Exercise 3.4

A model is the sum of two trees, . For feature 1 you computed Shapley values and separately. What is , and which axiom lets you add them?

Recall Solution

, by the Additivity (Linearity) axiom. Because every marginal of the summed model splits as , and Shapley is a linear (weighted-average) functional of those marginals, the whole computation distributes over the sum. This is exactly why TreeSHAP can attribute each tree independently and add — a random forest's explanation is the sum of its trees' explanations.


Level 4 — Synthesis

Exercise 4.1

LIME weights each perturbation by , where is a distance and a kernel width. First state precisely what kind of function must be. Then, for , compute the weights of three perturbations at distances from . Finally, say qualitatively what happens to the weights as .

Recall Solution

What is ? It is a distance metric — a non-negative function measuring how far the perturbation sits from the explained point . It must satisfy the metric axioms: (i) with ; (ii) symmetry ; (iii) the triangle inequality . In LIME's tabular case is typically Euclidean distance on (normalised) features; for images it is a cosine or Hamming-style distance on the on/off superpixel mask (the "#different pixels" count from the parent note). The only structural requirement here is that grows as moves away from , so that far perturbations are down-weighted.

With :

  • : .
  • : .
  • : .

Figure — Feature attribution (SHAP, LIME)
Figure (Ex 4.1) — alt text: the proximity kernel plotted (yellow curve) against distance on the horizontal axis and weight on the vertical axis, for . Three marked points read pink, blue, and pink. The curve is a bell that starts at and decays fast: the far point at is crushed to almost zero, so LIME barely listens to it.

As : every exponent , so all weights approach . The kernel stops distinguishing near from far, and LIME degenerates into a global linear fit — losing the "local" in Local Interpretable. That is why literally sets the radius of the neighbourhood being explained.

Exercise 4.2

A SHAP explanation for Bob reports (with base value as defined at the top of this page):

(a) Reconstruct . (b) Which single feature is most responsible for the high prediction, and is any feature pulling the prediction down?

Recall Solution

(a) By the additive decomposition (this is the Efficiency axiom rearranged, with the base value): (b) debt () is the largest positive driver — it does most of the work raising risk. credit () and income () both lower risk (negative ), consistent with Bob having some protective factors that the strong debt signal overwhelms. This mirrors the loan example in the parent note.

Exercise 4.3

KernelSHAP fits a weighted linear model to sampled coalitions, just like LIME — but with a different weighting kernel

Explain why this specific weighting (rather than LIME's proximity kernel) recovers exact Shapley values, and contrast which coalitions each kernel emphasises.

Recall Solution

Why this exact shape? The Shapley value is a weighted average of marginal contributions with the combinatorial weights . Lundberg & Lee's key result is that if you set up the coalition sampling as a weighted least-squares problem, there is a unique kernel over coalition sizes whose least-squares solution's coefficients equal those Shapley weights — and it is exactly above. Concretely, the factor counteracts two things at once: removes the over-counting of same-size coalitions (there are many of them), and up-weights the informative extremes — coalitions with almost no features or almost all features — because those pin down single-feature marginals most sharply. Feed these weights into the linear fit and the fitted coefficients provably satisfy Efficiency, Symmetry, Dummy and Additivity; converge the sampling and you get the true .

Which coalitions each emphasises:

  • LIME's emphasises perturbations geometrically close to — local fidelity, no axiomatic guarantee.
  • KernelSHAP's emphasises very small and very large coalitions (where or is tiny, the denominator shrinks and blows up) and down-weights medium ones — the shape that forces the linear fit onto the Shapley solution. Same regression skeleton, opposite weighting philosophy.

Level 5 — Mastery

Exercise 5.1

Reconsider the game in 2.2. Now compute directly from the weighted-subset form of the Shapley formula (not by averaging orderings), using weights with . Confirm you get the same .

Recall Solution

Feature ; the coalitions not containing 1 are . Compute weights (with ):

  • : .
  • : (each of and ).
  • : .

Marginals of feature 1:

  • :
  • :
  • :
  • :

Weighted sum:

Same as the ordering average — the weights are the fraction of orderings that produce each coalition. Note : the weights form a probability distribution. ✓

Exercise 5.2

A stakeholder complains: "SHAP said debt = but LIME's coefficient for debt was . One of them is wrong." Diagnose whether this is necessarily a bug.

Recall Solution

Not necessarily a bug. They answer different questions and are on different scales:

  • SHAP's is a marginal contribution to this prediction, guaranteed to satisfy efficiency (the 's sum to ).
  • LIME's coefficient is the slope of a local linear surrogate, in whatever units the (possibly binarised/normalised) perturbation features use, with no efficiency constraint and dependent on and the sampling.

Different objectives, different weightings ⇒ different numbers are expected. The right check is direction and rank consistency (both call debt the dominant positive driver), plus SHAP's efficiency sum. Contradictory signs would be the real red flag. This connects to why 6.3.03-Counterfactual-explanations are sometimes preferred: they sidestep the "which number is true" debate by answering "what minimal change flips the decision?"

Exercise 5.3

For a tree ensemble, exact Shapley values are computable in polynomial time via TreeSHAP instead of the brute force. (a) Give the complexity intuition — why polynomial, not exponential. (b) State why a practitioner might still prefer TreeSHAP over KernelSHAP for a random forest.

Recall Solution

(a) Why polynomial. Brute-force Shapley needs coalition evaluations — exponential in the number of features — because it re-evaluates the model for every subset. TreeSHAP never enumerates subsets. Instead it walks each tree once and, at every node, tracks the proportion of training paths that flow down each branch. Whether a feature is "present" or "marginalised" is handled by pushing a weighted fraction of the sample down both children at that feature's split and combining the leaf outputs. The combinatorial Shapley weights are folded directly into this traversal, so the cost per tree is polynomial in its size and depth — roughly for a tree with leaves and depth , times trees, giving overall. No anywhere, because the tree structure already encodes which feature interactions actually occur.

(b) Why prefer it over KernelSHAP. TreeSHAP returns exact Shapley values with zero sampling variance, while KernelSHAP only converges to them as the number of sampled coalitions and is noisy under a finite budget — the same instability the parent note flags for LIME's small-sample fits. So for a random forest TreeSHAP gives you exactness and speed simultaneously; there is no reason to fall back on an approximation. The Additivity axiom (Ex 3.4) is what makes this legal: you can attribute each tree independently and sum. See 3.5.04-Tree-ensembleinterpretation.


Recall Self-test: three one-liners

Efficiency axiom in words ::: The Shapley values sum exactly to , no leftover residual. What does to LIME ::: Every weight , so LIME becomes a global linear fit and loses locality. Why zeros are wrong for "removing" a feature ::: Absent features must be marginalised over their distribution; zero is itself an informative, possibly out-of-distribution value.