Skip to main content

Chapter 22 demo: Auditing an income classifier

Read Chapter 22 · Download notebook (.ipynb)

A model can predict historical labels reasonably well while making different mistakes for different groups. In this activity, we move from Chapter 22’s synthetic admissions example to historical Adult income data. Our aim is to interpret an audit and assess a proposed use of the model.

Allow 20–25 minutes: setup and prediction (3 minutes), Task 1 (7 minutes), Task 2 (6 minutes), and Task 3 with debrief (7 minutes). Run the folded setup cells before class; students can inspect them without spending class time rebuilding the pipeline.

Learning outcomes

By the end of the activity, you should be able to interpret group confusion matrices and fairness measures, explain why removing a sensitive feature does not establish fairness, and recommend a next action that matches the evidence.

The activity connects to Chapter 22’s sections on where bias enters the ML workflow, evaluating fairness across groups, and responding to ethical concerns. Read the chapter for the broader discussion of privacy, accountability, and responsible use.

Setup and data

Compare group metrics, examine removing a sensitive feature, and critique a proposed lending use.

Run cells in order with the repository’s Python environment selected as the kernel. From the repository root, start Jupyter with uv run --locked jupyter lab, then open book/demo-chapter-22-ethics.ipynb. Data paths work from either the repository root or book/. If using a downloaded notebook separately, place its required files in a data/ folder beside it.

Use data/adult.csv, included in the repository. Source: UCI Adult. Recorded income labels are not measures of creditworthiness or repayment.

Class route: Allow 20–25 minutes for the three guided tasks. Folded setup can be run before class; instructor discussions are expandable. Intersecting-group and threshold comparisons are optional.

Pause at prediction and discussion questions before revealing results. Rendered pages show saved outputs; controls that depend on a running Python kernel require Jupyter. General environment and download guidance is on the Demos page.

The data and the proposed decision

The UCI Adult dataset was extracted from the 1994 Census database. We use the local adult.csv already used in the book. Our prediction target is whether recorded annual income exceeds $50,000. These historical labels are not measures of merit, creditworthiness, or loan repayment. The threshold also refers to historical dollars, not current purchasing power.

The dataset’s sex field records only Female and Male. We use those recorded categories for an audit; they do not represent the full range of sex or gender identities. We will not infer the cause of a disparity merely from its presence.

We drop race from the predictors and retain it separately for possible additional audits. Our first model includes sex; our second excludes it while keeping it available for evaluation. Neither exclusion establishes fairness because related information can remain in other features.

We also drop fnlwgt, a sampling-weight field. All reported rates are unweighted comparisons within this sample, not estimates for the US population.

A company proposes using the predictions to approve loans: approve if predicted income is >50K, otherwise reject. Treat this as a proposal to critique, not a justified lending policy. We have income labels but no repayment outcomes.

Evaluation plan: fit once, inspect on validation data

We reserve 20% of the data as a test set. Of the remaining development data, we use 75% for fitting and 25% for validation, giving a 60/20/20 split overall. All activity comparisons use validation data. We leave the test set untouched because our discussion may lead to changes in features or decision rules.

Run the notebook from the book directory or repository root. No download is required if book/data/adult.csv is present.

Show imports, data loading, and splits
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from IPython.display import display
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import ConfusionMatrixDisplay, accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, OrdinalEncoder, StandardScaler

DATA_PATH = Path("data/adult.csv")
if not DATA_PATH.exists():
    DATA_PATH = Path("book/data/adult.csv")
if not DATA_PATH.exists():
    raise FileNotFoundError("Run from the book directory or repository root with adult.csv available.")

adult = pd.read_csv(DATA_PATH).replace("?", np.nan)
assert set(adult["income"]) == {"<=50K", ">50K"}
development, test = train_test_split(
    adult, test_size=0.2, random_state=42, stratify=adult["income"]
)
fit, valid = train_test_split(
    development, test_size=0.25, random_state=123,
    stratify=development["income"],
)
y_fit = fit["income"].eq(">50K").astype(int)
y_valid = valid["income"].eq(">50K").astype(int)
audit_valid = valid[["sex", "race"]].copy()
print(f"Fit: {len(fit):,}; validation: {len(valid):,}; reserved test: {len(test):,}")
Fit: 19,536; validation: 6,512; reserved test: 6,513

