MLDay 47 of 50ML in Production
Detect Drift
The D28 credit model scored 0.781 ROC AUC on its test set.
The D28 credit model scored 0.781 ROC AUC on its test set. Then the bank cuts limits and customers fall behind, and the model keeps answering with no error at all. Whether a customer defaults shows up a month later, so by the time the labels prove the model wrong, it has scored a month of customers.
The idea
Drift means live data stops looking like the data the model learned from. It comes in two kinds:
- Data drift: the inputs change. Limits drop, customers get older, or a pipeline bug sends limits in a new currency. You can see this right away, with no labels.
- Concept drift: the link from inputs to the answer changes. Customers with the same profile default more often after a rate rise. Only fresh labels show this.
So you watch what you can see now. Compare each live batch, say a day of requests to the D46 API, with the training data. Check every input feature and the model's output scores too. Two numbers measure each gap:
- PSI (Population Stability Index) cuts the training values into bins with equal shares. Then it adds up how far each bin's share moved.
- KS (the Kolmogorov–Smirnov statistic) is the biggest gap between the two cumulative shares: the share of values at or below each point.
A common rule of thumb for PSI: under 0.1 is stable, 0.1 to 0.2 is worth watching, and 0.2 or more raises an alert. An alert starts an investigation, not an automatic retrain. Fix it if it's a bug. If the change is real and lasting, retrain on recent data once its labels arrive.
A tiny example
Cut the training customers' ages into 5 bands, each holding 20% of them. This month's batch is older:
| Age band | Training share | Batch share | |
|---|---|---|---|
| 27 or under | 0.20 | 0.10 | |
| 28–31 | 0.20 | 0.15 | |
| 32–36 | 0.20 | 0.20 | 0 |
| 37–42 | 0.20 | 0.20 | 0 |
| 43 or over | 0.20 | 0.35 |
The PSI is 0.069 + 0.014 + 0.084 ≈ 0.17: worth watching, but no alert yet. Each term is positive whichever way the share moved, so changes never cancel out.
The formula
| Symbol | Meaning |
|---|---|
| the number of bins, cut so each holds an equal share of the training values (often 10) | |
| the share of training values in bin | |
| the share of live values in bin | |
| the natural log |
Worked: one bin moving from 0.20 to 0.35 adds . An empty bin would make blow up, so it counts as a tiny share, here 0.0001 (0.01%).
| Symbol | Meaning |
|---|---|
| the cumulative share: the fraction of values at or below | |
| the largest value over every point |
Worked: in the tiny example, 40% of the training ages are 31 or under, but only 25% of the batch's. The gap there is 0.15. KS is the largest such gap anywhere.
Try it
Age the customer base
Grey bars: the reference (training-time) data. Coloured bars: live data, made by scaling and shifting the same values. Move the sliders and watch PSI and KS climb.
PSI 0.317KS 0.2biggest change: bin 1, 20% → 5%Drift alert: PSI ≥ 0.2
The dashed lines split the reference into 5 bins with equal shares. PSI = Σ (p − q) · ln(p / q) over those bins (p: reference share, q: live share); an empty bin counts as 0.01% so the log stays finite. KS is the biggest gap between the two cumulative distributions.
It opens on a batch 4 years older than 20 training ages: PSI 0.317, KS 0.2, and the alert is on. Drag shift to 3 and PSI falls to 0.135, below the line. Now push it to 5. The youngest bin empties and counts as 0.01%, so PSI leaps to 1.64, while KS only creeps to 0.25.
In code
First the D28 model, rebuilt on the same split, then a simulated downturn
batch. It takes the 6,000 test rows and, with a fixed seed, cuts every credit limit by a random 20–50%. One
customer in four also becomes at least a month late on the latest bill (PAY_0).
# script_id: day_047_drift_detection/drift_report
import os
from pathlib import Path
import numpy as np
import pandas as pd
from scipy.stats import ks_2samp
from sklearn.ensemble import HistGradientBoostingClassifier
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): # the D28 cleaning
X = X.copy()
X["EDUCATION"] = X["EDUCATION"].replace({0: 4, 5: 4, 6: 4})
X["MARRIAGE"] = X["MARRIAGE"].replace({0: 3})
return X.astype(float)
X_train, X_test = clean(X_train), clean(X_test)
model = HistGradientBoostingClassifier(random_state=42).fit(X_train, y_train)
rng = np.random.default_rng(42)
late = rng.random(len(X_test)) < 0.25 # one customer in four
batch = X_test.assign(
LIMIT_BAL=X_test["LIMIT_BAL"] * rng.uniform(0.5, 0.8, len(X_test)), # limits cut by 20-50%
PAY_0=np.where(late, np.maximum(X_test["PAY_0"], 0) + 1, X_test["PAY_0"]), # now 1+ month late
)
Now the drift report. It checks the untouched test rows too, to show how much drift there is when nothing has
changed. ks_2samp from SciPy returns the KS statistic.
# script_id: day_047_drift_detection/drift_report
def psi(ref, live, bins=10):
edges = np.percentile(ref, np.arange(1, bins) * 100 / bins) # 9 cuts: 10 bins of about equal share
p = np.bincount(np.searchsorted(edges, ref), minlength=bins) / len(ref)
q = np.bincount(np.searchsorted(edges, live), minlength=bins) / len(live)
p, q = np.maximum(p, 1e-4), np.maximum(q, 1e-4) # an empty bin counts as 0.01%
return float(np.sum((p - q) * np.log(p / q)))
ALERT = 0.2
ref_scores = model.predict_proba(X_train)[:, 1] # the model's chance of default
for name, live in [("test rows", X_test), ("shifted batch", batch)]:
feats = pd.DataFrame({c: [psi(X_train[c], live[c]), ks_2samp(X_train[c], live[c]).statistic]
for c in X_train}, index=["PSI", "KS"]).T.sort_values("PSI", ascending=False)
scores = model.predict_proba(live)[:, 1]
score_psi = psi(ref_scores, scores)
alerts = list(feats.index[feats["PSI"] >= ALERT]) + (["scores"] if score_psi >= ALERT else [])
print(f"--- {name}: mean score {scores.mean():.3f} (train {ref_scores.mean():.3f}), "
f"score PSI {score_psi:.3f}")
print(feats.head(3).round(3).to_string())
print("alerts:", alerts or "none")
print(f"AGE, test rows: KS p-value {ks_2samp(X_train['AGE'], X_test['AGE']).pvalue:.3f}")
--- test rows: mean score 0.221 (train 0.221), score PSI 0.001
PSI KS
AGE 0.003 0.022
BILL_AMT4 0.003 0.009
PAY_AMT5 0.002 0.011
alerts: none
--- shifted batch: mean score 0.253 (train 0.221), score PSI 0.117
PSI KS
LIMIT_BAL 0.277 0.220
PAY_0 0.212 0.195
AGE 0.003 0.022
alerts: ['LIMIT_BAL', 'PAY_0']
AGE, test rows: KS p-value 0.023
The untouched test rows stay near 0 everywhere. In the batch, both shifted features cross 0.2, and nothing else moves. The scores moved too: the model now expects more defaults, and its score PSI sits in the "worth watching" band. That says the predictions changed. Whether they're still right takes labels.
Quick check
Quick check
1. A bin holds 10% of the training rows and 10% of the live batch. What does it add to the PSI?
2. Every input looks just like the training data, but customers with the same profile now default twice as often. What catches it?
3. The score PSI is 0.117, and the mean score rose from 0.221 to 0.253. No labels have arrived. What do you know?
Next
The model's inputs can drift; its treatment of different groups can be unequal from day one. D48 measures that gap and writes it down in a model card.
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).