Simple Algorithm
Artificial Intelligence · Deep Layer · 26 min

Explainability Methods

LIME, SHAP, saliency and their pitfalls.

A model denies a loan and the applicant asks why. LIME fits a small linear model around the case, SHAP divides the prediction among the features by the only rule that satisfies four axioms, a saliency map highlights the inputs the output is most sensitive to, and a counterfactual says what would have had to change. Each answers a different question, each can be precisely wrong, and some popular saliency methods draw nearly the same picture for a trained network as for one with random weights.

What you’ll learn

  • Distinguish local from global and intrinsic from post hoc explanations, and faithfulness from plausibility.
  • Write LIME's objective and algorithm, and explain why its explanations can be unstable and manipulable.
  • State the Shapley axioms, prove that they determine the Shapley value uniquely, and explain the value-function choices behind SHAP and KernelSHAP.
  • Explain gradient-based saliency methods and the model- and data-randomization sanity checks.
  • Derive minimal counterfactual explanations for linear models in any norm, connect them to adversarial examples, and explain actionable recourse.

What an explanation is for

An explanation answers a question about a model, and different methods answer different questions. Global explanations describe a model's overall behavior, such as which features matter on average; local ones explain a single prediction. Intrinsically interpretable models, such as sparse linear models, short rule lists or small trees, are their own explanation, while post hoc methods explain a black box from outside. Rudin (2019) argues that for high-stakes decisions one should prefer an interpretable model whenever one is about as accurate, because a post hoc explanation is a second model that can be wrong about the first. Two properties are easily confused: faithfulness, whether the explanation reflects what the model actually computes, and plausibility, whether it convinces a person. Only faithfulness is a property of the model.

MethodQuestion it answersAccess neededCharacteristic failure
LIMEWhich features would a simple model use to mimic this one near xx?queriesdepends on the sampling kernel; unstable; queries leave the data manifold
SHAPHow should f(x)f(x) minus a baseline be divided among the features?queries (exact for trees)depends on the value function and baseline; exponential cost; correlated features
Gradients, integrated gradients, Grad-CAMWhich input directions is the output locally sensitive to?gradientssaturation and noise; some variants ignore the model
CounterfactualsWhat is the smallest change that would flip the decision?queries or gradientsinfeasible, implausible or non-unique changes
Explainability methods, the questions they answer, and how each typically fails.

LIME: local surrogate models

