AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
★Advanced & Frontier Topics
  1. Efficient Inference: Quantization, Distillation, Pruning and Faster Decoding
  2. Mixture of Experts: Bigger Models at the Same Compute
  3. Distributed Training: Many GPUs, One Model
  4. Interpretability: Opening the Black Box
  5. AI Safety & Ethics: Bias, Hallucination, Alignment and Regulation
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Advanced & Frontier Topics

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.

Advanced~28 min·6 references
Key terms
InterpretabilitySHAP (SHapley Additive exPlanations)FeatureGradient boostingGradientEmbedding

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.

≈
Analogy: the doctor and the neuroscientist
Ask a doctor why they diagnosed flu and they point to evidence: fever, cough, season. That is post-hoc attribution (SHAP, LIME, saliency): which inputs pushed the decision. A neuroscientist instead records neurons to learn *how* the brain computes. That is mechanistic interpretability: reverse-engineering the model's internal features and circuits. Both are useful; neither alone is the full truth.
MethodScopeModel accessAnswers
Permutation importanceGlobalAgnostic (predictions only)Which features does the model rely on overall?
SHAPLocal + globalAgnostic; fast exact version for treesHow much did each feature push *this* prediction?
LIMELocalAgnosticWhich simple rule approximates the model near this input?
Saliency / Integrated Gradients / Grad-CAMLocalGradients (white-box)Which pixels or tokens mattered?
Probes, sparse autoencoders, circuitsInternalActivations (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.

φᵢ = Σ_{S ⊆ F∖{i}} [ |S|! (|F| − |S| − 1)! / |F|! ] · ( f(S ∪ {i}) − f(S) ) f(x) = φ₀ + Σᵢ φᵢ
Example: base value Rp 300 jt; “luas tanah” +120 jt, “lokasi” +80 jt, “umur bangunan” −40 jt → prediction Rp 460 jt.
In words: “feature i's credit = its average extra contribution when it joins a group of other features, averaged fairly over all orders in which features could join”. The second part says the credits add up exactly: base value plus all φᵢ equals the prediction.
Symbols(hover a symbol in the formula)
φᵢ
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
Two features (1 = luas tanah, 2 = lokasi), prices in Rp jt f(∅) = 300, f({1}) = 420, f({2}) = 380, f({1, 2}) = 460; each weight = 1/2 φ₁ = ½ · (420 − 300) + ½ · (460 − 380) = 60 + 40 = 100 φ₂ = ½ · (380 − 300) + ½ · (460 − 420) = 40 + 20 = 60 φ₀ + φ₁ + φ₂ = 300 + 100 + 60 = 460 = f(x) ✓

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) = argmin_{g ∈ G} L(f, g, πₓ) + Ω(g)
Find a simple model g (from class G) that mimics f near x (weighted by πₓ) while staying simple (Ω penalises complexity).
In words: “the explanation of x is the simple model that best imitates the black box in the neighbourhood of x, without getting too complicated”. Closeness to x is enforced by weighting perturbed samples with πₓ.
Symbols(hover a symbol in the formula)
ξ(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
3 perturbed samples near x, weights πₓ = [1.0, 0.6, 0.2] black box f = [0.9, 0.7, 0.2], candidate g = [0.85, 0.75, 0.5] L = 1.0 · 0.05² + 0.6 · 0.05² + 0.2 · 0.3² = 0.0025 + 0.0015 + 0.018 = 0.022 The far sample (weight 0.2) barely counts. Ω(g) = 2 if g uses 2 features.

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) = (xᵢ − x′ᵢ) × ∫₀¹ ∂F(x′ + α·(x − x′)) / ∂xᵢ dα
x′ is the baseline; in practice the integral is approximated with 20–300 steps.
In words: “feature i's attribution = how far it moved from the baseline × its average gradient along the straight path from baseline to input”. Averaging along the path avoids the saturation problem of a single gradient, and the attributions add up to F(x) − F(x′).
Symbols(hover a symbol in the formula)
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
F(x) = x₁ · x₂, baseline x′ = (0, 0), input x = (2, 3); path point = (2α, 3α) ∂F/∂x₁ = x₂ = 3α → ∫₀¹ 3α dα = 1.5 → IG₁ = (2 − 0) × 1.5 = 3 ∂F/∂x₂ = x₁ = 2α → ∫₀¹ 2α dα = 1 → IG₂ = (3 − 0) × 1 = 3 IG₁ + IG₂ = 6 = F(x) − F(x′) = 6 − 0 ✓

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

knobbackground / reference data size (SHAP)
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.
knobnum_samples / kernel_width (LIME)
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.
knobIG steps and baseline
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).
knobSAE dictionary size and L1 sparsity coefficient
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

python
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}")
Compare the two rankings: when they disagree, look for correlated features.
!
How explanations mislead
Attribution is not causation: SHAP says how the *model* used a feature, not how the world works — a high SHAP value for “postcode” may reveal a proxy for ethnicity, not a real effect. Correlated features split or swap credit unpredictably. Attention weights are not explanations by themselves; they show where information flowed, not why. Explanations can be gamed: models can be built to look fair to LIME/SHAP while behaving unfairly on real data. Plausible ≠ faithful: an explanation that matches human intuition may not reflect the model's actual computation — validate with sanity checks and interventions.
▸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

1.
A SHAP waterfall shows base value 0.20 and contributions +0.30, −0.05 and +0.10. What is the model's output for this example?
2.
Two features are almost perfectly correlated. What tends to happen with permutation importance?
3.
What does LIME fit to explain a single prediction?
4.
A saliency method produces almost the same map for a trained model and for the same model with randomised weights. What should you conclude?
5.
Why are individual neurons in language models often hard to interpret?
Score: 0/5

References

  1. [1]
    A Unified Approach to Interpreting Model Predictions
    PaperLundberg & Lee2017arxiv.org
    SHAP.
  2. [2]
    “Why Should I Trust You?”: Explaining the Predictions of Any Classifier
    PaperRibeiro et al.2016arxiv.org
    LIME, including the husky-vs-wolf example.
  3. [3]
    Axiomatic Attribution for Deep Networks
    PaperSundararajan et al.2017arxiv.org
    Integrated Gradients.
  4. [4]
    Sanity Checks for Saliency Maps
    PaperAdebayo et al.2018arxiv.org
  5. [5]
    Towards Monosemanticity: Decomposing Language Models With Dictionary Learning
    ArticleBricken et al. (Anthropic)2023transformer-circuits.pub
  6. [6]
    Interpretable Machine Learning (book)
    BookMolnarchristophm.github.io
← Previous
Distributed Training: Many GPUs, One Model
Next →
AI Safety & Ethics: Bias, Hallucination, Alignment and Regulation