Level 3 In-Depth AI · ML Engineering and Production
Monitoring and Data Drift
The world keeps changing after a model ships, and its accuracy quietly decays. What to watch, how to detect that today's inputs no longer look like the training data (PSI and the KS test), the difference between data drift and concept drift, and when to retrain.
- Level
- ●●●●● Easy
- Reading
- 11 min
- To learn it well
- 45 minutes to read, an afternoon to practise
- Builds on
- 7 concepts →
- Quiz
- 5 questions ↓
Read first
Deploying ModelsThis leads to
—The full path from zero — 7 concepts before this one
- What Is AI?
- Python for AI
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- The ML Project Lifecycle
- Deploying Models
- Monitoring and Data Drift
Read them roughly in this order. See it on the concept map →
Why it matters
Software that worked yesterday usually works today. Models are different: they can be broken by the world changing around them while the code stays exactly the same. A fraud model learns last year's tricks, and fraudsters invent new ones. A demand forecaster learns normal shopping, and then a pandemic, a heatwave or a competitor's sale changes what normal is. A spam filter meets a new kind of spam.
When this happens, nothing crashes. The service still answers in 3 milliseconds with confident predictions. They are just increasingly wrong. Model monitoring is the practice of watching a deployed model's inputs, outputs, performance and health so that you notice this decay before your users or your finance team do.
Monitoring closes the loop of the The ML Project Lifecycle: its alerts send you back to collect data and retrain. This chapter assumes a model is already deployed (Deploying Models).
The intuition
Think of a weather forecaster who learned the climate of one city and then moved. Her methods are fine, but her sense of "typical" is wrong for the new place. You could notice in two ways. You could wait for her forecasts to fail, which takes days and costs picnics. Or you could notice at once that the temperatures she is reading look unlike any she trained on, and treat her forecasts with suspicion.
Monitoring uses both signals. Performance monitoring compares predictions with the true outcomes, when they arrive. Drift monitoring compares today's inputs with the training inputs and raises a flag when they differ, without waiting for outcomes.
Data drift means the distribution of the inputs has changed. Here is what that looks like for one feature, with the training data in blue and a week of production data on top:
Key idea Models decay silently. Watch four things: service health, the inputs (drift), the outputs (prediction distribution), and, when labels arrive, real performance. Drift is a warning, not a verdict: what matters is whether performance on the business metric falls.
How it works
What can change
Statisticians describe a model as learning the relationship between inputs and the target . Several things can change after deployment:
- Covariate shift (one kind of data drift): the inputs' distribution changes, but the rule linking inputs to outputs stays the same. The app launches in a new country and users get younger. A model that saw few young users may now be extrapolating.
- Label shift: the share of each outcome changes. Fraud rates double during a holiday sale.
- Concept drift: the relationship itself, , changes. The same customer profile that used to stay now leaves, because a competitor launched a cheaper plan. Inputs can look identical while the right answer has moved.
Change also has a tempo. It can be sudden (a new law, a bug upstream), gradual (an ageing customer base), or recurring (weekends, Christmas, school holidays).
A special and very common case is not drift at all but training–serving skew: production computes a feature differently from training, for example in different units or with a different default for missing values. Drift detection catches it on day one, which is one reason to monitor from launch.
What to monitor
Think of it in layers, from easiest to most informative:
- Service health: request rate, error rate, latency percentiles, memory. These are standard software metrics (Deploying Models).
- Data quality: missing values, out-of-range values, unseen categories, schema changes. The same checks as the validation gate in Data Pipelines and Datasets.
- Input drift: each feature's distribution compared with a reference window, usually the training data or a recent stable period.
- Output drift: the distribution of predictions. If a churn model suddenly flags 30% of customers instead of 10%, something changed, even before any labels arrive.
- Performance: accuracy, precision, recall or the business metric, computed when true labels arrive. Often labels arrive late (whether a customer churns is known only after 30 days; a fraud chargeback can take weeks) or never (the loan you refused can never default). That delay is why the earlier layers matter.
Measuring drift: PSI
The population stability index (PSI) is a popular, easy-to-read drift score that comes from credit scoring. Cut the feature's range into bins, often ten bins at the reference data's deciles so each holds 10% of the reference. Then compare the share of data in each bin:
Here is the number of bins, is the fraction of reference data in bin , and is the fraction of current data in the same bin. Each term is positive whenever the two fractions differ, in either direction, so PSI is zero only when the histograms match. (It is a symmetrised form of the KL divergence.)
Worked example with three bins. Reference fractions , this week :
- Bin 1:
- Bin 2:
- Bin 3:
PSI . A widely used rule of thumb reads PSI below 0.1 as no significant change, 0.1 to 0.25 as a moderate shift worth a look, and above 0.25 as a major shift. These thresholds are conventions from industry practice, not laws. Tune them on your own history.
Measuring drift: the KS test
The Kolmogorov–Smirnov (KS) test is a classical statistical test of whether two samples come from the same distribution. Sort each sample and draw its cumulative distribution: the fraction of values below each point. The KS statistic is the largest vertical gap between the two curves:
is the fraction of a sample at or below . runs from 0 (identical) to 1 (no overlap). The test also returns a p-value: the probability of seeing a gap this large if both samples really came from the same distribution. A small p-value, conventionally below 0.05, means "these probably differ".
The catch is sample size. With thousands of rows per day, the KS test detects differences far too small to matter. In the code below, shifting a feature by 0.5 when its spread is 10 gives p = 0.003, "significant", while its PSI of 0.006 says nothing important happened. Use the size of the difference ( or PSI) for alerts, and the p-value only as a sanity check. For categorical features use a chi-squared test or PSI on the categories. For high-dimensional inputs such as images or text, measure drift on embeddings or on the model's own output probabilities. A 2019 study of shift-detection methods (Rabanser et al., Failing Loudly) found that tests applied to a model's softmax outputs, or to a dimensionality-reduced representation, worked well.
From alert to action
An alert should lead to a decision, not a panic:
- Is it a bug? Check data quality first. Many "drifts" are broken pipelines.
- Does it matter? Check whether performance or the business metric has moved, or is likely to, for the features the model relies on most.
- Retrain, recalibrate, or redesign. Retraining on recent data fixes most covariate shift and mild concept drift. Some teams retrain on a fixed schedule (daily, weekly); others retrain when monitoring triggers. Either way, the new model must beat the old one on recent held-out data before it replaces it (shadow or canary rollout).
Too many alerts are as bad as none. If every feature fires a warning every Monday, people learn to ignore them. This is alert fatigue. Alert on few, important signals: the top features by importance, the prediction distribution, and the business metric. Send the rest to a dashboard.
In code
PSI from scratch and the KS test from SciPy, on a reference sample and four synthetic "production weeks":
import numpy as np
from scipy.stats import ks_2samp
def psi(reference, current, bins=10):
"""Population Stability Index with bins at the reference deciles."""
edges = np.quantile(reference, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf # catch values outside the range
ref = np.histogram(reference, edges)[0] / len(reference)
cur = np.histogram(current, edges)[0] / len(current)
ref, cur = np.clip(ref, 1e-6, None), np.clip(cur, 1e-6, None) # avoid log(0)
return np.sum((cur - ref) * np.log(cur / ref))
rng = np.random.default_rng(42)
train = rng.normal(50, 10, 20_000) # e.g. customer age at training time
weeks = {
"same distribution": rng.normal(50, 10, 5_000),
"tiny shift (+0.5)": rng.normal(50.5, 10, 5_000),
"mean shift (+5)": rng.normal(55, 10, 5_000),
"wider (sd 15)": rng.normal(50, 15, 5_000),
}
for name, x in weeks.items():
ks = ks_2samp(train, x)
print(f"{name:<18} PSI {psi(train, x):.3f} KS {ks.statistic:.3f} p={ks.pvalue:.3g}")
# same distribution PSI 0.002 KS 0.016 p=0.23
# tiny shift (+0.5) PSI 0.006 KS 0.028 p=0.00316 <- "significant", but harmless
# mean shift (+5) PSI 0.240 KS 0.202 p=1.47e-143
# wider (sd 15) PSI 0.194 KS 0.102 p=4.84e-37
Now concept drift. The inputs keep exactly the same distribution, but the behaviour behind the labels changes. Input monitoring sees nothing, while accuracy falls:
from sklearn.linear_model import LogisticRegression
rng = np.random.default_rng(1)
x_old = rng.normal(50, 10, 5_000)
y_old = rng.random(5_000) < 1 / (1 + np.exp(-(x_old - 50) / 3)) # P(buy) rises with x
model = LogisticRegression().fit(x_old[:, None], y_old)
x_new = rng.normal(50, 10, 5_000) # same inputs...
y_new = rng.random(5_000) < 1 / (1 + np.exp(-(x_new - 60) / 3)) # ...new behaviour
print(f"input PSI {psi(x_old, x_new):.3f}")
print(f"accuracy before {model.score(x_old[:, None], y_old):.3f} after {model.score(x_new[:, None], y_new):.3f}")
# input PSI 0.002
# accuracy before 0.851 after 0.695
Libraries such as Evidently and NannyML wrap these tests into reports and dashboards, with per-feature drift scores and estimated performance when labels are missing.
Common pitfalls
- Alerting on p-values with big data. With enough rows, every feature is "significantly" different every day. Alert on effect size (PSI, KS statistic) with thresholds tuned on history.
- Monitoring only inputs. Concept drift leaves inputs unchanged, as the second example shows. Track real performance as labels arrive, and the prediction distribution meanwhile.
- The wrong reference. Comparing December traffic with a training set from summer flags seasonality, not a problem. Use a reference window that matches the season, or compare with the same period last year.
- Feedback loops. A model's decisions change the data it later learns from. A recommender shows only what it already likes, and a fraud model blocks transactions whose true labels you then never see. Keep a small random control group if you can.
- Retraining blindly. Automatic retraining on corrupted data ships the corruption. Gate every retrained model with the same validation and evaluation as the first one.
- No owner. Dashboards nobody reads don't help. Every alert needs a named person and a runbook.
Watch out The most dangerous failure is silent: inputs look normal, the service is healthy, and accuracy has collapsed because the world's rules changed. If true labels ever arrive, even late, even for a sample, compute real performance on them. It is the only direct evidence the model still works.
Where it leads
- Data Pipelines and Datasets: the same distribution checks guard training data.
- Experiment Tracking and Reproducibility and Deploying Models: retraining produces a new tracked run and a new versioned deployment.
- Anomaly Detection: methods for spotting individual unusual inputs rather than shifts in whole distributions.
- Evaluating LLM Applications: for LLM applications, monitoring means sampling real conversations and scoring them, often with an LLM judge.
- Time Series Forecasting: forecasting models face drift constantly and are usually retrained on a rolling window.
A bit of history
The term concept drift comes from machine learning research in the 1980s. Schlimmer and Granger used it in 1986 for learning systems whose target concept changes over time. Widmer and Kubat studied learning under drift and "hidden contexts" in the 1990s. The PSI comes from credit scoring, where banks have long had to check that the population applying for loans still resembles the one their scorecards were built on. The KS test is far older: Kolmogorov published the one-sample test in 1933, and Smirnov the two-sample version in 1939.
Drift became a mainstream engineering topic once many companies ran models in production. In 2020 the COVID-19 lockdowns changed shopping, travel and finance almost overnight, and many forecasting and fraud models degraded sharply at once. That episode made monitoring and fast retraining a standard part of MLOps.
Try it
- In the first script, find the smallest mean shift that pushes PSI above 0.1. What KS p-value does it have?
- Change the bins from deciles to 10 equal-width bins between 0 and 100. Do the PSI values change much?
- In the concept-drift example, retrain the model on
x_new, y_newand measure its accuracy on fresh data from the new behaviour.Hint for 1: try shifts of 1, 2, 3 and 4. PSI grows roughly with the square of the shift for small shifts.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Designing Machine Learning Systems
The practical guide to data, features, deployment, monitoring and iteration in production ML.
Evidently documentation
An open-source library for data-drift, data-quality and model-performance reports and monitoring dashboards, with clear explanations of each test.
Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift
Compares many ways to detect distribution shift in high-dimensional data and finds that simple two-sample tests on reduced representations work well.
scipy.stats.ks_2samp
Reference for the two-sample Kolmogorov–Smirnov test in SciPy, with examples.
Machine Learning in Production
Scoping, data definition, error analysis, deployment and concept drift, taught through the full lifecycle of a project.
Rules of Machine Learning: Best Practices for ML Engineering
43 hard-won rules from building production ML at Google, with a long section on features, training–serving skew and when to add complexity.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/monitoring-and-drift.md