Chapter 12 — Lab: Explainability and Responsible AI
Lab Overview¶
You will write the main explanation methods yourself, for any model given as a function, and audit a model for fairness.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Permutation importance | 15 |
| 2 | Importance of a group of features | 10 |
| 3 | Partial dependence | 15 |
| 4 | Exact Shapley values | 25 |
| 5 | A one-feature counterfactual | 15 |
| 6 | Fairness gaps | 20 |
| Challenge | A threshold for equal opportunity | +10 |
How it works. Each exercise has a function to complete where you see # TODO. Run the check cell under it: ✅ means your function is right, ❌ tells you what is wrong. Models are given as plain functions, so your code works for any of them. Do not change the check cells.
import itertools
from math import factorial
import numpy as np
def check(name, test):
"""Run one self-check: test() must return True; any exception or False is reported."""
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
rng = np.random.default_rng(0)
X = rng.normal(size=(400, 3))
y = (2 * X[:, 0] + 0.5 * X[:, 1] > 0).astype(int) # feature 0 decides, feature 1 helps, feature 2 is noise
model = lambda Z: (2 * Z[:, 0] + 0.5 * Z[:, 1] > 0).astype(int) # a "model" that knows the rule
accuracy = lambda yt, yp: float(np.mean(yt == yp))
print('Setup complete.')Exercise 1: Permutation Importance (15 points)¶
perm_importance(predict, X, y, score, repeats=10, seed=0) returns one number per feature: the mean drop of score(y, predict(X)) when that feature’s column is shuffled, over repeats shuffles. Use rng = np.random.default_rng(seed) and rng.permutation.
def perm_importance(predict, X, y, score, repeats=10, seed=0):
# TODO
raise NotImplementedErrorimp = perm_importance(model, X, y, accuracy)
check('the deciding feature matters most', lambda: imp[0] > imp[1] > imp[2])
check('the noise feature does not matter at all', lambda: abs(imp[2]) < 1e-12)
check('the deciding feature costs about 0.4', lambda: 0.3 < imp[0] < 0.5)Exercise 2: A Group of Features (10 points)¶
group_importance(predict, X, y, score, cols, repeats=10, seed=0) shuffles the columns cols together (the same permutation of rows for all of them) and returns the mean drop.
def group_importance(predict, X, y, score, cols, repeats=10, seed=0):
# TODO
raise NotImplementedErrorXc = np.c_[X[:, 0], X[:, 0] + 1e-9 * rng.normal(size=400)] # two copies of the deciding feature
copy_model = lambda Z: (Z[:, 0] + Z[:, 1] > 0).astype(int)
yc = (X[:, 0] > 0).astype(int)
single = perm_importance(copy_model, Xc, yc, accuracy)
check('the two copies shuffled together matter more than either alone', lambda: group_importance(copy_model, Xc, yc, accuracy, [0, 1]) > max(single) + 0.1)Exercise 3: Partial Dependence (15 points)¶
pdp(predict, X, j, grid) returns, for each value v in grid, the average of predict(Z) where Z is X with column j set to v for every row.
def pdp(predict, X, j, grid):
# TODO
raise NotImplementedErrorlin = lambda Z: 3 * Z[:, 0] - Z[:, 1] + 10
g = np.array([-1.0, 0.0, 1.0])
check('a linear model gives a straight line of slope 3', lambda: np.allclose(np.diff(pdp(lin, X, 0, g)), [3, 3]))
check('the level includes the average of the other terms', lambda: abs(pdp(lin, X, 0, g)[1] - (10 - X[:, 1].mean())) < 1e-9)
check('the noise feature gives a flat line', lambda: np.allclose(pdp(lambda Z: model(Z).astype(float), X, 2, g), pdp(lambda Z: model(Z).astype(float), X, 2, g)[0]))Exercise 4: Exact Shapley Values (25 points)¶
shapley(value, n) takes a function value(S) giving the worth of any tuple of feature indices S (sorted), and returns the Shapley value of each of the n features:
Pass S and S ∪ {j} to value as sorted tuples.
def shapley(value, n):
# TODO
raise NotImplementedErroradditive = lambda S: sum({0: 4.0, 1: -1.0, 2: 2.5}[k] for k in S)
check('an additive game gives each feature its own value', lambda: np.allclose(shapley(additive, 3), [4, -1, 2.5]))
glove = lambda S: 1.0 if (0 in S and (1 in S or 2 in S)) else 0.0 # one left glove, two right gloves
check('the glove game: 2/3, 1/6, 1/6', lambda: np.allclose(shapley(glove, 3), [2 / 3, 1 / 6, 1 / 6]))
check('efficiency: the values add up to v(all) − v(none)', lambda: abs(shapley(glove, 3).sum() - (glove((0, 1, 2)) - glove(()))) < 1e-12)Exercise 5: A One-Feature Counterfactual (15 points)¶
counterfactual(predict, x, j, factors) multiplies feature j of the single example x by each factor in factors, trying the factors closest to 1 first, and returns the first factor that changes predict (applied to x[None]) from its original value; None if none does.
def counterfactual(predict, x, j, factors):
# TODO
raise NotImplementedErrorx1 = np.array([0.3, -0.2, 5.0]) # 2·0.3 − 0.1 = 0.5 > 0: class 1
fs = np.round(np.linspace(-1, 2, 61), 2)
check('feature 0 must shrink below 1/6 of its value: the factor 0.15', lambda: counterfactual(model, x1, 0, fs) == 0.15)
check('the noise feature never flips it', lambda: counterfactual(model, x1, 2, fs) is None)Exercise 6: Fairness Gaps (20 points)¶
fairness_gaps(approve, y, group) takes three boolean arrays (approved, deserves approval, member of group B) and returns (demographic parity difference, equal opportunity difference), both as B minus A: the difference in approval rates, and the difference in approval rates among those with y true.
def fairness_gaps(approve, y, group):
# TODO
raise NotImplementedErrorap = np.array([1, 1, 0, 1, 0, 0, 1, 0], bool); yy = np.array([1, 1, 0, 1, 1, 0, 1, 1], bool); gg = np.array([0, 0, 0, 0, 1, 1, 1, 1], bool)
check('the gaps of a small example', lambda: np.allclose(fairness_gaps(ap, yy, gg), [0.25 - 0.75, 1 / 3 - 1]))
check('equal treatment gives (0, 0)', lambda: np.allclose(fairness_gaps(np.array([1, 0, 1, 0], bool), np.array([1, 0, 1, 0], bool), np.array([0, 0, 1, 1], bool)), [0, 0]))Challenge: A Threshold for Equal Opportunity (+10 points)¶
equal_opportunity_threshold(p, y, group, t_a=0.5): group A keeps the threshold t_a. Return the threshold for group B that gives B the same true positive rate as A, as the (1 − TPR_A) quantile of the scores of B’s deserving members (np.quantile).
def equal_opportunity_threshold(p, y, group, t_a=0.5):
# TODO
raise NotImplementedErrorr = np.random.default_rng(3); gB = r.random(2000) < 0.5; yv = r.random(2000) < 0.6
pv = np.clip(0.5 + 0.25 * yv - 0.15 * gB + r.normal(0, 0.15, 2000), 0, 1)
t_b = equal_opportunity_threshold(pv, yv, gB)
check('B gets a lower threshold', lambda: t_b < 0.5)
check('and the two true positive rates match within 0.01', lambda: abs(np.mean(pv[gB & yv] >= t_b) - np.mean(pv[~gB & yv] >= 0.5)) < 0.01)Lab Report¶
Submit this notebook with:
every check cell showing ✅,
one paragraph: the challenge equalises true positive rates. Which other gap does it change, and in which direction? Would you use it for loans? For hiring?