Chapter 12: Explainability and Responsible AI
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:
Debugging: does the model use sensible features, or a leak (Chapter 7) or a shortcut?
Trust: domain experts accept a model they can check.
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.
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.
import numpy as np
import warnings
from sklearn.datasets import load_breast_cancer, load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.ensemble import RandomForestClassifier, GradientBoostingRegressor
from sklearn.inspection import permutation_importance, partial_dependence
warnings.filterwarnings('ignore')
cancer = load_breast_cancer()
names = list(cancer.feature_names)
X_tr, X_te, y_tr, y_te = train_test_split(cancer.data, cancer.target, test_size=0.3, random_state=0, stratify=cancer.target)
logreg = make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000)).fit(X_tr, y_tr)
coef = logreg[-1].coef_[0]
order = np.argsort(-np.abs(coef))[:5]
print(f'test accuracy {logreg.score(X_te, y_te):.3f}; the five largest standardised coefficients (positive = benign):')
for j in order:
print(f' {names[j]:22s} {coef[j]:+.2f}')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:
tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X_tr, y_tr)
print(export_text(tree, feature_names=names))
print(f'test accuracy of this depth-2 tree: {tree.score(X_te, y_te):.3f}')|--- 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:
rng = np.random.default_rng(0)
Xn_tr = np.c_[X_tr, rng.normal(size=len(X_tr))]; Xn_te = np.c_[X_te, rng.normal(size=len(X_te))]
names_n = names + ['random noise']
forest = RandomForestClassifier(n_estimators=300, random_state=0).fit(Xn_tr, y_tr)
imp = forest.feature_importances_
o = np.argsort(-imp)
print(f'forest test accuracy {forest.score(Xn_te, y_te):.3f}')
for j in o[:5]:
print(f' {names_n[j]:22s} {imp[j]:.3f}')
print(f'random noise: {imp[-1]:.4f}, rank {list(o).index(30) + 1} of 31')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?
perm = permutation_importance(forest, Xn_te, y_te, n_repeats=20, random_state=0)
po = np.argsort(-perm.importances_mean)
for j in po[:5]:
print(f' {names_n[j]:22s} {perm.importances_mean[j]:.3f}')
print(f'random noise: {perm.importances_mean[-1]:.3f}') 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:
forest30 = RandomForestClassifier(n_estimators=300, random_state=0).fit(X_tr, y_tr)
base = forest30.score(X_te, y_te)
prng = np.random.default_rng(1)
def drop(cols, reps=20):
out = []
for _ in range(reps):
Z = X_te.copy(); Z[:, cols] = Z[prng.permutation(len(Z))][:, cols]
out.append(base - forest30.score(Z, y_te))
return np.mean(out)
size = [names.index(n) for n in ['mean radius', 'mean perimeter', 'mean area', 'worst radius', 'worst perimeter', 'worst area']]
print(f'accuracy {base:.3f}; drop when "worst radius" alone is shuffled: {drop([names.index("worst radius")]):.3f}; '
f'when all six size features are: {drop(size):.3f}')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 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:
diab = load_diabetes()
Xd, yd, dn = diab.data, diab.target, list(diab.feature_names)
gb = GradientBoostingRegressor(random_state=0).fit(Xd, yd)
for f in ['bmi', 's5', 'age']:
r = partial_dependence(gb, Xd, [dn.index(f)], grid_resolution=5)
print(f'{f:4s} at {np.round(r["grid_values"][0], 3).tolist()}: average prediction {np.round(r["average"][0], 1).tolist()}')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
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(12, 3.2), sharey=True)
for ax, f in zip(axes, ['bmi', 's5', 'age']):
r = partial_dependence(gb, Xd, [dn.index(f)], grid_resolution=40, kind='both')
for line in r['individual'][0][::15]:
ax.plot(r['grid_values'][0], line, color='C0', alpha=0.15)
ax.plot(r['grid_values'][0], r['average'][0], color='C1', lw=3)
ax.set_title(f); ax.set_xlabel('standardised value')
axes[0].set_ylabel('predicted progression'); plt.tight_layout(); plt.show()
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:
where is the model’s average prediction when the features in are fixed to this patient’s values and the others are drawn from a background sample. The shares add up exactly: average prediction this prediction.
With four features there are only subsets, so we can compute them exactly:
import itertools
from math import factorial
four = [dn.index(c) for c in ['bmi', 's5', 'bp', 'age']]
X4 = Xd[:, four]
gb4 = GradientBoostingRegressor(random_state=0).fit(X4, yd)
background = X4[rng.choice(len(X4), 100, replace=False)]
def value(S, x):
Z = background.copy()
Z[:, list(S)] = x[list(S)]
return gb4.predict(Z).mean()
def shapley(x):
n, phi = len(x), np.zeros(len(x))
for j in range(n):
others = [k for k in range(n) if k != j]
for r in range(n):
for S in itertools.combinations(others, r):
w = factorial(len(S)) * factorial(n - len(S) - 1) / factorial(n)
phi[j] += w * (value(S + (j,), x) - value(S, x))
return phi
i = int(np.argmax(yd)); x = X4[i]
phi = shapley(x); base_value = value((), x)
print(f'patient {i}: true progression {yd[i]:.0f}, prediction {gb4.predict(x[None])[0]:.1f}, average prediction {base_value:.1f}')
for name, ph in zip(['bmi', 's5', 'bp', 'age'], phi):
print(f' {name:4s} {ph:+7.1f}')
print(f' sum: {base_value:.1f} + {phi.sum():.1f} = {base_value + phi.sum():.1f}')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:
def perm_importance_scores(model, X, y, repeats=20, seed=0):
r = np.random.default_rng(seed); b = model.score(X, y); drops = np.zeros(X.shape[1])
for j in range(X.shape[1]):
for _ in range(repeats):
Xp = X.copy(); Xp[:, j] = r.permutation(Xp[:, j]); drops[j] += (b - model.score(Xp, y)) / repeats
return drops
top = np.argsort(perm_importance_scores(logreg, X_te, y_te))[::-1][:5]
p_benign = logreg.predict_proba(X_te)[:, 1]
malignant = np.where(logreg.predict(X_te) == 0)[0]
i = malignant[np.argmin(np.abs(p_benign[malignant] - 0.25))]
x0, best = X_te[i], None
for j in top:
for factor in sorted(np.linspace(0.2, 3, 281), key=lambda f: abs(f - 1)):
x = x0.copy(); x[j] = x0[j] * factor
if logreg.predict([x])[0] == 1:
if best is None or abs(factor - 1) < abs(best[1] - 1):
best = (j, factor)
break
j, factor = best
print(f'tumour {i}: P(benign) = {p_benign[i]:.2f}; "{names[j]}" from {x0[j]:.3g} to {x0[j] * factor:.3g} ({factor - 1:+.0%}) flips it to benign')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.
rng = np.random.default_rng(7)
n = 6000
group = rng.random(n) < 0.4 # True = group B
income = rng.normal(50, 15, n)
debt = rng.normal(20, 8, n)
history = rng.normal(np.where(group, 4, 7), 2, n) # years of credit history
repays = (0.05 * income - 0.08 * debt + 0.3 * history + rng.normal(0, 1, n)) > 2.2
past_decision = repays & ~(group & (rng.random(n) < 0.25)) # past approvals: 25% of good B applicants refused
features = np.column_stack([income, debt, history])
tr, te = np.arange(n) < 4000, np.arange(n) >= 4000
def group_report(approve, repays, group):
for name, g in [('A', ~group), ('B', group)]:
print(f' group {name}: approval rate {approve[g].mean():.2f} approved among those who would repay (TPR) {approve[g & repays].mean():.2f}')
print(f' demographic parity difference {approve[group].mean() - approve[~group].mean():+.2f} '
f'equal opportunity difference {approve[group & repays].mean() - approve[~group & repays].mean():+.2f}')
loan_model = make_pipeline(StandardScaler(), LogisticRegression()).fit(features[tr], past_decision[tr])
print('Trained on past decisions, group NOT used:')
group_report(loan_model.predict(features[te]), repays[te], group[te])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:
| Measure | Compares | Here |
|---|---|---|
| Demographic parity | the rate of positive decisions | 0.75 against 0.37 |
| Equal opportunity | the true positive rate among those who deserve a positive decision | 0.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:
fair_model = make_pipeline(StandardScaler(), LogisticRegression()).fit(features[tr], repays[tr])
print('Trained on true repayment:')
group_report(fair_model.predict(features[te]), repays[te], group[te])
p = loan_model.predict_proba(features[te])[:, 1]
gB, gA, rep = group[te], ~group[te], repays[te]
target = (p[gA & rep] >= 0.5).mean()
thr_B = np.quantile(p[gB & rep], 1 - target)
print(f'\nPast-decision model, group-specific threshold for B ({thr_B:.2f} instead of 0.50):')
group_report(np.where(gB, p >= thr_B, p >= 0.5), rep, gB)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¶
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?
Explain why impurity importance is computed on training data, and why that is a problem.
Two features are copies of each other. What happens to their permutation importances? What would you report instead?
Read the PDP of
ageabove. Can you conclude that age does not affect diabetes progression? Why not?Shapley values of a prediction are +30, −10 and +5; the average prediction is 100. What is the prediction?
Give a counterfactual explanation for a refused loan that is sparse and plausible, and one that is neither.
In the loan simulation, why does the model trained without the group attribute still treat the groups differently? Name both mechanisms.
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.