Chapter 12: Explainability and Responsible AI — Implementation
Permutation importance by groups of features
Partial dependence in two dimensions: seeing an interaction
Shapley values for every feature, by sampling orders
From local to global: the mean absolute Shapley value
A counterfactual that may change two features
A fairness report, group by group
A model card
import numpy as np
import warnings
import itertools
import matplotlib.pyplot as plt
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.ensemble import RandomForestClassifier, GradientBoostingRegressor
from sklearn.inspection import permutation_importance, PartialDependenceDisplay
warnings.filterwarnings('ignore')
diab = load_diabetes()
Xd, yd, dn = diab.data, diab.target, list(diab.feature_names)
Xd_tr, Xd_te, yd_tr, yd_te = train_test_split(Xd, yd, test_size=0.3, random_state=0)
gb = GradientBoostingRegressor(random_state=0).fit(Xd_tr, yd_tr)
print(f'gradient boosting on diabetes: test R² {gb.score(Xd_te, yd_te):.3f}')gradient boosting on diabetes: test R² 0.281
1. Permutation Importance by Groups¶
The six blood-serum measures s1 to s6 of the diabetes data are correlated. We compare each one alone with the whole group, on the test set, as the drop in R².
rng = np.random.default_rng(0)
base = gb.score(Xd_te, yd_te)
def group_drop(cols, reps=30):
out = []
for _ in range(reps):
Z = Xd_te.copy(); Z[:, cols] = Z[rng.permutation(len(Z))][:, cols]
out.append(base - gb.score(Z, yd_te))
return float(np.mean(out))
serum = [dn.index(f's{k}') for k in range(1, 7)]
singles = {dn[j]: group_drop([j]) for j in serum}
print('each serum measure alone:', {k: round(v, 3) for k, v in singles.items()})
print(f'sum of the six single drops {sum(singles.values()):.3f}; the six shuffled together {group_drop(serum):.3f}')each serum measure alone: {'s1': -0.013, 's2': 0.01, 's3': -0.018, 's4': -0.001, 's5': 0.197, 's6': 0.012}
sum of the six single drops 0.186; the six shuffled together 0.286
s5 alone carries most of it, but the six shuffled together cost more than the sum of their single drops: the others share information with each other. Slightly negative drops mean shuffling happened to help a little: noise around zero.
2. Partial Dependence in Two Dimensions¶
A one-dimensional PDP averages over everything else. A two-dimensional PDP shows how two features act together; if the effect of one depends on the level of the other, they interact.
Source
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
PartialDependenceDisplay.from_estimator(gb, Xd_tr, [dn.index('bmi')], kind='both', subsample=60, random_state=0, ax=axes[0])
PartialDependenceDisplay.from_estimator(gb, Xd_tr, [(dn.index('bmi'), dn.index('s5'))], ax=axes[1])
axes[0].set_title('bmi: average and individual curves'); plt.tight_layout(); plt.show()
3. Shapley Values for Every Feature, by Sampling¶
With 10 features, the exact formula needs subsets per feature, each averaged over a background sample. A cheaper estimate samples random orders of the features: walk through each order, add the features one by one, and record how much each one changes the prediction. Averaged over many orders, these changes converge to the Shapley values, and they always add up exactly to (prediction − average prediction) for each order.
background = Xd_tr[rng.choice(len(Xd_tr), 50, replace=False)]
def sampled_shapley(model, x, background, n_orders=200, seed=0):
r = np.random.default_rng(seed)
d, phi = len(x), np.zeros(len(x))
for _ in range(n_orders):
order = r.permutation(d)
Z = background.copy()
prev = model.predict(Z).mean()
for j in order:
Z[:, j] = x[j]
cur = model.predict(Z).mean()
phi[j] += (cur - prev) / n_orders
prev = cur
return phi
i = int(np.argmax(gb.predict(Xd_te)))
x = Xd_te[i]
phi = sampled_shapley(gb, x, background)
avg = gb.predict(background).mean()
order = np.argsort(-np.abs(phi))
print(f'test patient {i}: prediction {gb.predict(x[None])[0]:.1f}, average {avg:.1f}, average + sum of shares {avg + phi.sum():.1f}')
for j in order[:5]:
print(f' {dn[j]:4s} {phi[j]:+7.1f}')test patient 118: prediction 367.0, average 162.9, average + sum of shares 367.0
bmi +99.4
s5 +49.9
bp +23.7
s2 +10.6
age +8.5
The library shap does this far faster for trees (TreeSHAP computes exact values in polynomial time), and adds the standard plots. The idea is the one above.
4. From Local to Global¶
Averaging the absolute Shapley values over many patients gives a global importance that is built from local explanations, and can be compared with permutation importance:
sample = Xd_te[:40]
mean_abs = np.mean([np.abs(sampled_shapley(gb, xx, background, n_orders=60, seed=k)) for k, xx in enumerate(sample)], axis=0)
perm = permutation_importance(gb, Xd_te, yd_te, n_repeats=20, random_state=0).importances_mean
print(f'{"feature":8s} {"mean |SHAP|":>12s} {"permutation":>12s}')
for j in np.argsort(-mean_abs)[:6]:
print(f'{dn[j]:8s} {mean_abs[j]:12.1f} {perm[j]:12.3f}')feature mean |SHAP| permutation
s5 27.2 0.221
bmi 25.4 0.181
bp 9.9 0.043
s3 7.2 -0.029
s2 6.3 -0.003
s6 5.3 0.017
Both put bmi and s5 on top. They measure different things (average push on the prediction, against loss of accuracy) and need not agree further down.
5. A Counterfactual That May Change Two Features¶
For a tumour the logistic regression calls malignant, we search the pairs of the five most important features, each scaled by a factor between 0.5 and 1.5, for the change that flips the decision with the smallest total relative change.
cancer = load_breast_cancer(); cn = list(cancer.feature_names)
Xc_tr, Xc_te, yc_tr, yc_te = train_test_split(cancer.data, cancer.target, test_size=0.3, stratify=cancer.target, random_state=0)
clf = make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000)).fit(Xc_tr, yc_tr)
top = np.argsort(-permutation_importance(clf, Xc_te, yc_te, n_repeats=20, random_state=0).importances_mean)[:5]
p_benign = clf.predict_proba(Xc_te)[:, 1]
mal = np.where(clf.predict(Xc_te) == 0)[0]
i = mal[np.argmin(np.abs(p_benign[mal] - 0.25))]
x0 = Xc_te[i]; factors = np.linspace(0.5, 1.5, 41); best = None
for a, b in itertools.combinations(top, 2):
for fa in factors:
for fb in factors:
x = x0.copy(); x[a] *= fa; x[b] *= fb
if clf.predict([x])[0] == 1:
size = abs(fa - 1) + abs(fb - 1)
if best is None or size < best[0]:
best = (size, a, fa, b, fb)
size, a, fa, b, fb = best
print(f'tumour {i} (P(benign) {p_benign[i]:.2f}): "{cn[a]}" {fa - 1:+.0%} and "{cn[b]}" {fb - 1:+.0%} flip it to benign (total change {size:.0%})')tumour 139 (P(benign) 0.24): "radius error" -25% and "mean concave points" -2% flip it to benign (total change 27%)
Here the pair is no improvement: its total change (27%) is about the single change of the chapter (26%, “radius error” alone); for other cases two small changes beat one large one, and only the search can tell. Real counterfactual tools add constraints: only features a person can act on, values that occur in the data, and a preference for few changes.
6. A Fairness Report¶
A function that reports, for each group, the size, the base rate, the approval rate, the true and false positive rates, and the precision: the numbers behind demographic parity, equal opportunity and predictive parity. The chapter’s simulated loans:
rng7 = np.random.default_rng(7)
n = 6000
group = rng7.random(n) < 0.4
income = rng7.normal(50, 15, n); debt = rng7.normal(20, 8, n)
history = rng7.normal(np.where(group, 4, 7), 2, n)
repays = (0.05 * income - 0.08 * debt + 0.3 * history + rng7.normal(0, 1, n)) > 2.2
past_decision = repays & ~(group & (rng7.random(n) < 0.25))
features = np.column_stack([income, debt, history])
tr, te = np.arange(n) < 4000, np.arange(n) >= 4000
loan = make_pipeline(StandardScaler(), LogisticRegression()).fit(features[tr], past_decision[tr])
def fairness_report(approve, y, group, names=('A', 'B')):
print(f'{"group":6s} {"n":>5s} {"base rate":>10s} {"approved":>9s} {"TPR":>6s} {"FPR":>6s} {"precision":>10s}')
for name, g in zip(names, [~group, group]):
tp = np.sum(approve & y & g); fp = np.sum(approve & ~y & g)
print(f'{name:6s} {g.sum():5d} {y[g].mean():10.2f} {approve[g].mean():9.2f} {tp / np.sum(y & g):6.2f} '
f'{fp / np.sum(~y & g):6.2f} {tp / max(np.sum(approve & g), 1):10.2f}')
fairness_report(loan.predict(features[te]), repays[te], group[te])group n base rate approved TPR FPR precision
A 1148 0.68 0.75 0.91 0.41 0.82
B 852 0.47 0.37 0.64 0.14 0.81
Group B repays less often on average (a lower base rate, from the shorter histories), is approved half as often, and its good applicants are approved less often (TPR). When base rates differ, equal TPRs, equal FPRs and equal precision cannot all be reached at once: the report shows the trade-off; people decide it.
7. A Model Card¶
A model card is a short document that travels with the model. For the loan model above:
| Section | Content |
|---|---|
| Purpose | rank loan applications for review by a credit officer; not for automatic refusal |
| Data | 4 000 simulated past applications (income, debt, credit-history length); past decisions as labels |
| Performance | accuracy and recall on 2 000 held-out applications, with the fairness report above |
| Known limits | trained on biased past decisions; credit history is a proxy for group membership; untested on applicants outside the income range 10–90 |
| Fairness | equal-opportunity difference −0.27 between groups; mitigation options and their costs (Section 12.8 of the chapter) |
| Oversight | every refusal reviewed by a person; monthly monitoring of approval rates by group |
| Contact and version | who maintains it; version, date, training code |
Summary¶
Permute correlated features as a group; single drops underestimate shared information.
Two-dimensional partial dependence reveals interactions that averages hide.
Sampling feature orders estimates Shapley values for any model; the shares always add up.
Mean absolute Shapley values give a global importance built from local explanations.
Counterfactual search can trade a few small changes against one large one.
A fairness report lays out base rates, approvals, TPR, FPR and precision per group.
A model card documents purpose, data, performance, limits, fairness and oversight.