◆ AI All-in-One

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
↗ Plan a path here

Read first

Neural Networks

This leads to

Mechanistic Interpretability
The full path from zero — 14 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Gradient Descent
  10. Supervised Learning
  11. Linear Regression
  12. The Perceptron
  13. Logistic Regression
  14. Neural Networks
  15. 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.

  1. Measure the model's score on test data (accuracy, or R2R^2 for regression).
  2. For each feature jj: shuffle column jj, measure the score again, and record the drop.
  3. Repeat the shuffle several times and average, because one shuffle is noisy.
Ij=s−1K∑k=1Ksj,kI_j = s - \frac{1}{K}\sum_{k=1}^{K} s_{j,k}

Here ss is the original score, sj,ks_{j,k} is the score after the kk-th shuffle of feature jj, and KK is the number of repeats. A large IjI_j means the model leans heavily on feature jj. 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 ii in a set of features FF:

ϕi=∑S⊆F∖{i}∣S∣! (∣F∣−∣S∣−1)!∣F∣! [f(S∪{i})−f(S)]\phi_i = \sum_{S \subseteq F \setminus \{i\}} \frac{|S|!\,(|F|-|S|-1)!}{|F|!}\,\big[f(S \cup \{i\}) - f(S)\big]

Read it as: for every group SS of other features, compute how much adding feature ii changes the prediction ff, and take a weighted average. The weights (the factorials, where n!n! means 1×2×⋯×n1 \times 2 \times \dots \times n) are exactly the fraction of joining orders in which feature ii arrives just after the group SS.

The catch is cost: with nn features there are 2n2^n 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.

140 160 180 200 220 240 260 280 average prediction 152.1 s5 serum triglycerides +59.3 bmi body-mass index +29.7 s6 blood sugar +11.8 sex −10.5 s3 HDL cholesterol +10.3 bp blood pressure +9.4 s4 cholesterol ratio +8.2 3 others s2, s1, age +1.1 this patient's prediction: 271.3 predicted disease progression Why did the model predict 271 for this patient? red = pushes up · blue = pushes down
Fig. 1 A SHAP-style waterfall chart for one patient in scikit-learn's diabetes dataset. The model's average prediction is 152.1. Each bar shows how much one feature of this patient pushes the prediction up (red) or down (blue). Together they reach this patient's prediction of 271.3.

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
#  ...
Permutation importance drop in test R² when shuffled (± spread) Impurity importance built into the random forest bmi s5 bp age random_noise sex s2 s3 s6 s1 s4 0 0.1 0.2 0 0.1 0.2 0.3 A column of pure noise ranks 5th on permutation importance (within its error bar of zero) but beats 5 real features on impurity importance, because trees can split on anything.
Fig. 2 The same model explained two ways. Permutation importance (left, measured on test data) puts the noise column near zero, within its error bar. Impurity importance (right, from training) gives the noise column a higher score than five real medical measurements.

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 R2R^2 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

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

  1. Run the code and then duplicate the bmi column as bmi_copy. What happens to the permutation importance of bmi? Why?
  2. 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.)
  3. Harder: train a small PyTorch classifier on sklearn.datasets.load_digits, then compute a saliency map for one image with x.requires_grad_(True), a forward pass and .backward() on the true class's score. Plot x.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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You add a column of pure random noise to a dataset. A random forest's impurity importance ranks it above several real features. Why?

  2. A loan model's average score is 50. Income alone gives 70, debt alone 40, both together 65. What is income's Shapley value?

  3. Two features carry the same information. Permutation importance shows both as nearly unimportant. What is happening?

  4. You randomise a trained network's weights and the saliency map barely changes. What does this tell you?

  5. A linear probe on a hidden layer predicts part of speech with high accuracy. What can you conclude?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Interpretable Machine Learning

Christoph Molnar · Intermediate · Free

A clear guide to making black-box models explainable: feature importance, SHAP, LIME and more.

Docs

scikit-learn: Permutation feature importance

scikit-learn · Intermediate · Free

The user guide for permutation importance, with a clear warning about why impurity-based importances can mislead and how correlated features confuse both.

Tool

SHAP documentation

Scott Lundberg and contributors · Intermediate · Free

The standard Python library for SHAP values, with tutorials on waterfall, beeswarm and dependence plots for trees, linear models and deep networks.

Paper

A Unified Approach to Interpreting Model Predictions

Scott Lundberg & Su-In Lee · 2017 · Advanced · Free

Introduces SHAP, which explains a single prediction with Shapley values from game theory and shows that LIME and several other methods are special cases.

Paper

Sanity Checks for Saliency Maps

Julius Adebayo, Justin Gilmer, Michael Muelly, Ian Goodfellow, Moritz Hardt & Been Kim · 2018 · Advanced · Free

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.

Article

Feature Visualization

Olah, Mordvintsev & Schubert (Distill) · 2017 · Intermediate · Free

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