Here is a credit risk model with a ROC AUC of 0.78 on six months of loans it has never seen. Its Brier score is 0.202. A “model” that predicts the same default rate for every applicant scores 0.109 on the same loans. So the model ranks borrowers well and still gives worse probabilities than a constant.
It is what you get from gradient boosting with class_weight="balanced", a common setting for imbalanced data. AUC only measures ranking, and a credit risk model is used for more than ranking: the predicted probability of default (PD) feeds the approval cutoff, the price, the expected loss estimate and the provisioning numbers. If the PD is off by a factor of 3.6, every one of those is off too.
This post builds a credit risk scoring model end to end and checks the things AUC does not see:
- Synthetic loan applications with a fixed seed and a known default process
- An out-of-time split instead of a random one
- A WoE-binned logistic regression scorecard as the baseline
- Gradient boosting, and the class_weight trap
- Probability calibration: Platt vs isotonic with CalibratedClassifierCV, reliability diagram, Brier score
- A cutoff chosen from expected loss (PD × LGD × EAD) instead of 0.5
- Stability monitoring with the Population Stability Index (PSI)
- Reason codes for declined applicants
- A basic fairness check on a synthetic protected attribute
Stack: Python 3.13, numpy 2.5.4, pandas 3.1.0, scikit-learn 1.9.1, pytest 9.2.0. Every number below is real output from one run of the code in this post (seed 7, about 13 seconds on 2 CPUs).
What each number in a credit risk model answers
A model can pass the first row and fail every other one. The Federal Reserve and OCC model risk guidance (SR 11-7) lists three core elements of validation: evaluation of conceptual soundness, ongoing monitoring and outcomes analysis. Calibration, PSI and out-of-time testing are how those elements look in code for a credit risk model.
Step 1. Synthetic applications with a known truth
A generator gives you what public datasets hide: the true default probability and control over drift. Every applicant gets an application month (0 to 23), seven features, a default flag drawn from a known logistic process, and a synthetic group attribute the model never sees.
"""Synthetic consumer-loan applications with a known data-generating process.
Every number in the article comes from this generator with SEED=7, so the
run is reproducible. `group` is a synthetic protected attribute: the model
never sees it, but it is correlated with income, which is how proxy
discrimination sneaks in.
"""
import numpy as np
import pandas as pd
SEED = 7
FEATURES = ["income", "dti", "utilization", "delinq_2y",
"history_months", "inquiries_6m", "loan_amount"]
def make_applications(n: int = 60_000, months: int = 24, seed: int = SEED) -> pd.DataFrame:
rng = np.random.default_rng(seed)
month = rng.integers(0, months, n)
# 0..1 over the period; later cohorts face a mild downturn
t = month / (months - 1)
group = rng.choice(["A", "B"], size=n, p=[0.7, 0.3])
income = rng.lognormal(mean=np.where(group == "A", 11.0, 10.85), sigma=0.45)
dti = np.clip(rng.normal(0.30 + 0.04 * t, 0.12), 0.0, 0.95)
utilization = np.clip(rng.beta(2, 3, n) + 0.06 * t, 0.0, 1.0)
delinq_2y = rng.poisson(0.25 + 0.10 * t)
history_months = np.clip(rng.gamma(4.0, 30.0, n), 3, 600).round()
inquiries_6m = rng.poisson(1.0 + 0.6 * t)
loan_amount = np.clip(rng.lognormal(9.3, 0.5, n), 1_000, 50_000).round(-2)
# True log-odds: non-linear in utilization (U-shape), saturating in history,
# plus an interaction gradient boosting can find and a scorecard cannot.
z = (-3.4
- 0.9 * (np.log(income) - 11.0)
+ 3.2 * dti
+ 2.6 * (utilization - 0.35) ** 2 * 4 - 0.35
+ 0.55 * np.minimum(delinq_2y, 4)
- 0.6 * np.log1p(history_months / 24)
+ 0.18 * inquiries_6m
+ 0.25 * np.log(loan_amount / 10_000)
+ 1.1 * (dti > 0.45) * (utilization > 0.7)
+ 0.35 * t) # macro drift the model cannot see
pd_true = 1 / (1 + np.exp(-z))
default = rng.binomial(1, pd_true)
return pd.DataFrame({
"month": month, "group": group,
"income": income.round(-2), "dti": dti.round(3),
"utilization": utilization.round(3), "delinq_2y": delinq_2y,
"history_months": history_months, "inquiries_6m": inquiries_6m,
"loan_amount": loan_amount, "default": default, "pd_true": pd_true,
})
def out_of_time_split(df: pd.DataFrame):
"""Train on the oldest 14 months, calibrate on the next 4, test on the last 6."""
train = df[df.month < 14]
calib = df[(df.month >= 14) & (df.month < 18)]
oot = df[df.month >= 18]
return train, calib, oot
Three details are deliberate. Utilization has a U-shaped effect, so a linear model on raw values would miss it. High DTI combined with high utilization adds risk on top of each feature alone, which trees can learn and a scorecard cannot. And the 0.35 * t term is a macro drift the model has no feature for, so later cohorts default more often for reasons outside the data.
train months 0-13 n= 34772 default_rate=0.086
calib months 14-17 n= 10033 default_rate=0.108
oot months 18-23 n= 15195 default_rate=0.123
The default rate rises from 8.6% in the training window to 12.3% in the out-of-time window, a 43% relative increase.
Timeline of 24 application months split into train, calibration and out-of-time windows, with the monthly default rate rising from about 7% to 13%
Step 2. Split by time, not at random
A random 70/30 split mixes old and new months into both sides, so the test set has the same default rate as the training set by construction. An out-of-time split trains on the past and tests on the future, which is how the model will be used.
with step("02_random_vs_oot"):
gbm_args = dict(max_iter=300, learning_rate=0.05, max_leaf_nodes=15,
l2_regularization=1.0, random_state=SEED)
Xa, Xb, ya, yb = train_test_split(df[FEATURES], df["default"], test_size=0.3,
random_state=SEED, stratify=df["default"])
rnd = HistGradientBoostingClassifier(**gbm_args).fit(Xa, ya)
gbm = HistGradientBoostingClassifier(**gbm_args).fit(Xtr, ytr)
p_rnd = rnd.predict_proba(Xb)[:, 1]
p_oot = gbm.predict_proba(Xoot)[:, 1]
print(f"random 70/30 split AUC={roc_auc_score(yb, p_rnd):.4f} "
f"mean PD={p_rnd.mean():.4f} vs observed {yb.mean():.4f}")
print(f"out-of-time split AUC={roc_auc_score(yoot, p_oot):.4f} "
f"mean PD={p_oot.mean():.4f} vs observed {yoot.mean():.4f}")
random 70/30 split AUC=0.7738 mean PD=0.0988 vs observed 0.0992
out-of-time split AUC=0.7803 mean PD=0.1055 vs observed 0.1227
AUC is slightly higher out of time (0.780 vs 0.774), so ranking alone says the model generalizes. The probabilities tell a different story: on the random split the mean predicted PD matches the observed default rate almost exactly (9.88% vs 9.92%), while out of time the model predicts 10.55% and the loans default at 12.27%. The random split hides the drift completely. This is the “outcomes analysis on a sample period not used in development” that SR 11-7 describes as back-testing, and it is why credit risk model validation should always include a time-based holdout.
Step 3. A WoE scorecard as the baseline
The classic credit scorecard bins each feature, replaces the bin with its Weight of Evidence (WoE), and fits a logistic regression on the WoE values:
WoE for a bin = ln(share of all goods in the bin / share of all bads in the bin). Positive WoE means safer than average.
Information Value (IV) = Σ (share of goods − share of bads) × WoE across bins. It ranks features by how much they separate goods from bads.
Binning handles non-linear effects, and the model stays additive, which makes reason codes possible later.
def woe_table(x: pd.Series, y: pd.Series, edges: np.ndarray) -> pd.DataFrame:
"""WoE = ln(%good / %bad) per bin; IV = sum((%good - %bad) * WoE)."""
b = pd.cut(x, edges, right=False)
t = pd.crosstab(b, y).reindex(columns=[0, 1], fill_value=0)
good, bad = t[0] + EPS, t[1] + EPS
pg, pb = good / good.sum(), bad / bad.sum()
out = pd.DataFrame({"n": t.sum(axis=1), "bad_rate": t[1] / t.sum(axis=1).clip(lower=1),
"woe": np.log(pg / pb)})
out["iv"] = (pg - pb) * out["woe"]
return out
The logistic regression output is then turned into points with the usual “points to double the odds” (PDO) scaling: score = offset + factor × ln(odds of good), with factor = PDO / ln 2. Here 600 points means 50:1 odds of being good, and every 20 points doubles the odds. Because the model is additive in WoE, each feature contributes its own number of points:
def points(self, X: pd.DataFrame) -> pd.DataFrame:
"""Per-feature points. WoE is ln(good/bad), so higher WoE => more points."""
w = self.transform(X)
n = len(self.features)
b0 = self.lr_.intercept_[0]
# model predicts P(bad): log-odds(bad) = b0 + sum(beta_i * woe_i)
# log-odds(good) = -b0 - sum(beta_i * woe_i)
pts = {f: -self.lr_.coef_[0][i] * w[f] * self.factor - b0 * self.factor / n + self.offset / n
for i, f in enumerate(self.features)}
return pd.DataFrame(pts, index=X.index)
Information value (train):
utilization 0.451
dti 0.145
income 0.112
delinq_2y 0.059
history_months 0.041
inquiries_6m 0.027
loan_amount 0.007
WoE bins for utilization:
n bad_rate woe iv
utilization
[-inf, 0.209) 5765 0.075 0.159 0.004
[0.209, 0.309) 5821 0.052 0.539 0.039
[0.309, 0.403) 5773 0.049 0.613 0.049
[0.403, 0.504) 5789 0.053 0.526 0.037
[0.504, 0.628) 5823 0.068 0.253 0.010
[0.628, inf) 5801 0.221 -1.100 0.313
score range on OOT: 462..626, median 563
The bins recover the U-shape: the safest utilization range is 0.31 to 0.40 (4.9% bad rate), very low utilization is slightly riskier (7.5%), and above 0.63 the bad rate jumps to 22.1%. One feature with IV 0.45 does most of the work, which is common in real portfolios too.
Step 4. Gradient boosting and the class_weight trap
This is where most credit scoring model machine learning tutorials stop: swap the scorecard for boosting and report a higher AUC. Here it is a HistGradientBoostingClassifier from scikit-learn, trained twice on the same data: once as is, once with class_weight="balanced". Per the scikit-learn docs, “balanced” weights each class by n_samples / (n_classes * np.bincount(y)), so with 8.6% defaults each default counts about 10 times as much as a repaid loan.
with step("04_models"):
gbm_bal = HistGradientBoostingClassifier(**gbm_args, class_weight="balanced").fit(Xtr, ytr)
raw = {"scorecard (WoE + LR)": sc.predict_proba(Xoot)[:, 1],
"GBM": gbm.predict_proba(Xoot)[:, 1],
"GBM class_weight=balanced": gbm_bal.predict_proba(Xoot)[:, 1]}
tab = pd.DataFrame({k: summary(yoot, v) for k, v in raw.items()}).T
print(tab[["auc", "brier", "log_loss", "ece", "mean_pd", "default_rate"]].to_string())
auc brier log_loss ece mean_pd default_rate
scorecard (WoE + LR) 0.7665 0.0944 0.3206 0.0204 0.1035 0.1227
GBM 0.7803 0.0883 0.3058 0.0177 0.1055 0.1227
GBM class_weight=balanced 0.7796 0.2019 0.5929 0.3204 0.4431 0.1227
Gradient boosting beats the scorecard by 0.014 AUC, mostly thanks to the DTI × utilization interaction. The balanced model ranks just as well (0.7796), but its average predicted PD is 44.3% on a portfolio that defaults at 12.3%. Reweighting classes changes the base rate the model learns, so the output is no longer a probability of default. Any downstream code that reads it as one (pricing, expected loss, a “PD < 12%” policy rule) will be badly wrong.
Step 5. Probability calibration: Platt vs isotonic
Calibration fits a monotone mapping from the model’s raw output to observed default frequencies, on data the model was not trained on. scikit-learn offers two classic methods in CalibratedClassifierCV:
method="sigmoid" is Platt scaling: a one-feature logistic regression on the model’s score. Two parameters, hard to overfit. The scikit-learn guide notes that it keeps the ranking because it is strictly monotonic.
method="isotonic" fits a free-form non-decreasing step function. More flexible, but the same guide warns it is “more prone to overfitting, especially on small datasets”, and suggests it pays off with more than about 1,000 calibration samples.
The model is already fitted, so it is wrapped in FrozenEstimator and calibrated on the four months between training and the out-of-time window. Train and calibration data must not overlap; scikit-learn leaves that check to you.
with step("05_calibration"):
preds = {"scorecard raw": sc.predict_proba(Xoot)[:, 1],
"GBM balanced raw": raw["GBM class_weight=balanced"]}
for method in ["sigmoid", "isotonic"]:
cal = CalibratedClassifierCV(FrozenEstimator(gbm_bal), method=method).fit(Xca, yca)
preds[f"GBM balanced + {method}"] = cal.predict_proba(Xoot)[:, 1]
calg = CalibratedClassifierCV(FrozenEstimator(gbm), method=method).fit(Xca, yca)
preds[f"GBM + {method}"] = calg.predict_proba(Xoot)[:, 1]
sc_cal = CalibratedClassifierCV(FrozenEstimator(sc.lr_), method="sigmoid").fit(sc.transform(Xca), yca)
preds["scorecard + sigmoid"] = sc_cal.predict_proba(sc.transform(Xoot))[:, 1]
tab = pd.DataFrame({k: summary(yoot, v) for k, v in preds.items()}).T
base = summary(yoot, np.full(len(yoot), ytr.mean()))["brier"]
tab["brier_skill"] = 1 - tab["brier"] / base
print(tab[["auc", "brier", "brier_skill", "log_loss", "ece", "mean_pd"]].to_string())
print(f"\nreference Brier (always predict train default rate): {base:.4f}")
results["reliability"] = {k: reliability(yoot, preds[k]).round(4).to_dict("list")
for k in ["GBM balanced raw", "GBM balanced + sigmoid",
"GBM balanced + isotonic", "scorecard raw"]}
results["calibration_table"] = tab.round(4).to_dict("index")
auc brier brier_skill log_loss ece mean_pd
scorecard raw 0.7665 0.0944 0.1332 0.3206 0.0204 0.1035
GBM balanced raw 0.7796 0.2019 -0.8534 0.5929 0.3204 0.4431
GBM balanced + sigmoid 0.7796 0.0882 0.1902 0.3058 0.0122 0.1136
GBM + sigmoid 0.7803 0.0877 0.1950 0.3043 0.0090 0.1140
GBM balanced + isotonic 0.7789 0.0884 0.1885 0.3122 0.0133 0.1136
GBM + isotonic 0.7794 0.0879 0.1933 0.3114 0.0106 0.1139
scorecard + sigmoid 0.7665 0.0937 0.1395 0.3187 0.0094 0.1144
reference Brier (always predict train default rate): 0.1089
How to read this table:
Brier score is the mean squared difference between predicted PD and the 0/1 outcome. Lower is better. On its own it mixes calibration and discrimination, so the scikit-learn guide warns that a lower Brier score does not necessarily mean a better calibrated model.
Brier skill compares the model with a constant forecast of the training default rate (Brier 0.1089). The balanced GBM has a skill of −0.85: worse than the constant. After Platt scaling it is +0.19.
ECE (expected calibration error) is the average gap between predicted and observed default rates across ten equal-size bins, the numeric version of a reliability diagram.
AUC does not move with sigmoid calibration. With isotonic it drops slightly (0.7796 to 0.7789) because the step function creates ties.
Reliability diagram on out-of-time loans: the class-balanced GBM sits far below the diagonal, Platt-calibrated GBM and scorecard follow it closely
Two findings. Isotonic did not beat sigmoid, even with 10,033 calibration rows (Brier 0.0884 vs 0.0882, log loss 0.3122 vs 0.3058): when the error is mostly a base-rate shift, two parameters are enough. And no calibrator fixes drift after the calibration window: every calibrated model predicts about 11.4% on average, while the out-of-time loans default at 12.3%.
Step 6. Choose the cutoff from expected loss, not 0.5
Expected loss for a loan is the product of three numbers:
PD, probability of default: the calibrated model output.
LGD, loss given default: the share of the exposure you lose if the borrower defaults, after recoveries. Here it is an assumption of 45% for an unsecured loan.
EAD, exposure at default: how much is owed when default happens. Here it is simply the loan amount.
The Basel framework uses the same decomposition for capital: EL = PD × LGD, and the EL amount is EL × EAD (CRE35.2 and CRE35.3). For an approval decision, compare expected loss with expected margin. If a repaid loan earns a net margin of 6% of EAD, approving is profitable when (1 − PD) × margin × EAD > PD × LGD × EAD, which gives a cutoff of PD < margin / (margin + LGD).
def pd_cutoff(lgd: float, margin: float) -> float:
"""Approve when expected profit > 0:
(1 - PD) * margin * EAD > PD * LGD * EAD => PD < margin / (margin + LGD)."""
return margin / (margin + lgd)
def portfolio_pnl(y, pd_hat, ead, lgd: float, margin: float, cutoff: float) -> dict:
"""Realized P&L of approving everyone with predicted PD below `cutoff`."""
y, pd_hat, ead = map(np.asarray, (y, pd_hat, ead))
ok = pd_hat < cutoff
gain = (1 - y[ok]) * margin * ead[ok]
loss = y[ok] * lgd * ead[ok]
return {"approval_rate": float(ok.mean()),
"bad_rate_approved": float(y[ok].mean()) if ok.any() else 0.0,
"expected_loss": float((pd_hat[ok] * lgd * ead[ok]).sum()),
"realized_loss": float(loss.sum()),
"profit": float(gain.sum() - loss.sum())}
LGD=0.45, margin=0.06 -> approve if PD < 0.1176
approval_rate bad_rate_approved expected_loss_$M realized_loss_$M profit_$M
GBM balanced raw @ 0.118 0.0122 0.0216 0.10 0.03 0.11
GBM balanced + sigmoid @ 0.118 0.7157 0.0601 3.19 3.75 3.75
GBM balanced + isotonic @ 0.118 0.7445 0.0635 3.51 4.10 3.68
scorecard raw @ 0.118 0.7222 0.0640 3.35 3.95 3.55
scorecard + sigmoid @ 0.118 0.6916 0.0600 3.17 3.52 3.69
GBM raw @ 0.500 0.9720 0.1056 7.56 9.17 0.53
GBM balanced raw @ 0.500 0.6478 0.0561 17.59 3.16 3.66
With LGD 0.45 and margin 0.06 the break-even PD is 11.76%. The same cutoff gives very different results depending on whether the PD is calibrated:
The balanced GBM at 0.1176 approves 1.2% of applicants, because almost every raw score is above 0.12. Profit is $0.11M.
The calibrated GBMs and the scorecard (raw logistic regression or Platt-scaled) at the same cutoff approve 69% to 74% of applicants and make $3.55M to $3.75M.
The unweighted GBM at the default 0.5 threshold approves 97.2% of applicants, including most of the risky ones, and makes $0.53M.
The balanced GBM at 0.5 makes $3.66M, because the weighting happens to inflate its scores by about the right factor. But its expected loss for the approved book is $17.59M against a realized $3.16M, so pricing or provisioning built on it is off by a factor of 5.6.
The calibrated GBM still underestimates losses ($3.19M expected vs $3.75M realized), which is the drift from Step 5 showing up in dollars.
Profit and approval rate on out-of-time loans for seven combinations of model and cutoff, calibrated models at the break-even cutoff earn the most
Step 7. Stability monitoring with PSI
The Population Stability Index compares the distribution of a variable in a baseline sample (training) with a recent sample, using bins cut on the baseline:
PSI = Σ (actual share − expected share) × ln(actual share / expected share)
def psi(expected, actual, n_bins: int = 10) -> float:
"""Population Stability Index with bins cut on the *expected* (baseline) sample."""
edges = np.unique(np.quantile(expected, np.linspace(0, 1, n_bins + 1)))
edges[0], edges[-1] = -np.inf, np.inf
e = np.histogram(expected, edges)[0] / len(expected)
a = np.histogram(actual, edges)[0] / len(actual)
e, a = np.clip(e, 1e-6, None), np.clip(a, 1e-6, None)
return float(np.sum((a - e) * np.log(a / e)))
score PSI train -> OOT: 0.0438
score PSI by month: {14: 0.03, 15: 0.014, 16: 0.031, 17: 0.035, 18: 0.022, 19: 0.034, 20: 0.053, 21: 0.039, 22: 0.074, 23: 0.069}
characteristic PSI train -> OOT:
inquiries_6m 0.0932
dti 0.0399
utilization 0.0308
delinq_2y 0.0093
loan_amount 0.0012
history_months 0.0009
income 0.0006
A widely used rule of thumb reads PSI below 0.10 as little shift and uses 0.10 and 0.25 as escalation thresholds. Yurdakul (2018) points out these cutoffs are used without reference to Type I or Type II error rates, so treat them as a convention, not a statistical test.
By that convention everything here is green: the score PSI is 0.044 and the worst month is 0.074. Yet the default rate rose 43% over the same period. PSI measures whether the applicants look different. It cannot see a change in how the same applicants behave, which is exactly the kind of macro drift built into the generator. The early warning that did fire is in the features: inquiries_6m has the highest characteristic PSI (0.093), because more credit-seeking is part of the same downturn. PSI is necessary, not sufficient. Monitor realized default rates by vintage alongside it.
Over months 14 to 23 the monthly score PSI stays below 0.10 while the monthly default rate rises from about 10% to 13.5%
Step 8. Reason codes for declined applicants
In the US, the Equal Credit Opportunity Act and Regulation B require a creditor that takes adverse action to give the applicant a statement of specific reasons. The official interpretation of 12 CFR 1002.9 says the reasons must relate to the factors actually scored, that no principal reason may be left out, and that “disclosure of more than four reasons is not likely to be helpful.” CFPB Circular 2022-03 adds that this applies equally to complex algorithms, including machine learning: a creditor cannot skip specific reasons because its model is hard to explain.
This is not legal advice, and production adverse action notices go through compliance review. The engineering takeaway is narrower: the reasons must come from the model that made the decision. If the scorecard declines the applicant, rank its features by the points lost compared with the best bin of each feature:
def reason_codes(self, X: pd.DataFrame, top: int = 4) -> list[list[str]]:
"""Rank features by points lost versus the best attainable bin."""
w = self.transform(X)
lost = {}
for i, f in enumerate(self.features):
slope = -self.lr_.coef_[0][i] * self.factor
best = (slope * self.tables_[f]["woe"]).max()
lost[f] = best - slope * w[f] # points below the best bin
lost = pd.DataFrame(lost, index=X.index)
reasons = []
for _, row in lost.iterrows():
r = row[row > 0.5].sort_values(ascending=False)
reasons.append(list(r.index[:top]))
return reasons
app 3: PD=0.389 score=507 reasons=['utilization', 'delinq_2y', 'history_months', 'inquiries_6m']
app 11: PD=0.184 score=534 reasons=['utilization', 'inquiries_6m', 'history_months', 'income']
app 17: PD=0.382 score=508 reasons=['utilization', 'dti', 'income', 'delinq_2y']
points for app 3
income 87.5
dti 84.3
utilization 46.0
delinq_2y 67.2
history_months 70.0
inquiries_6m 73.0
loan_amount 79.0
Applicant 3 got 46 points for utilization, the lowest of the seven features (the others range from 67 to 88), so utilization is the first reason, followed by recent delinquencies. The feature names still need a mapping to plain-language reasons (“Proportion of balances to credit limits is too high”), and the 0.5-point floor stops a feature that is already in its best bin from being listed.
If the gradient boosting model makes the decision, these scorecard reasons would not describe it. You would need per-applicant attributions from the GBM itself (SHAP values are the common choice), and you would have to check that they are stable and accurate. That extra work is a fair cost to put next to the 0.014 AUC gain from Step 4.
Step 9. A basic fairness check
The generator gives group B lower incomes on average, so any model that uses income will approve group B less often, even though the model never sees group. Regulation B lists race, color, religion, national origin, sex, marital status and age among the prohibited bases. For most non-mortgage credit, creditors generally may not ask about race, color, religion, national origin or sex (12 CFR 1002.5(b)), so real fair lending analysis often relies on proxies; the CFPB has published its proxy methodology. In a synthetic setup the attribute is known, which makes the code easy to test.
def fairness_report(df: pd.DataFrame, approved: np.ndarray, pd_hat: np.ndarray) -> pd.DataFrame:
d = df.assign(approved=approved, pd_hat=pd_hat)
g = d.groupby("group").agg(n=("default", "size"), approval_rate=("approved", "mean"),
default_rate=("default", "mean"), mean_pd=("pd_hat", "mean"))
g["bad_rate_approved"] = d[d.approved].groupby("group")["default"].mean()
g["air_vs_A"] = g["approval_rate"] / g.loc["A", "approval_rate"]
return g
scorecard + sigmoid
n approval_rate default_rate mean_pd bad_rate_approved air_vs_A
group
A 10691 0.7033 0.1206 0.1103 0.0616 1.0000
B 4504 0.6639 0.1277 0.1240 0.0562 0.9439
GBM balanced + sigmoid
n approval_rate default_rate mean_pd bad_rate_approved air_vs_A
group
A 10691 0.7291 0.1206 0.1103 0.0609 1.0000
B 4504 0.6838 0.1277 0.1214 0.0581 0.9379
Three readings:
Adverse impact ratio (approval rate of B / approval rate of A) is 0.944 for the scorecard and 0.938 for the GBM. The “four-fifths” threshold of 0.8 comes from the US employment selection guidelines (29 CFR 1607.4(D)), which also say smaller differences may still constitute adverse impact. In lending it is a screening heuristic, not a safe harbor.
Bad rate among approved is lower for group B (5.6% vs 6.2% for the scorecard). Approved B applicants are safer than approved A applicants, which hints the cutoff is effectively stricter for B.
Calibration by group explains why: both groups are underpredicted because of drift, but group A more so (11.0% predicted vs 12.1% observed) than group B (12.4% vs 12.8%).
None of this proves or disproves discrimination. It shows where to look: which features carry the group difference (income here) and whether a less discriminatory model with similar accuracy exists.
Tests that pin the claims down
The tests pin down the properties the article relies on:
import numpy as np
import pytest
from sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.frozen import FrozenEstimator
from sklearn.metrics import brier_score_loss, roc_auc_score
from credit.data import FEATURES, make_applications, out_of_time_split
from credit.metrics import pd_cutoff, psi
from credit.scorecard import WoEScorecard
@pytest.fixture(scope="module")
def split():
return out_of_time_split(make_applications(n=20_000))
def test_generator_is_reproducible():
a, b = make_applications(n=1000), make_applications(n=1000)
assert a.equals(b)
def test_psi_zero_for_same_sample_and_large_for_shift():
x = np.random.default_rng(0).normal(size=10_000)
assert psi(x, x) == pytest.approx(0.0, abs=1e-9)
assert psi(x, x + 0.5) > 0.1
def test_cutoff_is_break_even():
lgd, margin = 0.45, 0.06
p = pd_cutoff(lgd, margin)
assert (1 - p) * margin == pytest.approx(p * lgd)
def test_score_is_log_odds_of_good(split):
train, _, oot = split
sc = WoEScorecard(FEATURES).fit(train[FEATURES], train["default"])
p = sc.predict_proba(oot[FEATURES])[:, 1]
expected = sc.offset + sc.factor * np.log((1 - p) / p)
np.testing.assert_allclose(sc.score(oot[FEATURES]), expected, rtol=1e-9)
def test_reason_codes_at_most_four(split):
train, _, oot = split
sc = WoEScorecard(FEATURES).fit(train[FEATURES], train["default"])
reasons = sc.reason_codes(oot[FEATURES].head(200))
assert all(len(r) <= 4 for r in reasons)
assert all(set(r) <= set(FEATURES) for r in reasons)
@pytest.mark.parametrize("method", ["sigmoid", "isotonic"])
def test_calibration_fixes_balanced_gbm(split, method):
train, calib, oot = split
gbm = HistGradientBoostingClassifier(max_iter=100, class_weight="balanced",
random_state=0).fit(train[FEATURES], train["default"])
raw = gbm.predict_proba(oot[FEATURES])[:, 1]
cal = CalibratedClassifierCV(FrozenEstimator(gbm), method=method).fit(
calib[FEATURES], calib["default"])
p = cal.predict_proba(oot[FEATURES])[:, 1]
y = oot["default"]
assert brier_score_loss(y, p) < 0.6 * brier_score_loss(y, raw)
# calibration is a monotone map: ranking (AUC) barely moves
assert abs(roc_auc_score(y, p) - roc_auc_score(y, raw)) < 0.01
order = np.argsort(raw)
assert np.all(np.diff(p[order]) >= -1e-12)
7 passed in 6.13s
Gotchas
Resampling breaks probabilities too. SMOTE and undersampling change the base rate the same way class_weight="balanced" does. Calibrate on data with the real class mix.
No overlap checks. With FrozenEstimator, scikit-learn calibrates on everything you pass and does not check that it is disjoint from training data.
Old calibration data inherits old default rates. Even the most recent four months left a 0.9 percentage point gap here.
Small WoE bins are noisy. Smoothing prevents log(0), but merge small bins and check that WoE moves in a direction you can explain.
Credit risk model validation checklist
☐ Out-of-time holdout from a later period than training and calibration
☐ AUC and calibration metrics (Brier score, log loss, ECE, reliability diagram) on that holdout
☐ Mean predicted PD vs observed default rate, per vintage
☐ Cutoff derived from PD × LGD × EAD and the margin, with LGD and EAD assumptions written down
☐ PSI on the score and on every feature, plus realized default rate by vintage
☐ Up to four specific reasons per decline, generated from the model that made the decision
☐ Approval rate, bad rate and calibration per protected group (or proxy)
☐ Fixed seeds and pinned library versions, so the validation report can be reproduced
Wrap-up
AUC tells you whether a credit risk model can sort applicants. The rest of the decision, where to cut, how to price, how much to reserve and what to tell a declined applicant, depends on whether the probabilities are right and stay right. In this run, a model with the best AUC had the worst Brier score until a two-parameter Platt calibration fixed it, the default 0.5 threshold turned a $3.75M book into $0.53M, and PSI stayed green through a 43% rise in defaults.
What do you monitor in production besides PSI to catch behavior drift early: vintage curves, early delinquency rates, something else?





Top comments (0)