Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 12: Explainability and Responsible AI

Open in Colab

All models are wrong, but some are useful.

George Box

12.1 Why Explain a Model?

A model that scores well on a test set can still be right for the wrong reasons. The classic warning is a horse, Clever Hans, who seemed to do arithmetic in 1900s Berlin and was in fact reading his trainer’s posture. Models do the same: a pneumonia classifier that learned the hospital’s scanner, a wolf detector that learned snow. A test score cannot reveal it, because the shortcut works on the test set too.

Explanations serve four purposes:

  1. Debugging: does the model use sensible features, or a leak (Chapter 7) or a shortcut?

  2. Trust: domain experts accept a model they can check.

  3. Rights: people affected by automated decisions (credit, hiring, medical triage) are increasingly entitled to an explanation, and regulations such as the EU AI Act require documentation of high-risk systems.

  4. Science: which factors drive the outcome? (With care: Section 12.7.)

There are two kinds of question: global (how does the model work overall?) and local (why this prediction for this person?).

12.2 Models That Explain Themselves

Some models are readable as they are.

A linear model on standardised features: each coefficient says how much the score changes for one standard deviation of that feature, all else equal.

test accuracy 0.959; the five largest standardised coefficients (positive = benign):
  radius error           -1.08
  worst texture          -1.07
  mean concave points    -1.01
  worst radius           -1.00
  worst area             -0.88

A shallow tree prints as a set of rules a person can follow:

|--- worst perimeter <= 106.10
|   |--- worst concave points <= 0.16
|   |   |--- class: 1
|   |--- worst concave points >  0.16
|   |   |--- class: 0
|--- worst perimeter >  106.10
|   |--- worst concave points <= 0.14
|   |   |--- class: 0
|   |--- worst concave points >  0.14
|   |   |--- class: 0

test accuracy of this depth-2 tree: 0.906

Interpretable models are the first choice when an explanation is required and they are accurate enough. But their readability has limits: with correlated features (radius, perimeter and area here), linear coefficients split credit arbitrarily (Chapter 7), and a tree deep enough to be accurate is no longer short. For forests, boosting and neural networks, we need post-hoc methods: tools applied to a trained model from the outside.

12.3 Global Importance

Impurity importance

Tree ensembles record how much each feature reduced impurity (Gini or entropy, Chapter 8) across all their splits. It is free, but measured on the training data, and it favours features with many possible split points. We add a column of pure noise to the 30 measurements, to see where it lands:

forest test accuracy 0.942
  worst radius           0.136
  worst perimeter        0.122
  worst area             0.115
  worst concave points   0.113
  mean concave points    0.101
random noise: 0.0015, rank 31 of 31

Permutation importance

Permutation importance asks a more direct question, on held-out data: how much does the score drop when one feature’s values are shuffled, breaking its link with the target?

  worst radius           0.009
  worst concave points   0.008
  worst area             0.007
  worst texture          0.005
  mean concave points    0.001
random noise: 0.000

The noise column is correctly ignored by both. But the permutation importances are all tiny: shuffling the most important feature costs less than 1% accuracy. Is size unimportant? No: radius, perimeter and area (each as mean and worst value) measure the same thing, and when one of them is shuffled, the forest falls back on the others. Shuffle the group together:

accuracy 0.953; drop when "worst radius" alone is shuffled: 0.017; when all six size features are: 0.196

Shuffling all six size measurements together costs about twenty points of accuracy. Permutation importance measures what the model would lose if one feature were removed, given the others, not how much the feature matters in the world. With correlated features, measure groups.

12.4 How a Feature Moves the Prediction

Importance says how much a feature matters, not how. A partial dependence plot (PDP) answers the second question: set the feature to a value vv for every row, average the model’s predictions, and repeat for a grid of values. The diabetes data (442 patients, 10 standardised measurements, disease progression a year later) with gradient boosting:

bmi  at [-0.067, -0.029, 0.01, 0.048, 0.087]:  average prediction [-29.8, -22.8, 21.3, 27.1, 59.8]
s5   at [-0.072, -0.034, 0.004, 0.042, 0.08]:  average prediction [-44.0, -32.7, 9.6, 41.8, 52.7]
age  at [-0.085, -0.046, -0.007, 0.032, 0.071]:  average prediction [8.8, -3.9, -6.1, 4.3, 2.9]
Source
<Figure size 1200x320 with 3 Axes>

Body-mass index raises the predicted progression by about 90 points from low to high; the blood serum measure s5 by about 100; age barely moves it once the others are known. The thin lines are ICE curves (individual conditional expectation): the same computation for single patients. When they run parallel, the average tells the story; when they cross, the feature interacts with others, and the average hides it.

12.5 Explaining One Prediction: Shapley Values

Why did the model predict 319 for this patient, when its average prediction is 150? Shapley values share the difference among the features, using an idea from cooperative game theory (Lloyd Shapley, 1953): a feature’s share is its average marginal contribution over all the orders in which the features could be revealed:

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

where v(S)v(S) is the model’s average prediction when the features in SS are fixed to this patient’s values and the others are drawn from a background sample. The shares add up exactly: average prediction +∑jϕj=+ \sum_j \phi_j = this prediction.

With four features there are only 24=162^4 = 16 subsets, so we can compute them exactly:

patient 256: true progression 346, prediction 318.8, average prediction 150.3
  bmi   +124.4
  s5     +42.1
  bp      +2.9
  age     -0.9
  sum: 150.3 + 168.5 = 318.8

For this patient, body-mass index pushes the prediction up by 124 points and s5 by 42; blood pressure and age barely matter. The library SHAP computes these values efficiently for trees (TreeSHAP) and approximately for any model (KernelSHAP), and draws them as waterfall and summary plots. LIME is a cheaper alternative: it fits a small linear model around the one prediction.

12.6 Counterfactual Explanations

A counterfactual answers the question a person actually asks: what would have to change for the decision to change? For a tumour the logistic regression of Section 12.2 calls malignant (probability of benign 0.24), we search for the smallest change to one of its most important measurements that flips the decision:

tumour 139: P(benign) = 0.24; "radius error" from 1.21 to 0.898 (-26%) flips it to benign

A counterfactual is concrete, and contestable: an applicant refused a loan can be told “approved if your debt were 4 000 lower”. But it explains the model, not the world: a smaller measurement would not make the tumour benign. Good counterfactuals are also plausible (they change features a person can change) and sparse (few features at once).

12.7 What Explanations Cannot Do

  • They describe the model, which learned associations (Chapter 7). A feature the model relies on need not cause anything.

  • Correlated features share or swap credit, in every method above.

  • Different methods can disagree on the same prediction; explanations are themselves approximations.

  • Attention weights and saliency maps (Part III) show where a network looked, not why it decided.

  • An explanation a language model writes about its own answer is a plausible story, not a record of its computation (Chapter 21).

12.8 Fairness

A model trained on historical decisions can reproduce historical bias, even without the sensitive attribute. Simulated loan applications: income, debt and a credit-history length decide whether an applicant can repay; applicants belong to group A or B; group B has shorter credit histories on average (for example, because they are younger), and the bank’s past approvals refused a quarter of the good applicants from B.

Trained on past decisions, group NOT used:
  group A: approval rate 0.75   approved among those who would repay (TPR) 0.91
  group B: approval rate 0.37   approved among those who would repay (TPR) 0.64
  demographic parity difference -0.37   equal opportunity difference -0.27

Two standard measures compare the groups:

MeasureComparesHere
Demographic paritythe rate of positive decisions0.75 against 0.37
Equal opportunitythe true positive rate among those who deserve a positive decision0.91 against 0.64

The model never saw the group, yet a good applicant from B is approved far less often than one from A. Two causes: the labels (past decisions) were biased, and credit history is a proxy for the group. Two remedies, compared:

Trained on true repayment:
  group A: approval rate 0.78   approved among those who would repay (TPR) 0.92
  group B: approval rate 0.47   approved among those who would repay (TPR) 0.75
  demographic parity difference -0.31   equal opportunity difference -0.17

