Skip to main content

AI and machine learning · Advanced · 25 min

Check a classifier for unfair outcomes with Fairlearn

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · fairlearn 0.15.0 · scikit-learn 1.9.1 · pandas 3.1.1

You will measure how a loan-approval model treats women, men, rural and urban applicants with Fairlearn, see why dropping the sensitive columns leaves most of the gap in place, and compare two ThresholdOptimizer fixes against their cost in accuracy.

On this page

A lender wants a model to pre-screen loan applications so its officers spend time on the likely approvals. The training labels are the officers' own past decisions. If those decisions were harder on some applicants than their finances justify, a model trained on them learns to be harder on them too, and does it faster and at scale.

Fairlearn is an open-source Python library for measuring and reducing that kind of gap. In this tutorial you generate 20,000 past applications with a gap planted on purpose against women and rural applicants, train a model that never sees gender or region, and then find out how much of the gap it kept. You measure it per group with MetricFrame, sum it up in two standard numbers, trace where it leaks in through proxy features, and try two post-processing fixes to see what each one costs.

The data is synthetic with fixed seeds, so your numbers should match the ones shown. One thing no library settles for you: which fairness definition to aim for. You will see two of them pull in opposite directions, and the choice between them is a policy decision for the people accountable for the lending, not a setting for the engineer to pick alone.

Step 1 · Create the project and install the libraries

Make a throwaway folder and a virtual environment, then install pinned versions of Fairlearn, scikit-learn, pandas and NumPy:

Bash
mkdir -p ~/fairness-demo
cd ~/fairness-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet fairlearn==0.15.0 scikit-learn==1.9.1 pandas==3.1.1 numpy==2.5.5

Fairlearn also pulls in SciPy and narwhals. The download is roughly 75 MB; on prepaid mobile data, run it once on Wi-Fi. Nothing later needs a connection.

Check it worked

Bash
python -c "import fairlearn, sklearn, pandas, numpy; print(fairlearn.__version__, sklearn.__version__, pandas.__version__, numpy.__version__)"

The output is 0.15.0 1.9.1 3.1.1 2.5.5.

Step 2 · Generate loan applications with a planted gap

Each application has five financial features, two sensitive attributes and the past decision:

  • income: monthly income, in thousands of the local currency
  • debt_ratio: existing repayments as a share of income
  • years_employed: years in current work
  • part_time: 1 if the applicant works part time
  • branch_km: distance from the applicant's home to the nearest branch
  • gender and region: female or male, rural or urban
  • approved: 1 if the loan officer approved the application

Two facts are built in. Women are more likely to work part time, and rural applicants live much further from a branch, so both of those columns carry information about a sensitive attribute. And the officers' decisions include a penalty for being a woman and for being rural that has nothing to do with the applicant's finances. That penalty is the bias you are hunting.

Bash
cat > make_data.py <<'PY'
import numpy as np
import pandas as pd

rng = np.random.default_rng(11)
N = 20_000

gender = rng.choice(["female", "male"], size=N)
region = rng.choice(["urban", "rural"], size=N, p=[0.6, 0.4])
female = gender == "female"
rural = region == "rural"

income = rng.lognormal(mean=np.log(np.where(rural, 280, 350)), sigma=0.5).round(0)
debt_ratio = rng.beta(2, 5, size=N).round(3)
years_employed = rng.gamma(2.0, 3.0, size=N).round(1)
part_time = (rng.random(N) < np.where(female, 0.40, 0.12)).astype(int)
branch_km = np.where(rural, rng.gamma(4.0, 9.0, size=N), rng.gamma(1.5, 2.0, size=N)).round(1)

# Past officers' decisions: mostly the finances, plus a planted penalty
# for women and for rural applicants that has nothing to do with repayment.
score = (
    -1.2
    + 0.006 * income
    - 4.0 * debt_ratio
    + 0.08 * years_employed
    - 0.4 * part_time
    - 0.9 * female
    - 0.7 * rural
    + rng.logistic(size=N) * 0.8
)
approved = (score > 0).astype(int)

df = pd.DataFrame({
    "income": income, "debt_ratio": debt_ratio, "years_employed": years_employed,
    "part_time": part_time, "branch_km": branch_km,
    "gender": gender, "region": region, "approved": approved,
})
df.to_csv("loans.csv", index=False)
print(f"wrote {len(df)} applications, {df.approved.mean():.1%} approved")
print(df.groupby(["gender", "region"]).approved.agg(["count", "mean"]).round(3))
PY
python make_data.py