The preprocessing follows Chapters 11–12. The education order matches the dataset’s numerical education codes. An assertion checks that order, not just category membership.

We use class_weight="balanced" to change the relative training weight of the two income classes. It does not impose equal outcomes or error rates across demographic groups. We keep this choice fixed throughout the activity rather than search for a favourable fairness result.

Show preprocessing, baseline, and initial model
numeric_features = ["age", "capital.gain", "capital.loss", "hours.per.week"]
categorical_features = [
    "workclass", "marital.status", "occupation", "relationship", "native.country"
]
education_levels = [
    "Preschool", "1st-4th", "5th-6th", "7th-8th", "9th", "10th", "11th",
    "12th", "HS-grad", "Some-college", "Assoc-voc", "Assoc-acdm", "Bachelors",
    "Masters", "Prof-school", "Doctorate",
]
observed_order = (
    fit[["education", "education.num"]].drop_duplicates()
    .sort_values("education.num")["education"].tolist()
)
assert education_levels == observed_order

def make_income_model(include_sex):
    # Each call constructs fresh preprocessing and estimator objects.
    categories = categorical_features + (["sex"] if include_sex else [])
    preprocessor = ColumnTransformer([
        ("numeric", StandardScaler(), numeric_features),
        ("education", OrdinalEncoder(categories=[education_levels]), ["education"]),
        ("categorical", make_pipeline(
            SimpleImputer(strategy="constant", fill_value="missing"),
            OneHotEncoder(handle_unknown="ignore", sparse_output=False),
        ), categories),
    ], remainder="drop")
    return make_pipeline(
        preprocessor, LogisticRegression(class_weight="balanced", max_iter=2000)
    )

features_with_sex = numeric_features + ["education"] + categorical_features + ["sex"]
X_fit = fit[features_with_sex]
X_valid = valid[features_with_sex]

baseline = DummyClassifier(strategy="most_frequent").fit(X_fit, y_fit)
model_with_sex = make_income_model(include_sex=True).fit(X_fit, y_fit)
valid_predictions = pd.Series(model_with_sex.predict(X_valid), index=valid.index)

aggregate = pd.DataFrame({
    "model": ["Most-frequent baseline", "Logistic regression with sex"],
    "validation_accuracy": [
        accuracy_score(y_valid, baseline.predict(X_valid)),
        accuracy_score(y_valid, valid_predictions),
    ],
})
display(aggregate.round(3))
model validation_accuracy
0 Most-frequent baseline 0.759
1 Logistic regression with sex 0.812

Task 1: What does overall accuracy hide? (7 minutes)

Predict before revealing the next output. Does beating the baseline tell us whether recall will be similar for both recorded groups? Can one group have higher accuracy but lower recall for >50K?

The table below includes the denominators needed to interpret the rates. Here, a positive prediction means predicted income >50K, not an observed loan approval.

Quantity Definition Chapter 22 connection
Label prevalence Actual positives / group size Helps interpret the mix of recorded outcomes
Selection rate Predicted positives / group size Compare for statistical parity
Recall / TPR TP / (TP + FN) Compare for equal opportunity
FPR FP / (FP + TN) Compare for predictive equality
Precision TP / (TP + FP) Among positive predictions, how often is the income label positive?

The term selection rate becomes an approval rate only if someone actually uses positive predictions to grant approval. Equality against income labels would still not establish fairness in lending.

