MLDay 48 of 50ML in Production
Fairness and Model Cards
A card issuer offers higher credit limits to clients its model trusts.
A card issuer offers higher credit limits to clients its model trusts. If one group gets the offer less often, someone will ask why. "The model decided" isn't an answer; a table of group results and a written account of the model's limits are.
The idea
A model can score well overall and still treat groups differently. To see it, split the test set by a sensitive attribute, a trait such as sex or age, and compute the same metric inside each group. These are group metrics. Two are common.
- Selection rate: the share of the group the model says yes to. Here, yes means "offer the increase", so it's the approval rate.
- Recall by group: of the people in the group who really repaid, the share approved. It's Day 13's recall, with "repaid" as the positive class.
Demographic parity asks for equal selection rates. Its gap, the demographic parity difference, is the largest selection rate minus the smallest. Equal recall is a different goal, and the two can disagree. Pick the one that matches the harm, and report both.
A model card is a one-page note that travels with the model. It says what the model is for, what data it saw, how it scores overall and by group, and what nobody has checked.
A tiny example
A bank's model reviews 50 applicants from each of two groups.
| Group | Applicants | Would repay | Approved | Approved and repaid |
|---|---|---|---|---|
| A | 50 | 40 | 30 | 28 |
| B | 50 | 30 | 21 | 21 |
- Approval rates: A is 30 ÷ 50 = 0.60, B is 21 ÷ 50 = 0.42. The gap is 0.18.
- Recall: A is 28 ÷ 40 = 0.70, B is 21 ÷ 30 = 0.70. No gap.
By approval rate, B looks short-changed. By recall, a good payer has the same 70% chance in either group. B simply has fewer good payers: 30, against A's 40.
The formula
| Symbol | Meaning |
|---|---|
| one group, such as "age 21–29" | |
| the selection rate of group : the share approved | |
| , | the largest and smallest value over all groups |
| DPD | the demographic parity difference; 0 means equal selection rates |
Worked, the tiny example: , or 18 percentage points.
Try it
Two groups, two thresholds
Each dot is a person with a model score; filled dots are truly positive (label 1), hollow dots truly negative (label 0). Everyone at or right of the dashed line is selected. Move the threshold and compare the two groups.
Group Aselected 60% (6 of 10)TPR 83.3%FPR 25%
Group Bselected 40% (4 of 10)TPR 75%FPR 16.7%
demographic-parity difference 0.2 (20 percentage points)
Selection rate: share of the group selected. TPR: of the truly positive, the share selected. FPR: of the truly negative, the share selected. Demographic-parity difference: the gap between the two selection rates.
Each score is the model's chance that the applicant repays; filled dots really repaid. TPR, the true-positive rate, is recall. At 0.5 for both, A is approved 60% and B 40%, a parity difference of 0.2. Lower the threshold for Group B to about 0.40, and the difference drops to 0. Now B's TPR is 100% against A's 83.3%, and B's FPR (defaulters approved) climbs from 16.7% to 33.3%.
In code
This rebuilds the D28 model on the Phase 3 split, and approves a client when the predicted default chance is below 0.5.
# script_id: day_048_fairness_and_model_cards/fairness
import os
from pathlib import Path
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.metrics import average_precision_score, roc_auc_score
from sklearn.model_selection import train_test_split
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "credit_default" / "default_of_credit_card_clients.csv")
df = df.drop(columns="ID").rename(columns={"default payment next month": "default"})
X, y = df.drop(columns="default"), df["default"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=42)
def clean(X):
X = X.copy()
X["EDUCATION"] = X["EDUCATION"].replace({0: 4, 5: 4, 6: 4}) # unknown codes -> 4, "others"
X["MARRIAGE"] = X["MARRIAGE"].replace({0: 3}) # unknown code -> 3, "others"
return X.astype(float)
model = HistGradientBoostingClassifier(random_state=42).fit(clean(X_train), y_train)
p_default = model.predict_proba(clean(X_test))[:, 1]
d = pd.DataFrame({
"repaid": y_test.values == 0,
"approved": p_default < 0.5, # offer the increase
"sex": "SEX = " + X_test["SEX"].astype(str).values,
"age": pd.cut(X_test["AGE"], [0, 29, 39, 100], labels=["age 21-29", "age 30-39", "age 40+"]).values,
})
print(f"test PR-AUC {average_precision_score(y_test, p_default):.3f}, approved {d['approved'].mean():.3f}")
test PR-AUC 0.551, approved 0.877
Now the group metrics, for SEX and for three age bands. The UCI codebook labels SEX 1 as male and 2 as
female; the file holds only the numbers, so the tables keep them.
# script_id: day_048_fairness_and_model_cards/fairness
def group_metrics(col):
t = d.groupby(col).agg(clients=("approved", "size"), repay_rate=("repaid", "mean"),
approval=("approved", "mean"))
t["recall"] = d[d["repaid"]].groupby(col)["approved"].mean() # approved, among those who repaid
print(t.round(3).to_string())
print(f"demographic parity difference: {t['approval'].max() - t['approval'].min():.3f}\n")
return t
table = pd.concat([group_metrics("sex"), group_metrics("age")])
clients repay_rate approval recall
sex
SEX = 1 2402 0.766 0.865 0.934
SEX = 2 3598 0.787 0.885 0.954
demographic parity difference: 0.020
clients repay_rate approval recall
age
age 21-29 1912 0.777 0.858 0.937
age 30-39 2198 0.794 0.899 0.957
age 40+ 1890 0.763 0.870 0.943
demographic parity difference: 0.040
By SEX, the approval gap (0.020) is about the same as the gap in who really repaid (0.787 against 0.766).
By age, the gap is between the two youngest bands: 30–39 is approved 0.899 of the time and 21–29 0.858, a
4-point gap, while their repay rates differ by under 2 points (0.794 against 0.777). The youngest band also has
the lowest recall. With about 2,000 clients per band, a gap of a point or so could be chance.
# script_id: day_048_fairness_and_model_cards/fairness
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True)
fig, ax = plt.subplots(figsize=(6, 4))
rows = range(len(table))
ax.scatter(table["approval"], rows, s=60, color="#2a78d6", label="approval rate", zorder=3)
ax.scatter(table["recall"], rows, s=60, color="#eb6834", marker="s", label="recall (repayers approved)", zorder=3)
ax.set(yticks=list(rows), yticklabels=table.index, xlim=(0.8, 1.0), xlabel="Share of the group (test set)",
title="Approval gaps: 2 points by SEX, 4 by age band")
ax.invert_yaxis()
ax.grid(axis="x", alpha=0.3)
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.18), ncol=2, frameon=False)
fig.tight_layout()
fig.savefig(FIG_DIR / "group_metrics.png", dpi=120)
plt.close(fig)

