Sub topic 3
Sensitive attributes and defining groups
Every group fairness metric compares outcomes across groups, so you must decide which groups to compare before you compute anything. This chapter covers what counts as a sensitive attribute, how groups get defined and recorded, and what to do when the attribute is missing or unreliable. It assumes you know the confusion matrix, precision, recall, and false positive rate, and that you can use pandas and scikit-learn.
What a sensitive attribute is
A sensitive attribute is a characteristic of a person that you want to check your model for unequal treatment on. Common examples are race, ethnicity, sex, gender identity, age, disability, religion, and national origin. Many of these are protected by law in specific settings, such as hiring, lending, housing, and education. The legal list differs by country and by domain, so check the rules that apply to your deployment instead of assuming a universal list.
Two things are easy to confuse:
- Protected characteristic: a legal category. Whether it applies depends on jurisdiction and context.
- Sensitive attribute for an audit: any attribute you choose to slice results by. It can include legally protected categories, and it can also include things like region, language, income band, or device type, if you suspect they relate to harm.
The audit list should come from the harms you identified in the first chapter, not from a default checklist. A model that routes customer support tickets may matter most for language. A medical triage model may matter most for age, sex, and race.
Sensitive attributes versus proxies
Removing the sensitive column from the training data does not remove its influence. Other features can encode it. These are called proxies. Postal code can stand in for race in places with residential segregation. First name can stand in for sex or ethnicity. Years of continuous employment can stand in for sex if parental leave patterns differ.
This has a practical consequence for the audit: you need the sensitive attribute available at evaluation time even if the model never sees it as an input. Keeping it out of the features is a modeling choice. Keeping it out of the audit data makes the audit impossible.
import pandas as pd
df = pd.DataFrame({
"zip_code": ["10001", "10001", "60629", "60629", "60629", "10001"],
"race": ["A", "A", "B", "B", "B", "A"],
"label": [1, 0, 0, 1, 0, 1],
})
# How well does a supposedly neutral feature predict the group?
purity = (
df.groupby("zip_code")["race"]
.agg(lambda s: s.value_counts(normalize=True).max())
)
print(purity)In this toy data every zip code is a single group, so the purity is 1.0 for both. Real data is rarely this clean, but a high value tells you that dropping race would not hide it from the model.
Defining the groups
A group definition is a rule that assigns each row to a group. It looks simple, and it is where many audits go wrong. Decide the following before you compute metrics.
Granularity
Coarse categories hide differences. A single "Asian" category combines populations with very different outcomes in many datasets. Fine categories produce groups with few rows, which makes metrics noisy (a later chapter covers this). Pick the finest level that still gives each group enough examples, and record the choice.
Reference group
Many metrics are reported as a gap or a ratio against a reference group. The reference choice changes the numbers you report. Using the largest group is common because its estimates are the most stable. Using the group with the best outcome is common in some regulatory ratios. Another option is to report the largest gap between any two groups, which needs no reference. Name your choice in the report.
Binary versus multi-valued attributes
The code in this tutorial's earlier examples compares two groups, A and B. Real attributes often have more than two values. For a multi-valued attribute, compute the per-group rates for all values and then summarize with the maximum difference or the minimum-to-maximum ratio.
import numpy as np
def selection_rates(y_pred, group):
y_pred = np.asarray(y_pred)
group = np.asarray(group)
return {g: float(y_pred[group == g].mean()) for g in np.unique(group)}
y_pred = [1, 0, 1, 1, 0, 0, 1, 0, 0]
group = ["A", "A", "A", "B", "B", "B", "C", "C", "C"]
rates = selection_rates(y_pred, group)
print(rates)
max_gap = max(rates.values()) - min(rates.values())
ratio = min(rates.values()) / max(rates.values())
print(f"max gap: {max_gap:.3f}, min/max ratio: {ratio:.3f}")Group A has a selection rate of about 0.667, B has 0.333, and C has 0.333. The maximum gap is 0.333 and the ratio is 0.5.
Missing and unknown values
Rows with a missing attribute are a group of their own. Do not drop them silently. If 30% of rows lack the attribute, dropping them can change the result, and the missingness itself may correlate with outcomes. Keep an explicit "unknown" label and report its size.
Attributes that change over time
Age changes. Address changes. Gender identity or disability status can change or be disclosed later. Record when the attribute was measured, and compute it as of the decision date, not the audit date.
Where the attribute comes from
How the attribute was obtained affects how much you can trust the audit.
| Source | Strength | Weakness |
|---|---|---|
| Self-reported | Reflects how the person identifies | Often optional, so missing values may not be random |
| Collected by staff or an administrator | Complete coverage | Observer judgment may be wrong or biased |
| Inferred by a model | Available when nothing else is | Errors correlate with the groups being studied |
| Joined from external data (census, area statistics) | Easy to obtain | Describes the neighborhood, not the person |
Self-reported data is the best default. It is also the most sensitive to collect, so consent, purpose limitation, and access control matter. Many organizations keep the attribute in a separate store that only the audit process can read, and join it to predictions only at evaluation time.
Inferred attributes
When no direct data exists, some teams infer group membership, for example by combining surname and postal code. Treat these estimates with care.
- Inference errors are not uniform. They are usually larger for the groups that are already underrepresented.
- Gaps measured on inferred groups are biased, often toward zero, because misassigned people blur the groups together.
- Inference is itself a use of sensitive information and may need legal review.
If you must use inference, report it as an approximation, give the estimated accuracy of the inference, and prefer collecting real data going forward.
The diagram: from attribute to audit groups
Building a group column in practice
The following function creates a clean group column from a raw column. It maps missing values to "unknown", merges categories that are too small to analyze into "other", and reports what it did. The size threshold is a parameter, since the right value depends on how precise you need the estimates to be.
import pandas as pd
def build_groups(series, min_size=30, unknown_label="unknown", other_label="other"):
"""Return a cleaned group column and a log of the decisions made."""
s = series.astype("object").where(series.notna(), unknown_label)
counts = s.value_counts()
small = [g for g, n in counts.items() if n < min_size and g != unknown_label]
s = s.where(~s.isin(small), other_label)
log = {
"original_counts": counts.to_dict(),
"merged_into_other": small,
"final_counts": s.value_counts().to_dict(),
}
return s, log
raw = pd.Series(["A"] * 80 + ["B"] * 50 + ["C"] * 10 + [None] * 5 + ["D"] * 4)
groups, log = build_groups(raw, min_size=30)
print(log["merged_into_other"])
print(log["final_counts"])Here C and D fall below 30 rows and merge into other, which then has 14 rows. The five missing values stay as unknown. Merging small groups makes the numbers more stable, but it also hides the people in those groups. Write that trade-off in the audit record.
Common errors
- Auditing only the attributes the model uses. The model may not use
sex, yet it can still produce different outcomes by sex. - Using different group definitions in training and evaluation. If the audit groups are coded differently from the ones used to build the model, results are not comparable.
- Dropping rows with missing attributes. This can remove exactly the people most at risk of being overlooked.
- Treating group labels as fixed truths. They are measurements with error, and categories like race and gender are social constructs that vary by place and time.
- Ignoring context. The same attribute can matter very differently across deployments. A gap in age may be a harm in lending and an intended feature in a pediatric dosing model.
- Collecting the attribute with no plan for protecting it. Sensitive data raises privacy, security, and legal duties. Decide who can see it and how long it is kept.
Tension between privacy and measurement
You cannot measure unfairness for a group you do not record. Yet collecting sensitive data carries risk. Neither extreme works. Not collecting leaves harm invisible, and collecting without controls creates exposure. Common middle paths are voluntary self-reporting with clear purpose statements, storing the attribute apart from decision data, restricting access to the audit team, and reporting only aggregates with small-cell suppression.
Exercise
A lender removes the column race from its training data and says the model is therefore fair. A reviewer asks for a per-race audit, but the data team says they no longer have the column. Give two problems with this situation and one way to fix it.
Show answer
First, postal code, name, and similar features can act as proxies, so the model can still produce different outcomes by race. Removing the column does not prove fairness. Second, without the attribute at evaluation time no per-group rate can be computed, so the harm cannot be detected. A fix is to collect or retain the attribute (preferably self-reported, stored separately with restricted access) for audit use only, then compute selection rate, TPR, FPR, and precision per group. If direct data cannot be obtained, use an inferred attribute and report its estimated error.
Exercise
A dataset has these counts for an attribute: A = 500, B = 120, C = 18, missing = 40. You set minsize = 30. Using the buildgroups function, what are the final group counts, and what should you record in the audit log?
Show answer
C (18 rows) is below the threshold and merges into "other", giving other = 18. Missing values become "unknown" = 40, and A = 500 and B = 120 stay unchanged. The log should record the original counts, that C was merged and why, the threshold used, and the size of the unknown group, since the merge could hide a problem affecting C.