Every later script needs the same split, feature list and model, so keep them in one shared file. The split is stratified on the combined gender and region group so all four groups keep their share in the test set:

Bash
cat > common.py <<'PY'
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

FEATURES = ["income", "debt_ratio", "years_employed", "part_time", "branch_km"]


def load_split():
    df = pd.read_csv("loans.csv")
    df["group"] = df["gender"] + "/" + df["region"]
    train, test = train_test_split(df, test_size=0.3, stratify=df["group"], random_state=42)
    return train.reset_index(drop=True), test.reset_index(drop=True)


def make_model():
    return make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
PY

FEATURES leaves out gender and region on purpose. This is the most common first attempt at a fair model: do not show it the sensitive columns.

Check it worked

The script prints wrote 20000 applications, 37.9% approved and a table of approval rates. Women in rural areas were approved 0.166 of the time and men in urban areas 0.562, more than three times as often. Part of that is real: rural incomes in this data are lower. The rest is the planted penalty.

Step 3 · Train the model and see why accuracy hides the problem

Train a logistic regression on the five financial features and score it on the 6,000 test applications:

Bash
cat > baseline.py <<'PY'
from sklearn.metrics import accuracy_score

from common import FEATURES, load_split, make_model

train, test = load_split()
model = make_model().fit(train[FEATURES], train["approved"])
pred = model.predict(test[FEATURES])
accuracy = accuracy_score(test["approved"], pred)

print(f"features used: {FEATURES}")
print(f"test rows: {len(test)}")
print(f"accuracy: {accuracy:.3f}")
print(f"approval rate, past officers: {test['approved'].mean():.1%}  model: {pred.mean():.1%}")
assert accuracy > 0.75
PY
python baseline.py

Check it worked

You see accuracy: 0.774, and an approval rate of 30.5% against the officers' 37.5%. Nothing in this output says anything about who gets turned down. A single accuracy figure averages over everyone, so a model can be accurate overall and much worse for one group. The next step splits every number by group.

Step 4 · Break the metrics down by group with MetricFrame

MetricFrame takes any metric with the usual (y_true, y_pred) signature, plus a column of group labels, and computes the metric overall and for each group. Use four metrics that matter for lending:

  • Selection rate: the share of applicants the model approves.
  • False negative rate: of the applicants the officers approved, the share the model turns down. For a qualified applicant, this is the chance of being wrongly rejected.
  • Precision: of the applicants the model approves, the share the officers also approved.
  • Accuracy, for comparison.
Bash
cat > by_group.py <<'PY'
from functools import partial

from fairlearn.metrics import MetricFrame, count, false_negative_rate, selection_rate
from sklearn.metrics import accuracy_score, precision_score

from common import FEATURES, load_split, make_model

train, test = load_split()
model = make_model().fit(train[FEATURES], train["approved"])
pred = model.predict(test[FEATURES])

metrics = {
    "n": count,
    "selection_rate": selection_rate,
    "false_neg_rate": false_negative_rate,
    "precision": partial(precision_score, zero_division=0),
    "accuracy": accuracy_score,
}

for cols in (["gender"], ["region"], ["gender", "region"]):
    mf = MetricFrame(metrics=metrics, y_true=test["approved"], y_pred=pred, sensitive_features=test[cols])
    print(f"\nby {' and '.join(cols)}:")
    print(mf.by_group.round(3).to_string())
    print("largest gap between groups:")
    print(mf.difference().drop("n").round(3).to_string())

assert mf.difference()["selection_rate"] > 0.2
PY
python by_group.py

Passing a DataFrame with two columns, as in the last loop, gives one row per combination. That matters: a model can look fair by gender and fair by region and still treat one combination badly.

Check it worked

By gender alone the selection rate gap looks modest, 0.282 for women and 0.329 for men. By region it is 0.158 rural against 0.402 urban. The combined table is the one to read:

Text
                    n  selection_rate  false_neg_rate  precision  accuracy
gender region
female rural   1177.0           0.143           0.480      0.536     0.863
       urban   1820.0           0.371           0.307      0.675     0.768
male   rural   1208.0           0.174           0.581      0.786     0.773
       urban   1795.0           0.433           0.363      0.841     0.723

Rural women are approved 14% of the time against 43% for urban men, a gap of 0.291. Rural men have the highest false negative rate, 0.581: more than half of the rural men the officers approved, the model turns down. Notice too that accuracy is highest for rural women, 0.863. When a model says no to almost everyone in a group, and that group was mostly refused in the past, it agrees with the past and looks accurate. High accuracy for a group is not evidence of fair treatment.