Show the group audit calculation
def group_audit(labels, predictions, groups):
    data = pd.DataFrame({"y": labels, "prediction": predictions, "group": groups})
    rows = []
    def rate(numerator, denominator):
        return numerator / denominator if denominator else np.nan
    for group, part in data.groupby("group", dropna=False):
        tn, fp, fn, tp = confusion_matrix(
            part["y"], part["prediction"], labels=[0, 1]
        ).ravel()
        rows.append({
            "group": group, "n": len(part),
            "TN": tn, "FP": fp, "FN": fn, "TP": tp,
            "prevalence": part["y"].mean(),
            "accuracy": (tn + tp) / len(part),
            "selection_rate": part["prediction"].mean(),
            "recall_TPR": rate(tp, tp + fn),
            "FPR": rate(fp, fp + tn),
            "precision": rate(tp, tp + fp),
        })
    return pd.DataFrame(rows).set_index("group")

with_sex_report = group_audit(y_valid, valid_predictions, audit_valid["sex"])
display(with_sex_report.round(3))
n TN FP FN TP prevalence accuracy selection_rate recall_TPR FPR precision
group
Female 2124 1741 143 58 182 0.113 0.905 0.153 0.758 0.076 0.560
Male 4388 2194 866 156 1172 0.303 0.767 0.464 0.883 0.283 0.575
Show count and normalized confusion-matrix plotting code
groups = ["Female", "Male"]
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
count_limit = int(with_sex_report[["TN", "FP", "FN", "TP"]].to_numpy().max())
for column, group in enumerate(groups):
    mask = audit_valid["sex"].eq(group)
    for row, normalization in enumerate([None, "true"]):
        ConfusionMatrixDisplay.from_predictions(
            y_valid[mask], valid_predictions[mask], labels=[0, 1],
            display_labels=["<=50K", ">50K"], normalize=normalization,
            ax=axes[row, column], colorbar=False,
            values_format="d" if normalization is None else ".2f",
            im_kw={"vmin": 0, "vmax": count_limit if normalization is None else 1},
        )
        axes[row, column].set_title(
            f"Recorded sex: {group} — "
            + ("counts" if normalization is None else "row proportions")
        )
fig.suptitle("Validation income predictions: identical colour scales within each row")
fig.tight_layout()
plt.show()

Discuss with a partner:

  1. Which group has higher accuracy? Which has higher recall for >50K? Support your answer with the table.
  2. Which parity criteria show disparities? Explain one comparison using its denominator.
  3. Among people recorded as earning >50K, how does the rate of positive predictions compare? Why does this not establish equal treatment of otherwise similar individuals?
  4. How could different label prevalences help explain different precision values? Can this table tell us why those prevalences differ?
Instructor notes: reveal after discussion

With the fixed split, the recorded Female group has accuracy about 0.905 versus 0.767 for Male, but recall about 0.758 versus 0.883. Overall logistic-regression accuracy is about 0.812, compared with 0.759 for the baseline. Use the executed results if software changes alter the last digits. Higher accuracy can coexist with lower recall because accuracy weights both classes according to their frequencies. Selection rates use everyone in a group; TPR uses actual positives; FPR uses actual negatives. Precision uses predicted positives and depends on prevalence as well as TPR and FPR. None of these comparisons identifies the cause of a disparity. The historical target, sampling process, and group categories limit the conclusions. Counts help assess whether rates are based on enough observations; even a large group difference does not by itself establish causation.

Task 2: Does removing sex fix the problem? (6 minutes)

Predict first. Will removing sex make the group selection rates and error rates equal? What other columns could carry related information?

We now fit a fresh pipeline with the same training rows and settings, excluding sex. We keep its recorded values separately for the audit. We do not refit the preprocessing of the already fitted first model.

features_without_sex = [name for name in features_with_sex if name != "sex"]
model_without_sex = make_income_model(include_sex=False).fit(
    fit[features_without_sex], y_fit
)
without_sex_predictions = pd.Series(
    model_without_sex.predict(valid[features_without_sex]), index=valid.index
)
without_sex_report = group_audit(
    y_valid, without_sex_predictions, audit_valid["sex"]
)
comparison = pd.concat(
    {"With sex": with_sex_report, "Without sex": without_sex_report},
    names=["model", "recorded_sex"],
)
display(comparison[[
    "n", "accuracy", "selection_rate", "recall_TPR", "FPR", "precision"
]].round(3))
n accuracy selection_rate recall_TPR FPR precision
model recorded_sex
With sex Female 2124 0.905 0.153 0.758 0.076 0.560
Male 4388 0.767 0.464 0.883 0.283 0.575
Without sex Female 2124 0.893 0.172 0.788 0.093 0.518
Male 4388 0.770 0.456 0.873 0.275 0.579

