Sub topic 11
Individual and Counterfactual Fairness
This chapter assumes you know binary classification, the confusion matrix, train/test splits, and basic Python with NumPy and scikit-learn. You should also have read the earlier chapters on sensitive attributes and per-group rates.
Every metric so far compares groups. Demographic parity, equalized odds, and predictive parity all average over many people and then compare the averages. Group metrics can look fine while individual people are still treated inconsistently. This chapter covers two ideas that ask about individuals: individual fairness and counterfactual fairness.
Why group metrics are not enough
A group metric can be satisfied by a model that treats individuals arbitrarily. Suppose a lender wants equal selection rates for groups A and B. It could approve the strongest applicants in A and a random subset of B. The selection rates match, but within B, similar people get different decisions for no reason related to merit.
Individual-level criteria catch this kind of failure. They also catch a second problem: a model can pass a group check on the attributes you tested and still behave unevenly for people who differ only in an attribute you did not test.
The cost is that these criteria need more from you. You must define what "similar" means, or you must state a causal model of the world. Both are assumptions you must defend.
Individual fairness
Individual fairness comes from Dwork et al. (2012). Its principle is that similar individuals should receive similar outcomes.
Formally, you choose a task-specific similarity measure d(x, x') between people and a distance between outputs. The model f is individually fair if
|f(x) - f(x')| <= L * d(x, x')
for all pairs, where L is a constant. This is a Lipschitz condition. Two people who are close under d must get close scores.
The hard part is the metric
The formula is simple. The difficulty is d. Someone must decide which features make two people comparable for this task, and how much each matters. For a loan, income, repayment history, and debt load may count. Zip code probably should not, because it can act as a proxy for race.
That decision encodes values, so it needs domain experts and often the affected communities. If d is built from the same biased data as the model, the individual criterion inherits the bias. Two people can look "similar" under a metric that already hides the disadvantage one of them faced.
A practical consistency check
You rarely have a validated d. A common compromise is a nearest-neighbor consistency score. For each person, compare their prediction with the average prediction of their k nearest neighbors in a chosen feature space.
import numpy as np
from sklearn.neighbors import NearestNeighbors
def consistency(X, y_pred, k=5):
"""Mean agreement between each prediction and its k nearest neighbors.
X: 2D array of features used to define similarity (scaled, no sensitive columns).
y_pred: array of binary predictions.
Returns a value in [0, 1]. Higher means similar people get similar predictions.
"""
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)
neighbor_idx = idx[:, 1:] # drop each point itself
neighbor_mean = y_pred[neighbor_idx].mean(axis=1)
return 1.0 - np.abs(y_pred - neighbor_mean).mean()
rng = np.random.default_rng(0)
X = rng.normal(size=(500, 3))
smooth = (X[:, 0] + X[:, 1] > 0).astype(int) # depends smoothly on features
noisy = rng.integers(0, 2, size=500) # ignores features entirely
print("smooth model:", round(consistency(X, smooth), 3))
print("random model:", round(consistency(X, noisy), 3))The smooth model scores clearly higher than the random one. Treat the score as a diagnostic, not a certificate. It only says that people close in the features you picked get similar outputs. If those features are poorly chosen, a high score means little.
You can also compare consistency across groups. If neighbors in group B are treated less consistently than neighbors in group A, that is a finding worth recording.
Fairness through unawareness fails
A tempting shortcut is to drop the sensitive column and call the model fair. This is called fairness through unawareness. It rarely works, because other features correlate with the sensitive attribute. Zip code, school, and purchase history can all reveal group membership. The model can reconstruct the attribute and use it indirectly.
You can test this directly. Train a classifier to predict the sensitive attribute from the remaining features. If it succeeds well above chance, the features leak the attribute, and removing the column did not remove the information.
Counterfactual fairness
Counterfactual fairness, from Kusner et al. (2017), asks a causal question. Would this person's prediction have been the same if their sensitive attribute had been different, with everything that causally depends on it changing accordingly?
The definition: a predictor is counterfactually fair if, for an individual, the distribution of its output is the same in the actual world and in a counterfactual world where the sensitive attribute A took a different value. The comparison uses a causal model.
Why a causal model is required
Changing only the A column and re-scoring is not a counterfactual. In the real world, if A changed, other features would change too. A person's neighborhood, school, or occupation may depend on their group through history and discrimination. A counterfactual has to carry those downstream effects along.
This is where the structural causal model (SCM) comes in. An SCM is a set of equations saying how each variable is produced from its causes plus unobserved background factors U. To compute a counterfactual for one person you follow three steps, often called abduction, action, and prediction:
- Abduction: infer the person's background factors
Ufrom what you observed. - Action: set
Ato the other value. - Prediction: recompute the downstream features with the same
U, then score them.
A worked example
Take a toy model where a feature depends on the sensitive attribute plus individual noise:
z = 2 * a + u, with a in {0, 1} and u the person's background factor.
A person observed with a = 0 and z = 1.3 has u = 1.3. The counterfactual with a = 1 keeps u and gives z = 3.3. A predictor that uses z will score the counterfactual person differently, so it is not counterfactually fair. A predictor that uses only u will score both identically.
import numpy as np
rng = np.random.default_rng(1)
n = 2000
a = rng.integers(0, 2, size=n)
u = rng.normal(size=n)
z = 2.0 * a + u # feature caused by A and by background u
# Counterfactual features: abduct u, set A to the other value, recompute z.
u_hat = z - 2.0 * a # abduction (exact in this toy model)
a_cf = 1 - a # action
z_cf = 2.0 * a_cf + u_hat # prediction of the feature
def score_uses_z(z):
return 1 / (1 + np.exp(-z)) # depends on the descendant of A
def score_uses_u(z, a):
return 1 / (1 + np.exp(-(z - 2.0 * a))) # uses only the background residual
shift_z = np.abs(score_uses_z(z) - score_uses_z(z_cf)).mean()
shift_u = np.abs(score_uses_u(z, a) - score_uses_u(z_cf, a_cf)).mean()
print("mean score change under counterfactual, uses z:", round(shift_z, 3))
print("mean score change under counterfactual, uses u:", round(shift_u, 3))The first number is large and the second is zero. The second predictor is counterfactually fair in this model because it depends only on u, which does not change when A changes.
Design implication
Kusner et al. propose building predictors from features that are not descendants of A in the causal graph, or from the background factors U inferred for each person. That removes the dependence on A by construction. It can reduce accuracy if A-driven variation in features is genuinely predictive of the outcome.
Limits of counterfactual fairness
- The result is only as good as the causal graph. Different plausible graphs give different answers, and the data alone cannot always tell you which is right.
- Some attributes are hard to intervene on conceptually. What does it mean to change a person's race while holding everything else about their life fixed? Critics argue the question is ill-posed for some attributes.
- Fitting the SCM needs strong assumptions and often no testing is possible, because the counterfactual world is never observed.
Choosing among the three views
| View | Question it asks | Needs | Typical weakness |
|---|---|---|---|
| Group fairness | Do groups get equal rates? | Group labels, outcomes | Can hide unfair treatment of individuals |
| Individual fairness | Do similar people get similar outputs? | A similarity metric `d` | `d` encodes contested value judgments |
| Counterfactual fairness | Would the output change if `A` changed? | A causal model | Conclusions depend on untestable assumptions |
These do not replace group metrics. In an audit they serve as complements. Group metrics are easy to compute and communicate. Individual and counterfactual checks help you probe cases the group view cannot see, and they work best when you have a defensible similarity measure or a well-argued causal graph.
Common errors
- Flipping only the sensitive column and calling it a counterfactual test. This ignores causal descendants. It is still a useful quick probe, sometimes called a flip test, but it is not counterfactual fairness.
- Building the similarity measure from the model's own outputs or from features that already encode the bias.
- Reading a high consistency score as proof of fairness without checking which features defined similarity.
- Assuming that dropping the sensitive attribute satisfies either criterion.
- Treating a causal graph drawn on a whiteboard as established fact. Record it as an assumption.
Exercises
Exercise
A model drops the "race" column but still uses zip code, and zip code is strongly associated with race. Name one test that shows whether information about race remains, and explain which fairness view is most directly threatened.
Show answer
Train a classifier to predict race from the remaining features, including zip code. If it performs well above chance, the features leak race. Counterfactual fairness is most directly threatened, because zip code is plausibly a causal descendant of race, so changing race in a causal model would change zip code and therefore the prediction. Individual fairness is also at risk if zip code is used inside the similarity metric.
Exercise
In the toy model z = 2a + u, a person has a = 1 and z = 2.5. What is their counterfactual z if a were 0, and does a predictor that uses only z stay the same?
Show answer
Abduction gives u = z - 2a = 0.5. Setting a = 0 gives z_cf = 2*0 + 0.5 = 0.5. The predictor that uses only z sees 2.5 in the real world and 0.5 in the counterfactual world, so its score changes and it is not counterfactually fair in this model.