Always read the n column. Here every group has over 1,000 test rows. With a few dozen, the gaps you see can be noise, so collect more data or merge groups before drawing conclusions.

Step 5 · Sum the gaps up as demographic parity and equalised odds

Two summary numbers come up in most fairness reviews, and Fairlearn computes both directly:

  • Demographic parity difference: the largest gap in selection rate between any two groups. 0 means every group is approved at the same rate. Its ratio form divides the lowest rate by the highest, so 1 is equal.
  • Equalised odds difference: the larger of two gaps, in true positive rate (qualified applicants approved) and in false positive rate (unqualified applicants approved). 0 means the model makes the same kinds of mistakes for every group.
Bash
cat > summary.py <<'PY'
from fairlearn.metrics import (
    demographic_parity_difference,
    demographic_parity_ratio,
    equalized_odds_difference,
)

from common import FEATURES, load_split, make_model

train, test = load_split()
model = make_model().fit(train[FEATURES], train["approved"])
pred = model.predict(test[FEATURES])
y = test["approved"]

print("                    dp_difference  dp_ratio  eo_difference")
for name, groups in [("gender", test["gender"]), ("region", test["region"]), ("gender x region", test["group"])]:
    dpd = demographic_parity_difference(y, pred, sensitive_features=groups)
    dpr = demographic_parity_ratio(y, pred, sensitive_features=groups)
    eod = equalized_odds_difference(y, pred, sensitive_features=groups)
    print(f"{name:<18} {dpd:>14.3f}  {dpr:>8.3f}  {eod:>13.3f}")

past = demographic_parity_difference(y, y, sensitive_features=test["group"])
model_gap = demographic_parity_difference(y, pred, sensitive_features=test["group"])
print(f"\npast officers, gender x region dp_difference: {past:.3f}")
assert 0.2 < model_gap < past
PY
python summary.py

The last lines pass the officers' decisions in as the predictions, which measures the gap in the labels themselves.

Check it worked

Text
                    dp_difference  dp_ratio  eo_difference
gender                      0.047     0.856          0.081
region                      0.244     0.394          0.209
gender x region             0.291     0.329          0.274

past officers, gender x region dp_difference: 0.425

The model's gap across the four groups is 0.291, smaller than the officers' 0.425 but far from zero. A demographic parity ratio of 0.329 means the least-approved group is approved at about a third of the rate of the most-approved one.

Equalised odds is measured against the labels, and here the labels are the biased past decisions. A model with an equalised odds difference of 0 would make mistakes evenly relative to those decisions, penalty included. Error-rate metrics are only as fair as the ground truth you score them against, so ask where your labels came from before you trust them.

Step 6 · Find the proxies that carry the bias back in

The model never saw gender or region, yet the region gap is almost as large as in the officers' decisions. Test how well the five features can predict the columns you removed, then see which features do the work:

Bash
cat > proxies.py <<'PY'
from fairlearn.metrics import demographic_parity_difference
from sklearn.metrics import roc_auc_score

from common import FEATURES, load_split, make_model

train, test = load_split()
is_female = lambda df: (df["gender"] == "female").astype(int)
is_rural = lambda df: (df["region"] == "rural").astype(int)

# 1. How well do the model's features predict the columns you dropped?
for name, target in [("gender", is_female), ("region", is_rural)]:
    clf = make_model().fit(train[FEATURES], target(train))
    auc = roc_auc_score(target(test), clf.predict_proba(test[FEATURES])[:, 1])
    print(f"predict {name} from the model's features: ROC AUC {auc:.3f}")

# 2. Which features carry them?
print("\ncorrelation with:   female  rural")
for col in FEATURES:
    print(f"  {col:<15} {train[col].corr(is_female(train)):>7.2f} {train[col].corr(is_rural(train)):>6.2f}")


# 3. Compare three feature sets on accuracy and the selection-rate gap.
def run(label, features, add_sensitive=False):
    X_train, X_test = train[features].copy(), test[features].copy()
    if add_sensitive:
        X_train["female"], X_test["female"] = is_female(train), is_female(test)
        X_train["rural"], X_test["rural"] = is_rural(train), is_rural(test)
    pred = make_model().fit(X_train, train["approved"]).predict(X_test)
    acc = (pred == test["approved"]).mean()
    gap = demographic_parity_difference(test["approved"], pred, sensitive_features=test["group"])
    print(f"  {label:<36} accuracy {acc:.3f}  dp_difference {gap:.3f}")
    return gap


