Interpretability: Opening the Black Box
Tools for understanding why a model predicts what it does: feature importance, SHAP, LIME, saliency maps and integrated gradients, and mechanistic interpretability with sparse autoencoders — plus how explanations can mislead.
A model with 95% test accuracy can still be right for the wrong reasons. In the LIME paper[2], a classifier that separated wolves from huskies turned out to be a snow detector: wolf photos in the training set had snowy backgrounds. Interpretability is the toolbox for catching such shortcuts, debugging models, satisfying regulators (credit decisions and other high-risk uses must be explainable), building user trust and, for frontier AI, checking whether a model's internal reasoning is safe.
| Method | Scope | Model access | Answers |
|---|---|---|---|
| Permutation importance | Global | Agnostic (predictions only) | Which features does the model rely on overall? |
| SHAP | Local + global | Agnostic; fast exact version for trees | How much did each feature push *this* prediction? |
| LIME | Local | Agnostic | Which simple rule approximates the model near this input? |
| Saliency / Integrated Gradients / Grad-CAM | Local | Gradients (white-box) | Which pixels or tokens mattered? |
| Probes, sparse autoencoders, circuits | Internal | Activations (white-box) | What concepts are represented, and how are they computed? |
1. Feature importance
Tree ensembles report impurity-based importance for free, but it is biased toward features with many unique values (IDs, continuous noise) and is computed on training data. Permutation importance is more honest: shuffle one Feature column in the validation set and measure how much the score drops. Its weakness: if two features are strongly correlated (e.g. *gaji* and *pengeluaran*), shuffling one barely hurts because the other carries the same information — both may look unimportant.
2. SHAP: fair credit assignment
SHAP (Lundberg & Lee, 2017)[1] borrows Shapley values from cooperative game theory: the features are players, the prediction is the payout, and each feature's share is its average marginal contribution over all possible orders in which features could “join”. The values are additive — base value plus all contributions equals the model output exactly — and satisfy fairness properties (consistency, missing features get zero). Exact computation is exponential in the number of features, so SHAP uses fast exact algorithms for trees (TreeSHAP) and sampling approximations (KernelSHAP, PermutationSHAP) for other models.
- φᵢ
- phi-i, the SHAP value (credit) of feature i
- Σ_{S ⊆ F∖{i}}
- sum over every subset S of the other features (all features except i)
- S
- a coalition: a set of features that are “present”
- F
- the set of all features
- |S|!
- factorial of the size of S (3! = 6)
- (|F| − |S| − 1)!
- factorial of how many other features come after i
- |F|!
- number of possible orders of all features
- f(S ∪ {i})
- model output when the features in S plus i are known
- f(S)
- model output when only the features in S are known (others averaged out)
- φ₀
- base value: the average prediction over the data
- f(x)
- the model's prediction for this example
▸Worked example
3. LIME: a local, simple stand-in
LIME (Ribeiro et al., 2016)[2] explains one prediction by perturbing the input (removing words, hiding image super-pixels, jittering values), asking the black-box model for predictions on those variants, weighting variants by closeness to the original, and fitting a small interpretable model — usually a sparse linear model — to that neighbourhood. It works on any model and data type, but explanations depend on the perturbation scheme and kernel width, and can change from run to run.
- ξ(x)
- xi of x: the explanation (a fitted simple model) for input x
- argmin_{g ∈ G}
- the g from class G that makes the expression smallest
- G
- class of interpretable models, e.g. sparse linear models
- L(f, g, πₓ)
- locality-weighted error of g imitating f
- f
- the black-box model being explained
- πₓ
- proximity kernel: weight of each perturbed sample by its closeness to x
- Ω(g)
- complexity penalty, e.g. number of non-zero weights
▸Worked example
4. Saliency for neural networks
For images and text, the Gradient of the class score with respect to the input shows which pixels or tokens would change the output most — a saliency map. Raw gradients are noisy and can saturate, so Integrated Gradients (Sundararajan et al., 2017)[3] accumulates gradients along a straight path from a baseline (e.g. a black image) to the input, satisfying an additivity property similar to SHAP. Grad-CAM uses gradients flowing into the last convolutional layer to produce coarse heatmaps. Caution: Adebayo et al.[4] showed that some popular saliency methods produce nearly the same maps even when the model's weights are randomised — they reflect image edges, not the model's reasoning. Always run such sanity checks.
- IGᵢ(x)
- integrated-gradients attribution of feature i for input x
- xᵢ
- value of feature i in the input
- x′ᵢ
- value of feature i in the baseline
- x′
- the baseline input (e.g. a black image, all-zero embedding)
- ×
- multiply
- ∫₀¹
- integral (continuous average) over α from 0 to 1
- ∂F(x′ + α·(x − x′)) / ∂xᵢ
- gradient of the model output w.r.t. feature i at a point on the path
- α
- alpha, position on the path: 0 = baseline, 1 = input
- dα
- integration variable
▸Worked example
5. Mechanistic interpretability
Mechanistic interpretability tries to reverse-engineer *what is computed inside*. A first obstacle is polysemanticity: single neurons respond to unrelated things (e.g. academic citations *and* Korean text), because models store more features than they have neurons — superposition. Anthropic's “Towards Monosemanticity” (Bricken et al., 2023)[5] trained a sparse autoencoder (SAE) on a small transformer's activations: it rewrites each activation vector as a sparse combination of many learned directions (dictionary learning), and those directions turned out to be far more interpretable — features for DNA sequences, Arabic script, base64, legal language. Later work scaled SAEs to production models and showed that amplifying a feature steers behaviour, evidence that the features are causally used. Related tools include linear probes (train a classifier on activations to test if a concept is linearly readable) and circuit analysis (tracing how specific heads, such as induction heads, implement behaviours).
The knobs
- What it is
- The sample of data used to represent “feature absent” (and the base value φ₀); also nsamples/max_evals for sampling explainers.
- ↑ If you increase it
- More stable, representative attributions, but compute grows linearly (KernelSHAP can become very slow).
- ↓ If you decrease it
- Fast, but noisy values that depend on which few rows you picked; a biased background shifts every explanation.
- Typical values
- 100–1,000 background rows (or k-means summary); choose a meaningful reference population.
- What it is
- How many perturbed samples LIME draws, and how quickly their weight decays with distance from the original input.
- ↑ If you increase it
- More samples → more stable explanations. Wider kernel → explanation covers a bigger neighbourhood (more global, less faithful locally).
- ↓ If you decrease it
- Fewer samples → explanations change between runs. Narrower kernel → very local but based on few effective samples.
- Typical values
- num_samples 1,000–5,000; default kernel width 0.75 × √(number of features) for tabular data.
- What it is
- Number of interpolation steps for Integrated Gradients, and the reference input x′ the path starts from.
- ↑ If you increase it
- More steps → better integral approximation (attributions sum closer to F(x) − F(x′)), linearly more compute.
- ↓ If you decrease it
- Faster but the completeness check fails; a poorly chosen baseline (e.g. black for dark objects) hides real contributions.
- Typical values
- 50–300 steps; try several baselines (black, blurred, mean, padding token).
- What it is
- How many features the sparse autoencoder learns, and how strongly it is pushed to use few of them per input.
- ↑ If you increase it
- Bigger dictionary → finer, more specific features (features “split”). Higher L1 → sparser, cleaner features but worse reconstruction.
- ↓ If you decrease it
- Smaller dictionary → coarse, still-polysemantic features. Lower L1 → accurate reconstruction but dense, hard-to-read codes.
- Typical values
- Dictionary 4×–64× the layer width (much larger for big models); tune L1 for a few to tens of active features per token.
In code: SHAP and permutation importance
import shap, xgboost
from sklearn.model_selection import train_test_split
from sklearn.inspection import permutation_importance
X, y = shap.datasets.california() # house prices, 8 features
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
model = xgboost.XGBRegressor(n_estimators=300, max_depth=4).fit(X_tr, y_tr)
# SHAP: exact TreeSHAP with a background sample
explainer = shap.Explainer(model, X_tr.sample(200, random_state=0))
sv = explainer(X_te)
shap.plots.waterfall(sv[0]) # why THIS house got its price
shap.plots.beeswarm(sv) # global view: impact and direction per feature
# Permutation importance on held-out data
pi = permutation_importance(model, X_te, y_te, n_repeats=10, random_state=0)
for name, imp in sorted(zip(X.columns, pi.importances_mean), key=lambda t: -t[1])[:5]:
print(f"{name:12s} {imp:.3f}")▸Go deeper: the Shapley axioms and superposition
Shapley values are the *unique* attribution satisfying four axioms: efficiency (contributions sum to the total), symmetry (features that contribute equally get equal credit), dummy (a feature that never changes the output gets zero) and additivity (attributions of a sum of games are the sum of attributions). SHAP's contribution was to connect this to existing explanation methods (LIME, DeepLIFT) and to provide fast estimators[1]. A practical subtlety is how to “remove” a feature — by sampling from the marginal (interventional) or conditional distribution — which can change results when features are correlated[6].
Superposition is possible because in high dimensions you can fit many more *almost* orthogonal directions than dimensions. If features are sparse (rarely active together), the model can pack them into overlapping directions with little interference. Sparse autoencoders exploit the same sparsity assumption in reverse to pull the features apart again[5].
Quiz
References
- [1]
- [2]“Why Should I Trust You?”: Explaining the Predictions of Any ClassifierPaperRibeiro et al.2016arxiv.orgLIME, including the husky-vs-wolf example.
- [3]
- [4]Sanity Checks for Saliency MapsPaperAdebayo et al.2018arxiv.org
- [5]Towards Monosemanticity: Decomposing Language Models With Dictionary LearningArticleBricken et al. (Anthropic)2023transformer-circuits.pub
- [6]Interpretable Machine Learning (book)BookMolnarchristophm.github.io