Last, the model card. The script fills it from the numbers above and saves it as MODEL_CARD.md, next to the script.
# script_id: day_048_fairness_and_model_cards/fairness
rows_md = "\n".join(f"| {g} | {r.clients:.0f} | {r.repay_rate:.3f} | {r.approval:.3f} | {r.recall:.3f} |"
for g, r in table.iterrows())
card = f"""# Model card: credit-limit offer model
- **Model:** HistGradientBoostingClassifier(random_state=42), defaults, {model.n_iter_} trees.
- **Use:** offer a credit-limit increase when the predicted default chance is below 0.5.
Not tested for other decisions, such as refusing credit.
- **Data:** UCI dataset 350, 30,000 card clients in Taiwan; 24,000 train, 6,000 test.
- **Inputs:** 23 columns, including SEX, AGE, EDUCATION and MARRIAGE.
- **Test results:** PR-AUC {average_precision_score(y_test, p_default):.3f}, ROC AUC {roc_auc_score(y_test, p_default):.3f}, {d['approved'].mean():.1%} approved.
| Group | Clients | Repay rate | Approval rate | Recall |
|---|---|---|---|---|
{rows_md}
- **Limits:** only SEX and age bands checked, not EDUCATION, MARRIAGE or combinations.
SEX codes 1 and 2 are labelled in the UCI codebook, not in the data. Threshold 0.5 not tuned to costs.
"""
Path(__file__).with_name("MODEL_CARD.md").write_text(card, encoding="utf-8")
print(card)
# Model card: credit-limit offer model
- **Model:** HistGradientBoostingClassifier(random_state=42), defaults, 65 trees.
- **Use:** offer a credit-limit increase when the predicted default chance is below 0.5.
Not tested for other decisions, such as refusing credit.
- **Data:** UCI dataset 350, 30,000 card clients in Taiwan; 24,000 train, 6,000 test.
- **Inputs:** 23 columns, including SEX, AGE, EDUCATION and MARRIAGE.
- **Test results:** PR-AUC 0.551, ROC AUC 0.781, 87.7% approved.
| Group | Clients | Repay rate | Approval rate | Recall |
|---|---|---|---|---|
| SEX = 1 | 2402 | 0.766 | 0.865 | 0.934 |
| SEX = 2 | 3598 | 0.787 | 0.885 | 0.954 |
| age 21-29 | 1912 | 0.777 | 0.858 | 0.937 |
| age 30-39 | 2198 | 0.794 | 0.899 | 0.957 |
| age 40+ | 1890 | 0.763 | 0.870 | 0.943 |
- **Limits:** only SEX and age bands checked, not EDUCATION, MARRIAGE or combinations.
SEX codes 1 and 2 are labelled in the UCI codebook, not in the data. Threshold 0.5 not tuned to costs.
Quick check
Quick check
1. A model approves 0.75 of one group and 0.60 of another. What is the demographic parity difference?
2. Two groups have different approval rates but equal recall. What does equal recall tell you?
3. What does a model card hold?
Next
Day 49 puts the pieces together and designs a whole ML system, from business goal to monitoring.
Data: Default of Credit Card Clients (UCI Machine Learning Repository, dataset 350), CC BY 4.0; cite Yeh, I.-C. and Lien, C.-H. (2009), "The comparisons of data mining techniques for the predictive accuracy of probability of default of credit card clients", Expert Systems with Applications 36(2).