Sub topic 4
Measuring outcomes and errors per group
Every group fairness metric in this tutorial is built from a small set of per-group numbers. If you compute those numbers correctly, the metrics in later chapters reduce to simple subtraction. If you compute them carelessly, every later conclusion is wrong. This chapter covers the four rates, how to compute them, and where the computation goes wrong.
You are assumed to know the confusion matrix (TP, FP, TN, FN), precision, recall, false positive rate, train/test splits, and basic NumPy and pandas. You also need a chosen sensitive attribute for each row, as covered in the previous chapter.
Why overall accuracy is not enough
A model with 90% accuracy overall can have 95% accuracy for one group and 70% for another. The aggregate hides the difference because the larger group dominates the average. To see unequal treatment, you split the evaluation data by group and compute the same metrics inside each slice.
The split must happen on held-out data. Rates computed on training data reflect what the model memorized, not how it behaves on new people.
The four per-group rates
For each group, take the rows that belong to it and compute these four rates from the labels y_true and the binary predictions y_pred.
| Rate | Formula | Denominator | Question it answers |
|---|---|---|---|
| Selection rate | (TP + FP) / n | All people in the group | How often does the model give the favorable outcome? |
| True positive rate (TPR) | TP / (TP + FN) | People whose true label is positive | Of the people who deserve the favorable outcome, how many get it? |
| False positive rate (FPR) | FP / (FP + TN) | People whose true label is negative | Of the people who do not qualify, how many get it anyway? |
| Precision | TP / (TP + FP) | People the model selected | Of the people selected, how many were truly positive? |
The denominators are what matter. Selection rate conditions on nothing. TPR and FPR condition on the true label. Precision conditions on the prediction. Later chapters use this difference: demographic parity compares selection rates, equal opportunity and equalized odds compare TPR and FPR, and predictive parity compares precision.
A fifth number is worth recording even though it is not a model output. The base rate is the share of true positives in each group. If base rates differ, selection rates can differ even when the model is accurate for everyone. The chapter on incompatible criteria builds on this.
Computing the rates
The function below returns one dictionary of rates per group. It assumes binary labels and predictions coded as 0 and 1, where 1 is the favorable outcome.
import numpy as np
def group_rates(y_true, y_pred, group):
"""Per-group selection rate, TPR, FPR, and precision for binary labels."""
y_true = np.asarray(y_true)
y_pred = np.asarray(y_pred)
group = np.asarray(group)
out = {}
for g in np.unique(group):
m = group == g
yt, yp = y_true[m], y_pred[m]
out[g] = {
"n": int(m.sum()),
"selection_rate": yp.mean(),
"tpr": yp[yt == 1].mean() if (yt == 1).any() else float("nan"),
"fpr": yp[yt == 0].mean() if (yt == 0).any() else float("nan"),
"precision": yt[yp == 1].mean() if (yp == 1).any() else float("nan"),
}
return outThree details in this code are worth reading closely.
yp[yt == 1].mean()is the TPR. Among rows where the true label is 1, the mean of the predictions is the fraction predicted 1.yt[yp == 1].mean()is the precision. Among rows the model selected, the mean of the true labels is the fraction that were positive.- The
float("nan")guards cover groups with no positives, no negatives, or no selected rows. Without them, NumPy would return a warning and a NaN anyway, but the explicit guard makes the intent clear and avoids noisy warnings.
A worked example
Here are two groups of 10 people each. The data is small on purpose so you can verify the arithmetic by hand.
y_true = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0]
y_pred = [1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0]
group = ["A"] * 10 + ["B"] * 10
rates = group_rates(y_true, y_pred, group)
for g, r in rates.items():
print(g, {k: round(float(v), 3) for k, v in r.items()})The confusion matrices are as follows. Group A has TP = 3, FN = 1, FP = 1, TN = 5. Group B has TP = 1, FN = 2, FP = 2, TN = 5. The resulting rates are:
| Group | n | Base rate | Selection rate | TPR | FPR | Precision |
|---|---|---|---|---|---|---|
| A | 10 | 0.40 | 0.40 | 0.75 | 0.167 | 0.75 |
| B | 10 | 0.30 | 0.30 | 0.333 | 0.286 | 0.333 |
The selection rates differ by only 0.10. The TPRs differ by 0.417. A reviewer who looked only at how often each group is approved would see a small gap. A reviewer who looked at who is approved among qualified people would see that group B's qualified members are missed far more often. Different rates expose different problems, so compute all of them.
Turning the rates into one gap per criterion is a subtraction:
a, b = rates["A"], rates["B"]
demographic_parity_gap = abs(a["selection_rate"] - b["selection_rate"])
equal_opportunity_gap = abs(a["tpr"] - b["tpr"])
equalized_odds_gap = max(abs(a["tpr"] - b["tpr"]), abs(a["fpr"] - b["fpr"]))
predictive_parity_gap = abs(a["precision"] - b["precision"])On the example data these are 0.10, 0.417, 0.417, and 0.417. This code handles exactly two groups. With more groups, report the largest difference between any two groups, or compare each group with a chosen reference group.
How the pieces fit together
Edge cases and common errors
Undefined rates
A rate is undefined when its denominator is zero. A group with no true positives has no TPR. A group the model never selects has no precision. Report these as missing, not as 0. Treating a missing value as 0 creates a fake gap, and treating it as 1 hides a real one. When a rate is NaN, a gap computed from it is also NaN, so check for this before comparing groups.
Tiny denominators
A rate with a small denominator is noisy even when it is defined. In the example, group A's TPR rests on 4 people. Moving one prediction changes it by 0.25. The TPR and FPR use only a subset of each group, so they are usually less stable than the selection rate. The chapter on uncertainty shows how to attach confidence intervals. For now, always print n and the count behind each rate next to the rate itself.
Predictions that are not hard labels
The code above needs hard 0/1 predictions. If your model outputs probabilities, you must pick a threshold first, and the rates depend on that choice. A single global threshold can produce very different rates across groups. Record the threshold with the results. If the audit is about a score used for ranking, use calibration or score-distribution comparisons instead, covered later.
Label problems carry through
TPR, FPR, and precision all treat y_true as the truth. If the labels are themselves biased, for example arrest records standing in for crime, the per-group error rates inherit that bias. A low FPR against a flawed label does not prove fair treatment. State clearly what the label measures.
Group coding
np.unique treats "A", "a", and "A " as three groups. Clean the group column before computing anything. Also check that missing group values are handled explicitly. Dropping them silently changes the evaluated population, and who is missing is often itself a fairness finding.
Selection rate is not an error rate
Selection rate does not use y_true at all. It describes who gets the outcome, not whether the outcome was right. Do not describe a selection-rate gap as an "error" gap.
What to carry forward
- Split held-out data by group, then compute the same metrics in each slice.
- Selection rate, TPR, FPR, and precision answer different questions because they have different denominators.
- A gap in one rate can be small while a gap in another is large.
- Undefined rates and small denominators need explicit handling, not silent defaults.
The next chapters turn these rates into formal criteria, starting with demographic parity.
Exercise
A model is evaluated on two groups. In group C, 50 people have a true positive label and the model selects 30 of them. The model selects 10 more people in group C whose true label is negative, and group C has 100 people in total. Compute the selection rate, TPR, and precision for group C.
Show answer
Selected people = 30 + 10 = 40, so the selection rate is 40 / 100 = 0.40. TPR = 30 / 50 = 0.60. Precision = 30 / 40 = 0.75.
Exercise
Group D has no people with a true negative label in the evaluation set. What does group_rates return for its FPR, and why should you not replace that value with 0 before computing a gap?
Show answer
It returns NaN, because the FPR denominator (FP + TN) is zero. Replacing it with 0 would claim the model never wrongly selects group D members, which the data cannot show. That would create a false gap against any group with a real FPR. Report the rate as missing and collect more data, or exclude that rate from the comparison.