Past-decision model, group-specific threshold for B (0.22 instead of 0.50):
  group A: approval rate 0.75   approved among those who would repay (TPR) 0.91
  group B: approval rate 0.67   approved among those who would repay (TPR) 0.90
  demographic parity difference -0.07   equal opportunity difference -0.00
  • Training on the true outcome removes the label bias and narrows the opportunity gap, but the proxy keeps part of it.

  • A group-specific threshold equalises the true positive rates, at the price of using the group attribute at decision time (which some laws allow and others forbid) and of approving more applicants from B who will not repay.

When base rates differ between groups, demographic parity, equal opportunity and calibration cannot all hold at once (Kleinberg et al., 2016; Chouldechova, 2017). Which one matters is a value judgement, to be made with the people affected, not a technical detail. Removing the sensitive attribute is never enough: postcode, school or history can stand in for it.

12.9 Beyond Accuracy and Fairness

A deployed model carries further duties:

  • Privacy: training data can leak through a model (membership inference); personal data needs consent, minimisation and protection. Differential privacy and federated learning reduce the risk.

  • Security: adversarial examples, data poisoning, and, for language models, prompt injection (Chapter 21).

  • Human oversight: decisions with serious consequences keep a person in the loop, with the authority and the information to overrule; beware automation bias, the tendency to accept a machine’s answer.

  • Monitoring: data drift after deployment silently degrades a model (Chapter 10’s reporting, repeated over time).

  • Documentation: a model card states what a model is for, how it was evaluated, on whom, and its limits; a datasheet does the same for a dataset.

  • Regulation: the EU AI Act (2024) bans some uses, sets strict requirements for high-risk systems (hiring, credit, medical devices) and transparency duties for others; many countries, including Saudi Arabia through SDAIA’s AI ethics principles, publish their own frameworks. Common requirements: risk assessment, documentation, human oversight, accuracy and robustness testing, monitoring.

12.10 Summary

  • Explanations catch shortcuts and leaks that test scores cannot, build trust, and are increasingly a right.

  • Linear models and shallow trees explain themselves; complex models need post-hoc methods.

  • Impurity importance is free but biased; permutation importance on held-out data measures what the model would lose. With correlated features, permute groups.

  • Partial dependence and ICE curves show how a feature moves predictions.

  • Shapley values share one prediction exactly among the features; counterfactuals say what would change the decision.

  • Explanations describe the model, not the world.

  • Fairness measures compare groups; bias enters through labels and proxies; the remedies trade off against each other, and choosing among them is a value judgement.

  • Privacy, security, oversight, monitoring, documentation and regulation complete a responsible deployment.

Exercises

  1. A model that diagnoses skin cancer relies heavily on the presence of a ruler in the photo. Which method of this chapter would reveal it, and why does the test accuracy not?

  2. Explain why impurity importance is computed on training data, and why that is a problem.

  3. Two features are copies of each other. What happens to their permutation importances? What would you report instead?

  4. Read the PDP of age above. Can you conclude that age does not affect diabetes progression? Why not?

  5. Shapley values of a prediction are +30, −10 and +5; the average prediction is 100. What is the prediction?

  6. Give a counterfactual explanation for a refused loan that is sparse and plausible, and one that is neither.

  7. In the loan simulation, why does the model trained without the group attribute still treat the groups differently? Name both mechanisms.

  8. Demographic parity or equal opportunity for (a) a hiring screen, (b) a medical test? Argue both sides for one of them.

Further Reading

  • C. Molnar, Interpretable Machine Learning, 2nd ed., 2022 (free online).

  • S. M. Lundberg, S.-I. Lee, “A unified approach to interpreting model predictions”, NeurIPS, 2017 (SHAP).

  • S. Wachter, B. Mittelstadt, C. Russell, “Counterfactual explanations without opening the black box”, Harvard Journal of Law & Technology, 2018.

  • S. Barocas, M. Hardt, A. Narayanan, Fairness and Machine Learning, MIT Press, 2023 (free online).

  • M. Mitchell et al., “Model cards for model reporting”, FAT*, 2019.

  • The European Union, Artificial Intelligence Act, Regulation (EU) 2024/1689.