Level 3 In-Depth AI · Safety, Ethics and Society
Interpretability and Explainability
Ways to find out why a model made a prediction and what it relies on overall, from permutation importance and SHAP values to saliency maps and probes, and why every explanation must be checked before you trust it.
- Level
- ●●●●● Intermediate
- Reading
- 13 min
- To learn it well
- 1 hour to read, an hour to try the code
- Builds on
- 14 concepts →
- Quiz
- 5 questions ↓
Read first
Neural NetworksThis leads to
Mechanistic InterpretabilityThe full path from zero — 14 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Interpretability and Explainability
Read them roughly in this order. See it on the concept map →
Why it matters
A neural network with millions of weights can be very accurate and still completely opaque. You see the input and the output, but the reasoning in between is a huge pile of multiplications. That is a problem whenever you need to know why:
- Debugging. Is the model right for the right reasons, or has it found a shortcut that will break in the real world?
- Trust and safety. A doctor deciding whether to rely on a diagnosis tool, or an engineer deciding whether to ship one, needs more than a score.
- Fairness. Is a credit model quietly using a proxy for race or sex?
- Law. Europe's GDPR gives people rights around significant decisions made solely by automated means, including meaningful information about the logic involved. The EU AI Act adds transparency duties for high-risk systems (see AI Regulation and Governance).
- Science. Sometimes the model has found a real pattern, and we want to learn it too.
Interpretability is the degree to which a human can understand why a model behaves as it does. Explainability usually means the methods that produce explanations after the fact for models that aren't interpretable on their own. People often use the two words interchangeably. This chapter covers the practical toolbox. Its sequel, Mechanistic Interpretability, goes inside large networks to reverse-engineer the algorithms they have learned.
The intuition
Imagine a brilliant colleague who never explains their decisions. You can still learn a lot about how they think:
- Take things away and see what changes. Hide one piece of information at a time and watch whether their answer changes. If hiding someone's income changes the loan decision a lot, income mattered.
- Ask about one case or about their habits. "Why did you reject this applicant?" is a local explanation. "What do you usually pay attention to?" is a global explanation.
- Watch where their eyes go. For an image, which pixels did they focus on?
- Test what they know. Ask questions that reveal whether some concept is stored in their head, even if they never say it.
Almost every interpretability method is one of these four ideas made precise: perturbation, attribution, gradients and probing.
A classic warning shows why this matters. In the 2016 paper that introduced LIME, the authors deliberately trained a classifier to tell huskies from wolves using pictures where every wolf stood on snow. The model scored well, and the explanation showed it was looking at the snow, not the animal. This is shortcut learning: the model latches on to an easy feature that happens to correlate with the label in the training data. Real cases exist too. A 2018 study by Zech and colleagues found that chest X-ray models could detect which hospital an image came from, and hospitals differed in how common pneumonia was, a shortcut that hurt performance at new hospitals.
Key idea An explanation is itself a model of the model: a simplification. It can be helpful, and it can be wrong. Use explanations to generate hypotheses ("it seems to use the background"), then test those hypotheses directly ("does accuracy drop if I change the background?").
How it works
Interpretable by design
The simplest route is a model you can read. Linear and logistic regression have one weight per feature. A small decision tree is a flowchart. Generalised additive models add up one curve per feature. For tabular data these are often nearly as accurate as black boxes. Cynthia Rudin argued in 2019 that for high-stakes decisions you should prefer such models over explaining a black box afterwards, when they perform comparably. For images, audio and text there is usually no interpretable model that comes close, so we need the methods below.
Permutation importance (global)
Permutation importance answers: "How much worse does the model get if this feature becomes useless?" You make a feature useless without retraining by shuffling its column in the test data. That breaks its link with the target but keeps its distribution.
- Measure the model's score on test data (accuracy, or for regression).
- For each feature : shuffle column , measure the score again, and record the drop.
- Repeat the shuffle several times and average, because one shuffle is noisy.
Here is the original score, is the score after the -th shuffle of feature , and is the number of repeats. A large means the model leans heavily on feature . A value near zero means it doesn't use it, or that another, correlated feature can stand in for it.
It works with any model, it is cheap, and it is measured on held-out data, so it reflects what matters for generalisation. Compare it with the impurity importance built into Random Forests and Bagging, which counts how much each feature's splits reduced error during training. That number is computed on training data and is biased towards features with many distinct values, even random ones. The code below demonstrates exactly that.
Shapley values and SHAP (local)
Permutation importance tells you what matters on average. To explain one prediction, the most principled tool is the Shapley value, from cooperative game theory (Lloyd Shapley, 1953). Treat the features as players in a team, and the prediction as the team's payout. How do you share the payout fairly among the players?
Shapley's answer: consider every possible order in which the players could join the team, measure how much each player adds at the moment they join, and average over all orders.
A worked example. A loan model gives an average score of 50 when it knows nothing about the applicant. Knowing only income, it gives 70. Knowing only debt, it gives 40. Knowing both, it gives 65. There are two orders:
| Order | Income adds | Debt adds |
|---|---|---|
| income first, then debt | 70 − 50 = +20 | 65 − 70 = −5 |
| debt first, then income | 65 − 40 = +25 | 40 − 50 = −10 |
| average (Shapley value) | +22.5 | −7.5 |
The two values add up to 15, exactly the gap between this prediction (65) and the average (50). That is the key property: Shapley values always add up to "prediction minus baseline", so they divide the credit completely and without double counting. Formally, for feature in a set of features :
Read it as: for every group of other features, compute how much adding feature changes the prediction , and take a weighted average. The weights (the factorials, where means ) are exactly the fraction of joining orders in which feature arrives just after the group .
The catch is cost: with features there are groups. SHAP (SHapley Additive exPlanations; Lundberg and Lee, 2017) is a family of fast approximations, plus an exact fast algorithm for tree models. "Removing" a feature in practice means averaging over values drawn from a background dataset. For a linear model with independent features, the Shapley value is simply the weight times how far the feature is from its average, which is how the figure below was computed.
LIME (Ribeiro and colleagues, 2016) takes a different route to a local explanation. It creates many slightly changed copies of the input, asks the black box to predict each, and fits a small linear model to those answers. The linear model's weights are the explanation. It is simple and works for any model, but the result can change noticeably between runs and with the choice of "nearby".
Saliency maps and gradients (neural networks)
For a neural network you can use calculus. The gradient of the class score with respect to each input pixel says how much a tiny change to that pixel would change the score. Plot the size of those gradients as an image and you get a saliency map: a heat map of "where the model is looking" (Simonyan and colleagues, 2013). It costs one backward pass, the same Backpropagation used in training, but with respect to the input instead of the weights.
Raw gradients are noisy, so refinements followed: Integrated Gradients (2017) averages gradients along a path from a blank image to the real one, and Grad-CAM (2016) uses the gradients flowing into the last convolutional layer to produce a coarser, cleaner map. For text models the same ideas give a score per token.
Watch out In 2018, Adebayo and colleagues ran a simple sanity check: randomise the trained model's weights and recompute the saliency map. For some popular methods, the map barely changed. Those maps were mostly showing edges in the input image, not what the model had learned. Always check that an explanation changes when the model changes.
Probing (what is represented inside)
A probing classifier asks what information is stored in a network's hidden layers. Take the internal activations for many inputs, and train a small, simple model (usually linear) to predict some property from them: the part of speech of a word, whether a sentence is true, the colour of an object. If a linear probe succeeds, the information is present in a form that is easy to read out. Probes have shown, for example, that BERT's middle layers encode a lot of grammatical structure.
Probing shows that information is present. It doesn't show that the model uses it. To test use, you intervene: change the internal representation along the probe's direction and see whether the model's behaviour changes. That step, from correlation to cause, is the starting point of Mechanistic Interpretability.
In code
This example trains a random forest on scikit-learn's built-in diabetes dataset (442 patients, 10 measurements, predicting disease progression a year later) and adds a column of pure random noise that we know is useless. Then it compares permutation importance with the forest's built-in impurity importance.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.ensemble import RandomForestRegressor
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
X, y = load_diabetes(return_X_y=True, as_frame=True)
rng = np.random.default_rng(0)
X["random_noise"] = rng.normal(size=len(X)) # a feature we KNOW is useless
X_tr, X_te, y_tr, y_te = train_test_split(X, y, random_state=0)
model = RandomForestRegressor(n_estimators=200, random_state=0).fit(X_tr, y_tr)
print(f"test R^2: {model.score(X_te, y_te):.2f}")
result = permutation_importance(model, X_te, y_te, n_repeats=20, random_state=0)
order = result.importances_mean.argsort()[::-1]
print(f"{'feature':>13} {'permutation':>11} {'impurity':>9}")
for i in order:
print(f"{X.columns[i]:>13} {result.importances_mean[i]:>8.3f} ± {result.importances_std[i]:.3f}"
f" {model.feature_importances_[i]:>6.3f}")
# test R^2: 0.26
# feature permutation impurity
# bmi 0.164 ± 0.073 0.337
# s5 0.110 ± 0.049 0.264
# bp 0.032 ± 0.032 0.085
# age 0.016 ± 0.008 0.040
# random_noise 0.011 ± 0.010 0.050
# sex 0.003 ± 0.003 0.008
# s2 -0.002 ± 0.014 0.045
# ...
Both methods agree that body-mass index (bmi) and a blood-serum measurement (s5) dominate. But impurity importance gives the useless noise column 0.050, more than age, sex, s1, s2 and s4, because a tree can always find some split on a continuous random column that helps on the training data. Permutation importance on the test set puts it at 0.011 ± 0.010, indistinguishable from zero. Small negative values mean shuffling the feature happened to help slightly: also "not important".
For a local explanation of a single prediction, the SHAP library is the usual tool (pip install shap):
import shap
explainer = shap.TreeExplainer(model) # exact, fast algorithm for tree ensembles
explanation = explainer(X_te.iloc[:100])
shap.plots.waterfall(explanation[0]) # one patient, like the figure above
shap.plots.beeswarm(explanation) # all 100 patients: a global summary
Common pitfalls
- Correlated features share or hide credit. If two features carry the same information, shuffling one barely hurts because the model uses the other. Both look unimportant. Group correlated features, or check correlations first.
- Importance is not causation. A feature can be important to the model without causing the outcome. Ice-cream sales may predict drownings because both rise in summer.
- Explaining a bad model. If the model is inaccurate, explanations describe its errors, not the world. In our example the forest's test is only 0.26.
- Unfaithful explanations. An explanation is faithful if it reflects what the model actually computed. Plausible-looking saliency maps can fail this, as the sanity checks showed. The same applies to the step-by-step reasoning a language model writes in Chain-of-Thought and Reasoning Prompts: research (for example Turpin and colleagues, 2023) shows the written reasoning does not always reflect what drove the answer.
- Explanations can be gamed. Researchers have built models that hide a biased rule from LIME and SHAP while still applying it. An explanation from the model's owner is not an audit.
- Confirmation bias. People see what they expect in heat maps. Decide in advance what result would change your mind.
Where it leads
- Mechanistic Interpretability tries to fully reverse-engineer what a network computes: the features stored in its activations and the circuits that connect them.
- Bias and Fairness uses these tools to detect proxies and unequal treatment.
- Adversarial Examples uses the same input gradients as saliency maps, but to fool the model instead of explaining it.
- AI Alignment and AI Risks and Safety rely on interpretability as one of the few ways to check what a powerful model is "really" doing, beyond its outputs.
- Random Forests and Bagging and Gradient Boosting: XGBoost and LightGBM are the models where SHAP is most often used in practice.
A bit of history
Explaining expert systems was a research topic in the 1980s: MYCIN, a medical expert system, could answer "why?" by listing the rules it had used. With statistical learning the focus shifted to feature importance. Leo Breiman introduced permutation importance for random forests in 2001. Deep learning made the problem urgent. Zeiler and Fergus visualised what CNN layers respond to in 2013, Simonyan and colleagues introduced gradient saliency the same year, LIME followed in 2016 and SHAP in 2017. The US research agency DARPA ran an Explainable AI (XAI) programme from 2017. A wave of critical work from 2018 onwards, including the saliency sanity checks and Rudin's argument for interpretable models, made the field more careful about testing explanations rather than just admiring them. For large language models, attention has moved towards Mechanistic Interpretability and towards evaluating whether models' own explanations are faithful.
Try it
- Run the code and then duplicate the
bmicolumn asbmi_copy. What happens to the permutation importance ofbmi? Why?- Rework the Shapley example with a third feature, "employment", using any numbers you like. Check that the three values add up to the prediction minus 50. (There are now six joining orders.)
- Harder: train a small PyTorch classifier on
sklearn.datasets.load_digits, then compute a saliency map for one image withx.requires_grad_(True), a forward pass and.backward()on the true class's score. Plotx.grad.abs()as an 8 × 8 image. Then randomise the weights and plot again. Does the map change?Hint for 1: the forest can use either copy, so shuffling one of them hurts much less.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Interpretable Machine Learning
A clear guide to making black-box models explainable: feature importance, SHAP, LIME and more.
scikit-learn: Permutation feature importance
The user guide for permutation importance, with a clear warning about why impurity-based importances can mislead and how correlated features confuse both.
SHAP documentation
The standard Python library for SHAP values, with tutorials on waterfall, beeswarm and dependence plots for trees, linear models and deep networks.
A Unified Approach to Interpreting Model Predictions
Introduces SHAP, which explains a single prediction with Shapley values from game theory and shows that LIME and several other methods are special cases.
"Why Should I Trust You?": Explaining the Predictions of Any Classifier
Introduces LIME, which explains one prediction by fitting a simple model to the black box's behaviour on nearby perturbed inputs. Includes the famous husky-versus-wolf example.
Sanity Checks for Saliency Maps
Shows that some popular saliency methods produce nearly the same maps even after the model's weights are randomised, so they cannot be explaining what the model learned.
Feature Visualization
Beautiful interactive article showing the patterns that excite neurons at each depth of an image network.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/society/interpretability.md