AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
⚙ML Development & MLOps
  1. The ML development stack
  2. The ML lifecycle & MLOps maturity
  3. Experiment tracking with MLflow
  4. Model Registry, data versioning & lineage
  5. Deployment & model serving
  6. Monitoring, data drift & concept drift
  7. CI/CD, continuous training & feature stores
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/ML Development & MLOps

Monitoring, data drift & concept drift

What to monitor in production, the kinds of distribution shift, how PSI and the KS test quantify drift, how to set alert thresholds, and when to retrain.

Advanced~25 min·5 references
Key terms
Model monitoringData driftConcept driftProbability distributionDecision thresholdTraining setLatency

Software usually fails loudly — it crashes or throws errors. ML models fail silently: the service stays up, returns well-formed predictions, and those predictions slowly get worse because the world changed. Customers behave differently after a price change, a sensor is recalibrated, a new product category appears, fraudsters adapt. [[monitoring]] for ML therefore watches not only CPU and Latency but also the data going in and the predictions coming out[1][4].

≈
An old map of a growing city
A model is a map drawn from last year's city. Data drift is new neighbourhoods appearing at the edges — places your map never covered. Concept drift is the same streets but the rules changed: a road became one-way, so your old directions are now wrong even in familiar places. Monitoring is noticing both before drivers get lost.

What to monitor (four layers)

  1. Service health — request rate, error rate, p50/p95/p99 latency, CPU/GPU/memory. Same as any web service.
  2. Data quality — schema, missing-value rates, out-of-range values, unseen categories. Often the first sign of a broken upstream pipeline.
  3. Input & prediction drift — has the distribution of features or of model scores moved away from the training reference? Available immediately, no labels needed.
  4. Model performance — accuracy, precision/recall, MAE… once ground-truth labels arrive (minutes for clicks, months for loan defaults). Until then use proxies.

Kinds of distribution shift

P(X, Y) = P(Y | X) · P(X) = P(X | Y) · P(Y)
Every type of shift is a change in one factor of the joint distribution between training and production.
In words: The world a model sees is the joint distribution of inputs and labels, and it can be split into two factors in two ways. Covariate shift = P(X) changes while P(Y | X) stays; label shift = P(Y) changes while P(X | Y) stays; concept drift = the relationship P(Y | X) itself changes. Naming the factor that moved tells you whether you can detect it without labels and how to fix it.
Symbols(hover a symbol in the formula)
P(X, Y)
joint probability of seeing input X together with label Y
P(Y | X)
probability of the label given the input — the relationship the model learns; it changes under concept drift
P(X)
distribution of the inputs (features); it changes under covariate shift
P(X | Y)
how inputs look within each class
P(Y)
class balance / label distribution; it changes under label (prior) shift
|
“given”: the probability on the left assuming the right side is known
·
multiplication
▸Worked example
Churn model; X = “monthly contract”, Y = churn Training: P(X) = 0.4, P(Y | X) = 0.3, churn rate for other contracts = 0.05 P(X, Y) = 0.3 · 0.4 = 0.12 P(Y) = 0.12 + 0.6 · 0.05 = 0.15 check: P(X | Y) = 0.12 / 0.15 = 0.8 → 0.8 · 0.15 = 0.12 ✓ Production: a promo pushes monthly contracts to P(X) = 0.6, P(Y | X) unchanged P(X, Y) = 0.3 · 0.6 = 0.18 P(Y) = 0.18 + 0.4 · 0.05 = 0.20 → covariate shift (visible without labels) that also raises the churn rate 15% → 20%
ShiftWhat changesExampleDetectable without labels?
Data / covariate driftP(X) changes, P(Y|X) staysApp launches in a new city; users are youngerYes — compare feature distributions
Label / prior shiftP(Y) changes, P(X|Y) staysFlu season: many more positive casesPartly — via prediction distribution
Concept driftP(Y|X) changes — the relationship itselfFraudsters change tactics; same features now mean something elseMostly no — needs labels or proxies

Gama et al. also classify drift by how it happens over time: sudden (a policy change overnight), incremental (slow inflation of prices), gradual (old and new concepts alternate before the new one wins) and recurring (seasonality — the old concept comes back)[1]. Recurring drift is why “retrain on the last 7 days only” can be a bad idea before holidays.

Population Stability Index (PSI)

PSI compares binned distributions. Split the reference (training) data into bins — commonly 10 quantile bins so each holds ~10% — then measure what fraction of reference (eᵢ, expected) and production (aᵢ, actual) data falls into each bin:

