Sub topic 11
Individual and Counterfactual Fairness
This chapter assumes you can compute per-group rates (the previous chapters) and train a scikit-learn classifier. Group metrics compare averages across groups. Individual and counterfactual fairness ask a different question: is this particular person treated the way a similar person would be?
Individual fairness
Individual fairness says that similar individuals should receive similar predictions. It has two parts:
- A similarity metric that says which people are alike for the task. For a loan, this might use income, debt, and repayment history.
- A smoothness requirement: if two people are close under that metric, their scores must also be close.
The hard part is the metric. It encodes a value judgment about what counts as "similar", and it must not quietly rely on proxies for a sensitive attribute, such as postal code.
A simple audit is a consistency check. For each person, find their nearest neighbours on the task-relevant features and measure how much the model's predictions differ.
import numpy as np
from sklearn.neighbors import NearestNeighbors
def consistency(X, y_pred, k=5):
"""1.0 means every point gets the same prediction as its k nearest neighbours."""
X = np.asarray(X, dtype=float)
y_pred = np.asarray(y_pred, dtype=float)
nn = NearestNeighbors(n_neighbors=k + 1).fit(X)
_, idx = nn.kneighbors(X)
neighbours = idx[:, 1:] # drop the point itself
diffs = np.abs(y_pred[:, None] - y_pred[neighbours])
return 1.0 - diffs.mean()
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3))
y_pred = (X[:, 0] > 0).astype(int)
print(round(consistency(X, y_pred), 3))Choose the feature columns for X carefully. Scale them first, or one large-valued feature will dominate the distance.
Counterfactual fairness
Counterfactual fairness asks: would this person's prediction change if only their sensitive attribute were different, and everything causally downstream of it were adjusted accordingly? The question needs a causal model. It cannot be answered from the data alone.
In this graph the attribute reaches the prediction by two paths: a direct arrow and an indirect one through income. A model is counterfactually fair if flipping the attribute, while recomputing the descendants of that attribute, leaves the prediction distribution unchanged.
A simple flip test
A full counterfactual analysis needs a causal model. A cheap first probe is a flip test. You change only the sensitive column and compare predictions.
import numpy as np
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(1)
n = 1000
s = rng.integers(0, 2, n)
skill = rng.normal(size=n)
y = (skill + 0.8 * s + rng.normal(scale=0.5, size=n) > 0.4).astype(int)
X = np.column_stack([skill, s])
model = LogisticRegression().fit(X, y)
X_flip = X.copy()
X_flip[:, 1] = 1 - X_flip[:, 1]
changed = (model.predict(X) != model.predict(X_flip)).mean()
print(f"Predictions that change when only s is flipped: {changed:.1%}")A nonzero result shows the model uses the attribute directly. A zero result proves much less. The flip leaves other features unchanged, so proxies such as income still carry the signal. A real counterfactual would also change those features.
Choosing between approaches
| Approach | Needs | Main weakness |
|---|---|---|
| Group metrics | Group labels | Can hide unfairness to individuals within a group |
| Individual fairness | A similarity metric | The metric is a contested value choice |
| Counterfactual fairness | A causal graph | Conclusions depend on assumptions you cannot test from data |
Use these methods alongside group metrics. They also rely on assumptions you should record in the audit.
Exercise
A model never receives the sensitive attribute as an input, and a flip test changes 0% of predictions. Why can you still not conclude that it is counterfactually fair?
Show answer
The flip test changes only the sensitive column. Features that are causally downstream of the attribute, or correlated with it, stay fixed, so the model can still carry the attribute's effect through them. Counterfactual fairness requires recomputing those descendants under a causal model.