print()
gap_with = run("with gender and region", FEATURES, add_sensitive=True)
gap_without = run("without them (the baseline)", FEATURES)
gap_no_proxy = run("without them, part_time or branch_km", ["income", "debt_ratio", "years_employed"])
assert gap_without > 0.5 * gap_with
assert gap_no_proxy > 0.1
PY
python proxies.py

Check it worked

Text
predict gender from the model's features: ROC AUC 0.653
predict region from the model's features: ROC AUC 0.998

correlation with:   female  rural
  income             0.00  -0.19
  debt_ratio        -0.01  -0.01
  years_employed     0.00   0.00
  part_time          0.31  -0.01
  branch_km         -0.01   0.81

  with gender and region               accuracy 0.785  dp_difference 0.492
  without them (the baseline)          accuracy 0.774  dp_difference 0.291
  without them, part_time or branch_km accuracy 0.759  dp_difference 0.176

An ROC AUC of 0.998 means the features identify rural applicants almost perfectly, through branch_km. Gender leaks less, through part_time. Dropping the sensitive columns cut the gap from 0.492 to 0.291, which is real progress, but about 60% of the gap the model could have learned is still there.

Removing the proxies as well brings the gap down to 0.176, and costs accuracy. What remains comes from income, which genuinely differs by region in this data. Whether a lower income in a poorer region should count against an applicant is a lending policy question, not a modelling one.

Real data has subtler proxies than a distance column: the phone model on a mobile-money account, the language an application was filled in, a postcode, the time of day someone applies. In markets where many applicants have thin credit files and lenders lean on such alternative data, run the same "predict the sensitive column" check on every candidate feature before you ship. You also need the sensitive columns kept aside to run any of these checks at all, so removing them from your data entirely makes the bias invisible rather than absent.

Step 7 · Try ThresholdOptimizer and see the trade-off

ThresholdOptimizer is one of Fairlearn's mitigation tools. It leaves the trained model alone and picks a separate decision threshold for each group so that a chosen fairness constraint holds on the training data, while keeping accuracy as high as it can. Fit it twice, once for demographic parity and once for equalised odds:

Bash
cat > mitigate.py <<'PY'
import pandas as pd
from fairlearn.metrics import MetricFrame, demographic_parity_difference, equalized_odds_difference, selection_rate
from fairlearn.postprocessing import ThresholdOptimizer
from sklearn.metrics import accuracy_score

from common import FEATURES, load_split, make_model

train, test = load_split()
y = test["approved"]
model = make_model().fit(train[FEATURES], train["approved"])

results = {"baseline": model.predict(test[FEATURES])}
for constraint in ["demographic_parity", "equalized_odds"]:
    opt = ThresholdOptimizer(
        estimator=model,
        constraints=constraint,
        objective="accuracy_score",
        predict_method="predict_proba",
        prefit=True,
    )
    opt.fit(train[FEATURES], train["approved"], sensitive_features=train["group"])
    results[constraint] = opt.predict(test[FEATURES], sensitive_features=test["group"], random_state=0)

scores = {}
print("model               accuracy  dp_difference  eo_difference")
for name, pred in results.items():
    acc = accuracy_score(y, pred)
    dpd = demographic_parity_difference(y, pred, sensitive_features=test["group"])
    eod = equalized_odds_difference(y, pred, sensitive_features=test["group"])
    scores[name] = (acc, dpd, eod)
    print(f"{name:<19} {acc:>8.3f}  {dpd:>13.3f}  {eod:>13.3f}")

print("\nselection rate by group:")
table = {name: MetricFrame(metrics=selection_rate, y_true=y, y_pred=pred,
                           sensitive_features=test["group"]).by_group for name, pred in results.items()}
print(pd.DataFrame(table).round(3).to_string())

base, dp, eo = scores["baseline"], scores["demographic_parity"], scores["equalized_odds"]
assert dp[1] < 0.1 and eo[2] < 0.05
assert dp[0] < base[0] and eo[0] < base[0]
assert dp[2] > 0.1 and eo[1] > 0.15
PY
python mitigate.py

prefit=True tells it the model is already trained. The group column is passed to both fit and predict: unlike the model, the optimiser needs to know each applicant's group to apply that group's threshold. random_state is there because, to hit a constraint exactly, it sometimes picks between two thresholds at random for applicants near the line, so the same application can get different answers on different calls.

Check it worked