PSI = Σᵢ (aᵢ − eᵢ) · ln(aᵢ / eᵢ)
Population Stability Index: one drift score per feature, summed over bins.
In words: For each bin, multiply “how much the share changed” by “the log of how many times bigger or smaller it got”, then add up the bins. Both factors always have the same sign, so every term is ≥ 0 and PSI = 0 only when the distributions match. It equals a symmetric KL divergence, KL(a‖e) + KL(e‖a). Empty bins need a small ε (e.g. 0.0001) to avoid ln(0).
Symbols(hover a symbol in the formula)
PSI
Population Stability Index — 0 = identical; < 0.1 stable, > 0.25 significant shift (rules of thumb)
Σᵢ
sum over all bins i (commonly 10 quantile bins of the reference data)
aᵢ
actual: fraction of production data in bin i (all aᵢ sum to 1)
eᵢ
expected: fraction of reference (training) data in bin i
ln
natural logarithm; ln(1) = 0, negative when the ratio < 1
aᵢ / eᵢ
how many times more (or less) often production lands in bin i
·
multiplication
▸Worked example
3 bins, reference e = (0.5, 0.3, 0.2), production a = (0.4, 0.3, 0.3) bin 1: (0.4 − 0.5) · ln(0.4/0.5) = −0.1 · (−0.2231) = 0.0223 bin 2: (0.3 − 0.3) · ln(1) = 0 bin 3: (0.3 − 0.2) · ln(0.3/0.2) = 0.1 · 0.4055 = 0.0405 PSI = 0.0223 + 0 + 0.0405 ≈ 0.063 → < 0.1, stable
PSIInterpretationTypical action
< 0.1StableNone
0.1 – 0.25Moderate shiftInvestigate, watch closely
> 0.25Significant shiftAlert; check data pipeline; consider retraining
Widely used rules of thumb from credit-risk practice — not statistical laws. Calibrate on your own historical data.

Kolmogorov–Smirnov (KS) test

D = supₓ | F_ref(x) − F_prod(x) |
The two-sample Kolmogorov–Smirnov statistic.
In words: Draw the empirical cumulative distribution of the feature for the reference data and for production data — each curve says “what fraction of values are ≤ x”. D is the largest vertical gap between the two curves over every x. D = 0 means identical samples, D = 1 means they don't overlap at all.
Symbols(hover a symbol in the formula)
D
the KS statistic, between 0 and 1
supₓ
supremum over x — the largest value over all possible x (a max)
F_ref(x)
empirical CDF of the reference (training) sample: fraction of reference values ≤ x
F_prod(x)
empirical CDF of the production sample: fraction of production values ≤ x
|
absolute value bars: the size of the gap, ignoring which curve is higher
−
difference between the two curves at the same x
▸Worked example
reference = {1, 2, 3, 4}, production = {3, 4, 5, 6} x = 2: F_ref = 2/4 = 0.5, F_prod = 0/4 = 0 → gap 0.5 x = 3: F_ref = 0.75, F_prod = 0.25 → gap 0.5 x = 4: F_ref = 1, F_prod = 0.5 → gap 0.5 x = 5: F_ref = 1, F_prod = 0.75 → gap 0.25 D = 0.5 — half of the distribution has moved

The two-sample KS test works on raw continuous values without binning and returns a statistic D (0 = identical, 1 = no overlap) and a p-value[2]. Beware: with tens of thousands of production rows, even a tiny, harmless shift gives p < 0.001. Combine the p-value with an effect-size threshold on D (or use PSI) so you don't drown in alerts. For categorical features use a chi-square test on the category counts, or PSI with one bin per category (a brand-new category is an instant red flag).

python
import numpy as np
from scipy.stats import ks_2samp, chi2_contingency

def psi(reference, current, bins=10, eps=1e-6):
    # quantile bin edges from the REFERENCE data (~equal mass per bin)
    edges = np.unique(np.quantile(reference, np.linspace(0, 1, bins + 1)))
    edges[0], edges[-1] = -np.inf, np.inf
    e = np.histogram(reference, edges)[0] / len(reference)
    a = np.histogram(current, edges)[0] / len(current)
    e, a = np.clip(e, eps, None), np.clip(a, eps, None)
    return float(np.sum((a - e) * np.log(a / e)))

rng = np.random.default_rng(0)
ref = rng.normal(50, 10, 20_000)          # training: monthly_charges
cur = rng.normal(55, 12, 5_000)           # production this week

print("PSI:", round(psi(ref, cur), 3))
res = ks_2samp(ref, cur)
print("KS D:", round(res.statistic, 3), "p-value:", res.pvalue)

# categorical feature: counts per category (reference vs current)
table = np.array([[7000, 9000, 4000, 0],      # monthly, yearly, two-year, NEW
                  [1500, 2000,  900, 600]])
chi2, p, dof, _ = chi2_contingency(table + 1)  # +1 smoothing for empty cells
print("chi2 p-value:", p)
PSI, KS and chi-square in a few lines

Try it: drift detector

Loading interactive…
  • Shift the production mean slowly to the right. Watch PSI cross 0.1 (yellow) and 0.25 (red). How large a shift (in standard deviations) does each colour need?
  • Reset, then change only the scale (spread) without moving the mean. KS and PSI still react — drift is not only about averages.
  • Add a new category spike. Notice how quickly PSI jumps: a bin that was nearly empty in training gets a large ln(aᵢ/eᵢ).
  • Compare the KS p-value with the KS statistic D: a tiny D can still have a tiny p-value when samples are large.
  • In the 30-day timeline, move the drift start day and the alert threshold. A lower threshold alerts earlier but also fires on normal day-to-day noise.
