◆ AI All-in-One

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
↗ Plan a path here

Read first

Deploying Models

This leads to

—
The full path from zero — 7 concepts before this one
  1. What Is AI?
  2. Python for AI
  3. How Machines Learn
  4. Supervised, Unsupervised and Reinforcement Learning
  5. Supervised Learning
  6. The ML Project Lifecycle
  7. Deploying Models
  8. 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:

0 25 50 75 100 Mean shift: 50 → 55PSI 0.240 · KS D 0.202 feature value 0 25 50 75 100 Wider spread: sd 10 → 15PSI 0.194 · KS D 0.102 feature value training data (20,000 rows)production week (5,000 rows)
Fig. 1 Distributions of one input feature: the training data (blue) against two weeks of production data (orange), computed from synthetic samples. Left: the mean has shifted from 50 to 55 (PSI 0.24). Right: the mean is the same but the spread has grown (PSI 0.19). Both are clear drift.

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 xx and the target yy. Several things can change after deployment:

  • Covariate shift (one kind of data drift): the inputs' distribution P(x)P(x) 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 P(y)P(y) changes. Fraud rates double during a holiday sale.
  • Concept drift: the relationship itself, P(y∣x)P(y \mid x), 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.
Covariate shiftinputs move, the rule stays training inputs: lower leftproduction inputs: upper right Concept driftinputs stay, the rule moves: red band is now wrong class Aclass Bnew production input true boundary nowmodel learned
Fig. 2 Two kinds of change, computed from synthetic data. Left: covariate shift. New inputs (orange) arrive in a region the model saw little of, but the true boundary (dashed) is unchanged. Right: concept drift. The inputs look the same, but the true boundary has moved, so the old model's boundary (solid) is now wrong for many points.

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:

  1. Service health: request rate, error rate, latency percentiles, memory. These are standard software metrics (Deploying Models).
  2. Data quality: missing values, out-of-range values, unseen categories, schema changes. The same checks as the validation gate in Data Pipelines and Datasets.
  3. Input drift: each feature's distribution compared with a reference window, usually the training data or a recent stable period.
  4. 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.
  5. 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:

PSI=∑i=1B(ci−ri) ln⁡ciri\text{PSI} = \sum_{i=1}^{B} (c_i - r_i) \, \ln\frac{c_i}{r_i}

Here BB is the number of bins, rir_i is the fraction of reference data in bin ii, and cic_i 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 r=(0.3,0.4,0.3)r = (0.3, 0.4, 0.3), this week c=(0.2,0.4,0.4)c = (0.2, 0.4, 0.4):

  • Bin 1: (0.2−0.3)ln⁡(0.2/0.3)=(−0.1)(−0.405)=0.041(0.2 - 0.3)\ln(0.2/0.3) = (-0.1)(-0.405) = 0.041
  • Bin 2: (0.4−0.4)ln⁡(1)=0(0.4 - 0.4)\ln(1) = 0
  • Bin 3: (0.4−0.3)ln⁡(0.4/0.3)=(0.1)(0.288)=0.029(0.4 - 0.3)\ln(0.4/0.3) = (0.1)(0.288) = 0.029

PSI =0.07= 0.07. 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 DD is the largest vertical gap between the two curves:

D=max⁡x∣Fref(x)−Fcur(x)∣D = \max_x \left| F_{\text{ref}}(x) - F_{\text{cur}}(x) \right|

F(x)F(x) is the fraction of a sample at or below xx. DD 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 (DD 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:

  1. Is it a bug? Check data quality first. Many "drifts" are broken pipelines.
  2. Does it matter? Check whether performance or the business metric has moved, or is likely to, for the features the model relies on most.
  3. 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

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

  1. In the first script, find the smallest mean shift that pushes PSI above 0.1. What KS p-value does it have?
  2. Change the bins from deciles to 10 equal-width bins between 0 and 100. Do the PSI values change much?
  3. In the concept-drift example, retrain the model on x_new, y_new and 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. Input distributions look unchanged, the service is healthy, but accuracy on late-arriving labels has fallen sharply. What kind of change is this?

  2. Reference bin fractions are (0.3, 0.4, 0.3) and this week's are (0.2, 0.4, 0.4). The PSI is about 0.07. How would you read it with the usual rule of thumb?

  3. With 50,000 rows a day, a KS test on a feature gives p = 0.003, but the PSI is 0.006. What should you conclude?

  4. Every Monday, dozens of drift alerts fire across all features and the team has started ignoring them. What is the recommended fix?

  5. A shopping model trained on summer data flags heavy drift every December. What is the likely cause?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Book

Designing Machine Learning Systems

Chip Huyen · 2022 · Intermediate · Paid

The practical guide to data, features, deployment, monitoring and iteration in production ML.

Docs

Evidently documentation

Evidently AI · Intermediate · open-source core

An open-source library for data-drift, data-quality and model-performance reports and monitoring dashboards, with clear explanations of each test.

Docs

scipy.stats.ks_2samp

SciPy · Beginner · Free

Reference for the two-sample Kolmogorov–Smirnov test in SciPy, with examples.

Course

Machine Learning in Production

Andrew Ng (DeepLearning.AI) · Intermediate · free to audit

Scoping, data definition, error analysis, deployment and concept drift, taught through the full lifecycle of a project.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/monitoring-and-drift.md