Learning path: Monitor and Improve a Model in Production · Step 2 of 8
Drift Detection in Code: PSI Bin by Bin, the KS Test, Evidently and a Measured Threshold
Six weeks of synthetic support tickets, one weekly drift alarm. Open up PSI bin by bin, check it with a KS test, let Evidently write the report, and measure what PSI looks like when nothing has shifted.
What you will learn
- Explain how PSI adds up a penalty per bin, and why an empty bin counts for a lot
- Run a KS test with scipy's ks_2samp and read its statistic and p value
- Build an Evidently drift report and spot a false alarm from its default line
- Measure the PSI you get with no shift, so your alert threshold is based on your own data
Before you start
- Monitoring Drift and Retraining
- Basic NumPy and pandas
Think about a thermometer in your fridge. The milk looks fine, and you can't tell anything by looking at the carton. But the thermometer is climbing a little every hour, and you can read that right now, no tasting needed.
That's drift detection. The tickets going into our ticket priority model are the milk. We read the inputs because those we can measure today, long before the true answers arrive. And a warm fridge doesn't prove the milk has gone off. It means go and check.
In Monitoring Drift and Retraining we used PSI and Evidently as a first check. Now we open PSI up, get a second opinion from a KS test, read Evidently's report with a critical eye, and measure a threshold instead of trusting a rule of thumb.
The alarm we want to open up
The project scores six weeks of synthetic tickets, 200 a week, against the 2,000 training tickets. From week 3 the generator sends more chat tickets, angrier customers and more evening tickets. 01_drift.py prints one row per week:
import pandas as pd
from monitor import CAT, DATA, NUM, fit_model, psi
from monitor import score_stream
model, X_test, y_test = fit_model()
ref = pd.read_csv(DATA / "tickets.csv")
stream = pd.read_csv(DATA / "stream.csv")
log = score_stream(model, stream)
log.to_csv(DATA / "predictions.csv", index=False)
ref_score = model.predict_proba(X_test)[:, 1]
print("week errors p95ms psiSent psiHour psiScore")
for week, g in log.groupby("week"):
s = stream[stream.week == week]
ps = psi(ref.sentiment, s.sentiment)
ph = psi(ref.hour, s.hour)
pc = psi(ref_score, g.score)
flag = "DRIFT" if max(ps, ph, pc) > 0.2 else ""
err = int((1 - g.ok).sum())
p95 = round(g.ms.quantile(.95))
print(week, err, p95,
round(ps, 2), round(ph, 2), round(pc, 2), flag)
week errors p95ms psiSent psiHour psiScore
1 0 31 0.03 0.06 0.04
2 0 25 0.03 0.06 0.07
3 0 21 1.56 0.33 0.23 DRIFT
4 0 26 1.03 0.4 0.24 DRIFT
5 0 20 0.98 0.29 0.2 DRIFT
6 0 17 1.25 0.43 0.18 DRIFT
Weeks 1 and 2 are quiet: sentiment PSI is about 0.03. Week 3 jumps to 1.56 and DRIFT shows up, and it stays for weeks 4 to 6. The errors column reads 0 every week, so the service itself would never have told you. (The p95ms column is the 95th percentile latency of that run.)
How PSI gets to 1.56
Here is psi from monitor.py, comparing training sentiment with week 3:
def psi(old, new, bins=10):
# Rule of thumb: PSI above 0.2 is a big shift
edges = np.quantile(old, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf
a = np.histogram(old, edges)[0] / len(old)
b = np.histogram(new, edges)[0] / len(new)
a, b = np.clip(a, 1e-4, None), np.clip(b, 1e-4, None)
return float(np.sum((b - a) * np.log(b / a)))
np.quantilecuts the training values into ten bins, so each bin holds about 10% of the training tickets. The two outer edges become −∞ and +∞ so every new value lands somewhere.np.histogramcounts where the new tickets land. In week 3, 42% land in the lowest bin, the angriest tickets.- The top bin, the happiest one, gets nobody. That's why
np.clipis there: it puts a tiny floor (0.0001) under an empty bin so the log doesn't blow up. - Every bin adds its own penalty,
(b - a) * log(b / a), and the sum rolls up to 1.56.
So a bin that empties out counts for a lot. PSI is a good alarm, but it isn't a ruler: a big number tells you something moved, not how much it matters.
A second opinion: the KS test
The KS test (Kolmogorov-Smirnov) doesn't use bins at all. In 04_ks_report.py it's one call, ks_2samp:
import numpy as np
import pandas as pd
from evidently import DataDefinition, Dataset, Report
from evidently.presets import DataDriftPreset
from scipy.stats import ks_2samp
from monitor import CAT, DATA, NUM, psi
ref = pd.read_csv(DATA / "tickets.csv")
stream = pd.read_csv(DATA / "stream.csv")
print("week ksSent pSent ksWords pWords")
for week, s in stream.groupby("week"):
a = ks_2samp(ref.sentiment, s.sentiment)
b = ks_2samp(ref.words, s.words)
print(week, round(a.statistic, 2),
f"{a.pvalue:.0e}", round(b.statistic, 2),
round(b.pvalue, 2))
week ksSent pSent ksWords pWords
1 0.06 5e-01 0.06 0.5
2 0.04 9e-01 0.06 0.45
3 0.42 2e-29 0.09 0.1
4 0.38 2e-24 0.09 0.09
5 0.4 1e-26 0.05 0.75
6 0.37 3e-22 0.04 0.92
Sort the tickets by sentiment and, at each value, ask what share sits below it. You get two curves climbing from 0 to 1, one for training and one for the week. The KS statistic is the widest gap between those curves. For week 3 the widest gap is at sentiment −0.04: 37% of training tickets sit below it, and 79% of week 3 tickets. So the gap is 0.42.
KS also gives a p value: how surprising a gap this wide would be if nothing had changed. For week 3 it prints 2e-29, a number so close to zero that this is not luck. But a p value only says a change exists. It doesn't say the change matters.
Does it stay quiet?
An alarm that always rings is useless. For sentiment, weeks 1 and 2 give 0.06 and 0.04 with p values of 0.5 and 0.9: calm. Weeks 3 to 6 sit near 0.4 and the p values fall to almost nothing.
Now look at words, the length of the ticket. The generator never shifted that column. Its KS number stays under 0.1 and its lowest p value is 0.09. So PSI and KS agree on sentiment, and KS stays quiet on a column that didn't change.
Evidently writes the report
You don't want to write all this for every column. Evidently does it in a few lines. DataDefinition tells it which columns are numbers and which are categories:
data = DataDefinition(numerical_columns=NUM,
categorical_columns=CAT)
old = Dataset.from_pandas(ref[CAT + NUM],
data_definition=data)
week3 = stream[stream.week == 3][CAT + NUM]
new = Dataset.from_pandas(week3, data_definition=data)
result = Report([DataDriftPreset()]).run(new, old)
result.save_html("drift_week3.html")
rows = result.dict()["metrics"]
print("columns flagged:", int(rows[0]["value"]["count"]),
"of", len(rows) - 1)
for m in rows[1:]:
col = m["metric_name"].split("=")[1].split(",")[0]
flag = "DRIFT" if m["value"] > 0.1 else ""
print(f"{col:<17}{m['value']:.2f} {flag}")
columns flagged: 4 of 8
words 0.19 DRIFT
has_attachment 0.03
previous_tickets 0.08
hour 0.50 DRIFT
sentiment 1.06 DRIFT
channel 0.24 DRIFT
customer_tier 0.05
product_area 0.06
drift_week3.html is one page you can hand to a teammate. Evidently picks its own measure for each column, with a line at 0.1 in this script, so these scores are not on the PSI scale.
Four of eight columns get flagged. Sentiment, hour and channel are the three the generator did shift. The fourth is words at 0.19, the column nobody touched, the one KS just called quiet. So a default line can raise a false alarm. The report tells you where to look, and you still decide.
What line should you alert on?
0.2 for PSI is a rule of thumb, so treat it as illustrative until you've measured your own. Here's one way to measure it: take 200 tickets at random from training itself, where nothing has shifted, and compute PSI. Do that 1,000 times.
# How high does PSI go when nothing has shifted?
rnd = np.random.default_rng(19)
calm = [psi(ref.sentiment,
rnd.choice(ref.sentiment, 200, replace=False))
for _ in range(1000)]
print("PSI, no shift, 200 tickets, 1000 draws")
print("median", round(np.median(calm), 3),
"p99", round(np.quantile(calm, 0.99), 3))
PSI, no shift, 200 tickets, 1000 draws
median 0.039 p99 0.101
The middle value is about 0.04, and 99% of the draws stay under about 0.1. That's the noise you get from one week of 200 tickets.
Quiet weeks sit at 0.03, week 3 at 1.56, and 0.2 is well above the noise for this data. With a different weekly volume the noise changes, so measure it again.
And an alarm still isn't a verdict. Once the true answers arrived, accuracy hadn't fallen: 0.602 for weeks 1-2 and 0.625 for weeks 3-6. Drift says go and look. How to wait for those answers is the subject of When Labels Arrive Weeks Late.
Common mistakes
- Reading PSI as a size of harm. One empty bin can push it way up. It's an alarm, not a ruler.
- Treating a tiny p value as "this matters". The p value says a change exists, nothing more.
- Trusting a default line blindly. Evidently flagged
words, a column that never moved. - Copying 0.2 from a blog post. Measure no-shift PSI on your own data and weekly volume.
Recap
| Tool | What it does | On our tickets |
|---|---|---|
| PSI | Bins training, adds up how far each bin moved | Week 3 sentiment 1.56; quiet weeks 0.03 |
| KS test | Widest gap between two running totals, plus a p value | 0.42 on sentiment; stayed quiet on words |
| Evidently | Whole table on one HTML page | 4 of 8 flagged, one of them a false alarm |
| No-shift draws | Measures the noise for your volume | Median 0.039, p99 0.101 |
Try it yourself
In 04_ks_report.py, change 200 to 50 in the no-shift draws and see how high PSI goes with nothing shifted. What would that do to a 0.2 alert line?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Monitoring Drift and Retraining: When a Model Gets Worse With No Code Change
Next →Shadow, Canary and Rollback: Releasing a New Model Without Betting Everything on It
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.