knobPSI alert threshold
What it is
The PSI value above which a feature (or the prediction score) triggers an alert.
↑ If you increase it
Fewer false alarms, but real drift is detected later (or never for slow drift).
↓ If you decrease it
Earlier detection, but alert fatigue — people start ignoring the pager.
Typical values
0.1 warn / 0.25 alert, tuned on historical data.
knobKS significance level α
What it is
The p-value cut-off below which the KS test declares “distributions differ”.
↑ If you increase it
Larger α (e.g. 0.1) flags more features as drifted, including harmless noise.
↓ If you decrease it
Smaller α (e.g. 0.001, or Bonferroni-corrected for many features) reduces false positives; with huge samples you still need an effect-size floor on D.
Typical values
0.05 / number_of_features, plus D > 0.1.
knobnumber of bins (PSI)
What it is
How many bins numeric features are cut into before computing PSI.
↑ If you increase it
More detail, but bins get sparse and PSI becomes noisy and inflated on small production samples.
↓ If you decrease it
More stable but coarse — shifts inside a wide bin go unnoticed.
Typical values
10 quantile bins (deciles).
knobmonitoring window size
What it is
How much recent production data is compared with the reference each time (last hour, day, 7 days, or last N predictions).
↑ If you increase it
Smoother, more reliable statistics; sudden drift is detected later and short incidents get averaged away.
↓ If you decrease it
Fast reaction, but noisy — daily or weekly cycles can look like drift.
Typical values
1 day (with ≥ a few thousand rows) and 7 days side by side.
knobretraining frequency / trigger
What it is
When a new model is trained: on a fixed schedule, when drift/performance alerts fire, or when enough new labels arrive.
↑ If you increase it
Retraining more often keeps the model fresh in fast-changing domains, but costs compute, and every release carries risk (needs automated validation).
↓ If you decrease it
Cheaper and more stable, but performance decays between retrains.
Typical values
Weekly–monthly schedule plus drift-triggered retraining; measure how fast performance decays to choose.

From alert to action

  1. Check the data pipeline first. Most “drift” alerts are bugs: a unit change (cents → dollars), a renamed category, a broken join that fills nulls.
  2. Does it matter? Drift in a feature the model barely uses is less urgent. Weight alerts by feature importance and look at prediction-score drift.
  3. Measure performance on fresh labels (or a quickly labelled sample).
  4. Retrain on recent data (possibly with older data weighted down), validate against the champion, roll out via canary — ideally automated (next lesson).

You rarely need to write all of this yourself: open-source tools such as Evidently generate data-drift and data-quality reports and test suites from a reference and a current DataFrame, choosing a suitable statistical test per column type[3]. Their APIs change between versions, so follow the current docs.

!
Monitoring pitfalls
• Using p-values alone on huge samples → everything “drifts”. • Testing 300 features at α = 0.05 → ~15 false alarms every run. • Comparing against the wrong reference (e.g. the whole history instead of the training window). • Ignoring seasonality → alerts every Monday. • Monitoring inputs but not predictions, or predictions but never collecting labels. • Retraining blindly on drifted data that was actually a pipeline bug.
▸Go deeper: multivariate drift and detecting shift reliably

Per-feature tests miss changes in correlations between features. Two practical multivariate approaches: (1) a domain classifier — train a model to tell reference rows from production rows; an AUC well above 0.5 means the joint distribution changed, and its feature importances show where; (2) test drift in a lower-dimensional space (e.g. model embeddings or PCA components). Rabanser et al. compared many shift detectors empirically and found that two-sample tests on dimensionality-reduced representations (e.g. from a pretrained classifier's outputs) work well in practice[5].

Quiz

1.
A bank's fraud model sees the same feature distributions as in training, but fraud recall drops sharply because criminals changed tactics. What is this?
2.
PSI for monthly_charges this week is 0.31. Using the common rule of thumb, what is the best first step?
3.
With 200,000 production rows, the KS test gives p = 1e-9 but D = 0.01. How should you read it?
4.
What happens if you shrink the monitoring window from 7 days to 1 hour?
5.
Which signal is available immediately in production without waiting for labels?
Score: 0/5

References

  1. [1]
    A Survey on Concept Drift Adaptation
    PaperGama et al.2014doi.org
    ACM Computing Surveys 46(4).
  2. [2]
    scipy.stats.ks_2samp
    DocsSciPydocs.scipy.org
  3. [3]
    Evidently AI documentation
    DocsEvidently AIdocs.evidentlyai.com
  4. [4]
    Designing Machine Learning Systems (ch. 8: Data Distribution Shifts and Monitoring)
    BookChip Huyen2022oreilly.com
  5. [5]
    Failing Loudly: An Empirical Study of Methods for Detecting Dataset Shift
    PaperRabanser et al.2019arxiv.org
← Previous
Deployment & model serving
Next →
CI/CD, continuous training & feature stores