ξ(x)=arg min⁡g∈G ∑zπx(z)(f(z)−g(z′))2+Ω(g),πx(z)=exp⁡(−D(x,z)2/σ2)\xi(x)=\argmin_{g\in G}\ \sum_z\pi_x(z)\big(f(z)-g(z')\big)^2+\Omega(g),\qquad\pi_x(z)=\exp\big(-D(x,z)^2/\sigma^2\big)
LIME (Ribeiro, Singh & Guestrin, 2016) explains ff at xx by a simple model gg, usually linear in an interpretable representation z′∈{0,1}dz'\in\{0,1\}^d (words or superpixels present or absent), fitted to the black box's outputs on perturbed samples zz, each weighted by its proximity πx(z)\pi_x(z) to xx. The penalty Ω(g)\Omega(g) limits complexity, for example to KK nonzero weights.
text
function LIME(f, x, N, K, σ):
    samples ← empty
    repeat N times:
        z′ ← random subset of x's interpretable components   # drop words, gray out superpixels
        z  ← the input built from z′
        add (z′, f(z), weight = exp(−D(x, z)² / σ²)) to samples
    S ← K components chosen on the samples (e.g. by a LASSO path)
    g ← weighted least squares of f(z) on the components S of z′
    return the K coefficients of g                          # the explanation

Three weaknesses follow from the construction. The explanation depends on the kernel width σ\sigma and on the random sample, so two runs can rank the features differently. Perturbed samples, such as an image with gray patches, can be unlike anything in the data, so gg describes the model where it was never trained. And that can be exploited: Slack et al. (2020) built a classifier that detects such off-manifold queries and answers them with an innocuous model, while on real inputs it relied on race, and LIME and KernelSHAP explanations then hid the dependence.

Shapley values and SHAP

A cooperative game on players N={1,…,n}N=\{1,\dots,n\} assigns each coalition S⊆NS\subseteq N a value v(S)v(S). To explain ff at xx, the players are the features, and v(S)v(S) is the model's output when only the features in SS are "present". Conditionally, v(S)=E[f(X)∣XS=xS]v(S)=\E[f(X)\mid X_S=x_S]; interventionally, v(S)=EXSˉ[f(xS,XSˉ)]v(S)=\E_{X_{\bar S}}\big[f(x_S,X_{\bar S})\big], with the absent features drawn from a background distribution.

DerivationProof sketch
  1. ∑i[v(Si∪{i})−v(Si)]=v(N)−v(∅)for every order, where Si is the set preceding i\sum_i\big[v(S_i\cup\{i\})-v(S_i)\big]=v(N)-v(\varnothing)\quad\text{for every order, where }S_i\text{ is the set preceding }i

    The formula satisfies the axioms. Add the players in a uniformly random order and credit each with its marginal contribution when it joins; ∣S∣! (n−∣S∣−1)!/n!|S|!\,(n-|S|-1)!/n! is the probability that exactly the set SS precedes ii. In every order the contributions telescope, which gives efficiency, and symmetry, null player and additivity can be read off the formula:

  2. v=∑∅≠T⊆NcT uT,cT=∑S⊆T(−1)∣T∣−∣S∣ v(S)v=\sum_{\varnothing\ne T\subseteq N}c_T\,u_T,\qquad c_T=\sum_{S\subseteq T}(-1)^{|T|-|S|}\,v(S)

    Uniqueness. Subtract v(∅)v(\varnothing), so that v(∅)=0v(\varnothing)=0. The unanimity games uT(S)=1[T⊆S]u_T(S)=\mathbf 1[T\subseteq S], T≠∅T\ne\varnothing, form a basis of all such games (Möbius inversion), and the coefficients are the Harsanyi dividends:

  3. ϕi(v)=∑T∋icT∣T∣■\phi_i(v)=\sum_{T\ni i}\frac{c_T}{|T|}\qquad\blacksquare

    In the game cTuTc_Tu_T, players outside TT are null and get 0, players inside TT are symmetric, and efficiency splits cTc_T among them, so each gets cT/∣T∣c_T/|T|. Additivity then fixes ϕ\phi on every game: any rule satisfying the axioms gives each player an equal share of the dividend of every coalition it belongs to, which is the Shapley value.

Check your understanding

Explain f(x1,x2,x3)=x1+2x2x3f(x_1,x_2,x_3)=x_1+2x_2x_3 at x=(1,1,1)x=(1,1,1), with absent features set to a baseline of 0. What is ϕ2\phi_2?

  1. 0
  2. 0.5
  3. 1
  4. 2
Show the answer

C. 1

The dividends are 1 for {1}\{1\} and 2 for {2,3}\{2,3\}, and every other coalition's is 0. The interaction's 2 is split equally between the two features that create it, so ϕ=(1,1,1)\phi=(1,1,1), which sums to f(1,1,1)−f(0,0,0)=3f(1,1,1)-f(0,0,0)=3 as efficiency requires.

SHAP (Lundberg & Lee, 2017) writes an explanation as an additive model g(z′)=ϕ0+∑iϕizi′g(z')=\phi_0+\sum_i\phi_iz_i' and shows that local accuracy, missingness and a monotonicity property called consistency single out the Shapley values of vv. KernelSHAP estimates them by weighted least squares on sampled coalitions with the Shapley kernel π(z′)=M−1(M∣z′∣) ∣z′∣ (M−∣z′∣)\pi(z')=\frac{M-1}{\binom M{|z'|}\,|z'|\,(M-|z'|)}, under which the regression solution is exactly the Shapley values; exact computation needs 2M2^M evaluations of vv. TreeSHAP computes them exactly for tree ensembles in polynomial time (Lundberg et al., 2020). For a linear model the interventional values are ϕi=wi(xi−E[Xi])\phi_i=w_i\big(x_i-\E[X_i]\big), which equal gradient times (input minus baseline) and integrated gradients from the mean as baseline, whose completeness is proved in Mechanistic Interpretability.

Saliency maps and sanity checks

For differentiable models, the gradient of the class score, ∇xfc(x)\nabla_xf_c(x), is the oldest saliency map (Simonyan, Vedaldi & Zisserman, 2014). Its variants trade noise for other problems: gradient × input; SmoothGrad, which averages gradients over noisy copies of xx (Smilkov et al., 2017); integrated gradients, which integrates along a path from a baseline (Mechanistic Interpretability); Grad-CAM, which weights the last convolutional layer's feature maps by their average gradients (Selvaraju et al., 2017); and guided backpropagation, which also zeroes negative gradients at every ReLU on the way back (Springenberg et al., 2015). For a linear model z=w⊤x+bz=w^\top x+b the gradient is ww for every input, an explanation of the model rather than of the case, while gradient × input, w⊙xw\odot x, varies with the input and sums to z−bz-b.

Think first How can a method that barely depends on the weights still produce a convincing saliency map?

Natural images carry most of their structure in edges and object boundaries. A method whose output is dominated by the input highlights the object's outline whatever the weights; Nie, Zhang & Patel (2018) showed that guided backpropagation essentially performs partial image recovery. The map looks plausible because it is a picture of the input, which is exactly why plausibility cannot substitute for faithfulness. Kindermans et al. (2019) found a related failure: shifting every input by a constant that the first layer's bias exactly cancels leaves the model's outputs unchanged, yet changes gradient × input and integrated gradients with a zero baseline.

Counterfactual explanations and recourse

A counterfactual explanation answers a different question: what is the smallest change to this input that would have changed the decision? Wachter, Mittelstadt & Russell (2018) define it as x′=arg min⁡x′max⁡λ λ(f(x′)−y′)2+d(x,x′)x'=\argmin_{x'}\max_\lambda\ \lambda\big(f(x')-y'\big)^2+d(x,x'), with y′y' the desired output and dd an L1L_1 distance in which each feature is scaled by its median absolute deviation, which favors changing few features. It needs no access to the model's internals and says nothing about why the model works as it does; it says what would have been enough.

DerivationMinimal counterfactuals for a linear model
  1. min⁡δ ∥δ∥subject tow⊤δ≥∣f(x)∣\min_\delta\ \norm\delta\quad\text{subject to}\quad w^\top\delta\ge|f(x)|

    Let f(x)=w⊤x+bf(x)=w^\top x+b with decision 1[f(x)≥0]\mathbf 1[f(x)\ge0], and suppose f(x)<0f(x)<0. The decision flips once w⊤δ≥∣f(x)∣w^\top\delta\ge|f(x)|, so the smallest change in a norm ∥⋅∥\norm\cdot solves

  2. L2: ∣f(x)∣∥w∥2 along w,L∞: ∣f(x)∣∥w∥1 along sign⁡(w),L1: ∣f(x)∣∥w∥∞ on one featureL_2:\ \frac{|f(x)|}{\norm w_2}\ \text{along }w,\qquad L_\infty:\ \frac{|f(x)|}{\norm w_1}\ \text{along }\sign(w),\qquad L_1:\ \frac{|f(x)|}{\norm w_\infty}\ \text{on one feature}

    By Hölder's inequality w⊤δ≤∥w∥∗∥δ∥w^\top\delta\le\norm w_*\norm\delta, where ∥⋅∥∗\norm\cdot_* is the dual norm, with equality for a suitably aligned δ\delta. So the distance to the decision boundary is ∣f(x)∣/∥w∥∗|f(x)|/\norm w_*:

  3. The L1L_1 answer changes only the feature with the largest ∣wj∣|w_j|, which is why Wachter et al.'s weighted L1L_1 distance yields sparse counterfactuals. The L∞L_\infty answer moves every input by the same amount along sign⁡(w)\sign(w): it is the fast gradient sign step of an adversarial example. A minimal counterfactual and a minimal adversarial perturbation are the same mathematical object.

The adversarial widget makes this concrete. Its model is logistic regression on 12×1212\times12 images of 3s and 8s, and its FGSM step x′=clip(x+ε sign⁡(∇xL),0,1)x'=\mathrm{clip}\big(x+\varepsilon\,\sign(\nabla_xL),0,1\big) moves every pixel by ε\varepsilon along ±sign⁡(w)\pm\sign(w), clipped to valid pixel values. For a linear model, that is the largest possible change of the logit among valid images within L∞L_\infty distance ε\varepsilon, so the smallest ε\varepsilon that flips the decision is the L∞L_\infty distance to the nearest counterfactual image.

A counterfactual helps the person affected only if they can act on it. Recourse requires actionability (age and race cannot be changed, and some changes are costly), plausibility (the counterfactual should look like a real applicant, not like the image above) and causal consistency (raising one's income also changes one's debt-to-income ratio). Ustun, Spangher & Liu (2019) compute minimal-cost actionable changes for linear classifiers by integer programming, and Karimi, Schölkopf & Valera (2021) argue that recourse should be computed as interventions in a causal model rather than as independent feature edits. Wachter et al. proposed counterfactuals partly as explanations compatible with the EU's General Data Protection Regulation that do not require opening the black box. Whether that regulation creates a legal right to explanation at all is debated: Wachter, Mittelstadt & Floridi (2017) argue that it does not, and Selbst & Powles (2017) that it does.

Key takeaways

  • Explanations answer different questions: local or global, intrinsic or post hoc. Faithfulness to the model, not plausibility to people, is what makes an explanation evidence.
  • LIME fits a proximity-weighted sparse linear surrogate to perturbed queries; its answers depend on the kernel and the sample, and off-manifold queries make it manipulable.
  • The Shapley value is the unique attribution satisfying efficiency, symmetry, null player and additivity: equal shares of every coalition's Harsanyi dividend. SHAP's answers depend on the value function, since interventional values leave the data manifold and conditional values credit correlated but unused features.
  • Saliency methods must pass sanity checks: plain gradients and Grad-CAM change when the weights are randomized, while guided backpropagation largely does not.
  • For a linear model the minimal counterfactual distance is ∣f(x)∣/∥w∥∗|f(x)|/\norm w_* in the dual norm, and in L∞L_\infty it is the FGSM step. Useful recourse also needs actionability, plausibility and causal structure.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

SHAP is computed with the conditional value function v(S)=E[f(X)∣XS=xS]v(S)=\E[f(X)\mid X_S=x_S]. Can a feature that the model never reads receive a nonzero Shapley value?

  1. No: the null-player axiom guarantees it gets zero
  2. Yes, if it is correlated with features the model does read, because conditioning on it changes vv; the axiom applies to the game vv, not to the model
  3. Only if the model is nonlinear
  4. Only because of KernelSHAP's sampling error
Show the answer

B. Yes, if it is correlated with features the model does read, because conditioning on it changes vv; the axiom applies to the game vv, not to the model

If xjx_j is unused but correlated with a used feature xkx_k, then E[f(X)∣XS=xS]\E[f(X)\mid X_S=x_S] changes when jj joins SS, because conditioning on xjx_j shifts the distribution of xkx_k. So jj is not a null player in vv and receives credit. With the interventional value function, an unused feature does get zero, at the price of evaluating the model off the data manifold.

Question 2

Guided backpropagation produces nearly identical maps for a trained network and for the same network with randomized weights. What does that show?

  1. The network learned nothing
  2. The method mainly reflects the input, such as its edges, rather than what the model learned, so it fails the model-randomization test
  3. Randomized networks are as accurate as trained ones
  4. Guided backpropagation is the most faithful method
Show the answer

B. The method mainly reflects the input, such as its edges, rather than what the model learned, so it fails the model-randomization test

A faithful explanation must change when the model changes. If randomizing the weights leaves the map unchanged, the map is a property of the input, which is why it can look plausible while saying little about the model. Plain gradients and Grad-CAM passed this test in Adebayo et al.'s experiments.

Question 3

A linear classifier f(x)=w⊤x+bf(x)=w^\top x+b with w=(3,−4)w=(3,-4) gives f(x)=−2f(x)=-2, a rejection. What is the smallest Euclidean change to xx that reaches the decision boundary?

  1. 0.4, in the direction of ww
  2. 2, in the direction of ww
  3. 0.5, changing only the second feature
  4. 0.4, in the direction of −w-w
Show the answer

A. 0.4, in the direction of ww

∥w∥2=5\norm w_2=5, so the distance is ∣f(x)∣/∥w∥2=2/5=0.4|f(x)|/\norm w_2=2/5=0.4, along ww, the direction that increases ff. Changing only the second feature, the one with the largest ∣wj∣|w_j|, costs 2/4=0.52/4=0.5: that is the minimal L1L_1 change, not the minimal L2L_2 change.

Question 4

Two LIME runs on the same input rank its top features differently. What is the most likely cause?

  1. The model changed between the runs
  2. LIME fits its surrogate to randomly sampled perturbations weighted by a kernel, so sampling noise and the kernel width change the fitted weights
  3. LIME is exact, so the input must have changed
  4. The interpretable representation was not binary
Show the answer

B. LIME fits its surrogate to randomly sampled perturbations weighted by a kernel, so sampling noise and the kernel width change the fitted weights

The surrogate is a weighted regression on a finite random sample of perturbations; different samples, especially with few of them, give different coefficients, and the kernel width decides how local the fit is. Fixing seeds hides the instability without removing it.

Further reading

  • M. T. Ribeiro, S. Singh & C. Guestrin, "'Why should I trust you?' Explaining the predictions of any classifier," KDD (2016).
  • S. M. Lundberg & S.-I. Lee, "A unified approach to interpreting model predictions," NeurIPS (2017).
  • J. Adebayo, J. Gilmer, M. Muelly, I. Goodfellow, M. Hardt & B. Kim, "Sanity checks for saliency maps," NeurIPS (2018).
  • S. Wachter, B. Mittelstadt & C. Russell, "Counterfactual explanations without opening the black box: Automated decisions and the GDPR," Harvard Journal of Law & Technology (2018).
  • C. Molnar, Interpretable Machine Learning: A Guide for Making Black Box Models Explainable (2nd ed., 2022).