Text
model               accuracy  dp_difference  eo_difference
baseline               0.774          0.291          0.274
demographic_parity     0.749          0.071          0.159
equalized_odds         0.761          0.207          0.027

selection rate by group:
              baseline  demographic_parity  equalized_odds
group
female/rural     0.143               0.254           0.173
female/urban     0.371               0.288           0.282
male/rural       0.174               0.281           0.257
male/urban       0.433               0.325           0.381

Each fix does what it was asked and gives up the other definition. The demographic parity version cuts the selection gap to 0.071 (not 0, since thresholds set on training data are applied to new data) but leaves an equalised odds gap of 0.159. The equalised odds version cuts that gap to 0.027 and leaves rural women approved at 0.173, barely above the baseline, because equalised odds aims at the officers' decisions and those decisions were harsh on rural women.

Look at urban men too. Under demographic parity their approval rate falls from 0.433 to 0.325. Part of the gap is closed by approving fewer people in the best-treated group, not only more in the worst-treated ones. Fairlearn's documentation calls this levelling down, and whether that is acceptable is, again, a policy call.

Both versions lose accuracy, 0.749 and 0.761 against 0.774. That accuracy is measured against biased labels, so some of the "lost" accuracy is the model refusing to repeat the officers' penalty.

Step 8 · Record the trade-off for the people who decide

When some groups have different base rates in the data, a classifier generally cannot have equal selection rates, equal error rates and equally reliable scores across groups all at once: this has been proved, not just observed. Someone has to choose which gap to close, how much accuracy to give up, and whether using the group at decision time, which ThresholdOptimizer requires, is lawful and acceptable where you lend. Using a protected characteristic in individual decisions is restricted in many jurisdictions, so involve your legal or compliance team before you deploy any group-specific threshold.

Your job is to put the evidence in front of them in a form they can read. Write the per-group numbers for the baseline and one fix to a CSV:

Bash
cat > report.py <<'PY'
from functools import partial

import pandas as pd
from fairlearn.metrics import MetricFrame, count, false_negative_rate, selection_rate
from fairlearn.postprocessing import ThresholdOptimizer
from sklearn.metrics import accuracy_score, precision_score

from common import FEATURES, load_split, make_model

train, test = load_split()
model = make_model().fit(train[FEATURES], train["approved"])
opt = ThresholdOptimizer(estimator=model, constraints="demographic_parity",
                         predict_method="predict_proba", prefit=True)
opt.fit(train[FEATURES], train["approved"], sensitive_features=train["group"])

metrics = {"n": count, "selection_rate": selection_rate, "false_neg_rate": false_negative_rate,
           "precision": partial(precision_score, zero_division=0), "accuracy": accuracy_score}
rows = []
for option, pred in [
    ("baseline", model.predict(test[FEATURES])),
    ("demographic_parity", opt.predict(test[FEATURES], sensitive_features=test["group"], random_state=0)),
]:
    mf = MetricFrame(metrics=metrics, y_true=test["approved"], y_pred=pred, sensitive_features=test["group"])
    table = mf.by_group.copy()
    table.loc["overall"] = mf.overall
    table.loc["largest gap"] = mf.difference()
    table.loc["largest gap", "n"] = None
    rows.append(table.assign(option=option))

report = pd.concat(rows).reset_index(names="group")[["option", "group", *metrics]]
report.round(3).to_csv("fairness_report.csv", index=False)
print(report.round(3).to_string(index=False))
assert len(report) == 12
PY
python report.py

Alongside the table, write down in plain words: where the labels came from and what is known about their bias, which fairness definition was chosen and why, who approved it, and what will be monitored after launch. That record belongs in the model card for this model.

Check it worked

The script prints 12 rows, six per option: the four groups, overall and largest gap. Check the file:

Bash
head -3 fairness_report.csv

The first line is the header option,group,n,selection_rate,false_neg_rate,precision,accuracy, followed by baseline,female/rural,1177.0,0.143,0.48,0.536,0.863. In the demographic_parity rows, rural women's precision drops to 0.381: many of the extra approvals are applicants the officers turned down. Some of those were refused because of the penalty and some for real financial reasons, and the CSV cannot tell you which. Before launch, have experienced officers review a sample of those newly approved applications by hand, so the decision rests on evidence about real applicants as well as on the metrics.

Step 9 · Clean up

Leave the virtual environment and delete the project folder:

Bash
deactivate
cd ~
rm -rf ~/fairness-demo
ls ~/fairness-demo 2>/dev/null || echo "removed"

Check it worked

The last command prints removed.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.