Discuss:

  1. Which rates changed, and which disparities remain? Does any improvement hold for every measure?
  2. What does this experiment show about removing a column? What does it not establish about causation or suitability for use?
  3. Why is retaining sex for an audit different from using it to determine a prediction? What privacy and access controls would an actual project need?
Instructor notes: reveal after discussion

Removing an explicit attribute does not remove all associated information: relationship, occupation, and other features may act as proxies. Compare the displayed values rather than promise that removal must improve or worsen a particular metric. This two-model experiment does not isolate the social causes of disparities or prove that a particular column caused discrimination. Both models predict historical income, and neither has been evaluated for repayment or the effects of lending decisions. Collecting sensitive attributes for evaluation also requires a justified purpose and appropriate safeguards.

We explored alternatives on validation data. If we choose a model or threshold using these comparisons, validation results remain development evidence; a final assessment needs the reserved test set after choices are fixed. This activity deliberately does not use that test set or declare a winner.

Task 3: Should this model decide who receives a loan? (7 minutes)

Return to the company’s proposal: approve a loan if predicted income is >50K and reject it otherwise.

A false positive here means predicted income above $50,000 when the recorded income is at most $50,000. It does not mean the person would default. Similarly, a false negative is an income-prediction error, not evidence that a rejected applicant would repay a loan. Even knowing someone’s actual income would not by itself establish repayment or a fair decision.

Discuss which assumptions the proposal adds beyond the prediction task. What would we need to know about the intended applicants, requested loans, repayment, and consequences of decisions? Would higher accuracy or equal error rates against these income labels answer those questions?

Write a three-sentence recommendation for the project lead:

  1. State one finding the audit supports, with the relevant comparison.
  2. State one consequential limitation it cannot resolve.
  3. Recommend a specific next action and identify who should be involved.

You may recommend further investigation, a revised process, or declining the proposed automation. Do not invent repayment results. Explain what an appeal process or human review would need to accomplish rather than assuming either automatically solves the problem.

Instructor debrief: reveal after recommendations

A defensible recommendation distinguishes income prediction from lending suitability. The existing evidence does not justify automatic approval or rejection. Useful next actions include clarifying the decision and harms with affected applicants and domain specialists, investigating whether appropriate outcome evidence can be obtained responsibly, and considering a process that does not use this proxy to exclude applicants. Human reviewers need evidence, time, authority, and accountability; an appeal process must permit corrections and reconsideration.

Connect back to Chapter 22: the choice of income as a proxy raises a measurement concern; historical income can reflect unequal opportunity; the sample and audit categories affect representation; validation on this dataset does not evaluate a future lending population. The table alone cannot establish the presence or cause of each kind of bias. Fairness measures support investigation rather than certify a decision process.

Optional extensions

Intersecting groups. Use the retained race field to examine intersections with recorded sex. Report counts of positives and negatives alongside rates, and identify estimates that are too poorly supported to interpret confidently. Treat the dataset’s historical categories critically. Avoid publishing sensitive results about very small groups in a real project.

Thresholds. On validation data, examine one alternative threshold for the model’s >50K score. Predict how selection, TPR, and FPR will change before calculating. Does a smaller gap in one measure settle the others? Do not describe these scores as calibrated probabilities without supporting evidence. Reserve the test set for a final assessment after all choices are fixed.

Take-away

An audit can reveal patterns hidden by aggregate performance. Its conclusions depend on the labels, population, group definitions, and decision being considered. Removing a sensitive feature or matching a single metric is insufficient to establish fairness. A responsible recommendation explains what the evidence supports and what must change before relying on the system.

Further context: Chapter 22, UCI Adult documentation, and Fairlearn’s fairness-assessment guide.