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.
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].
What to monitor (four layers)
- Service health — request rate, error rate, p50/p95/p99 latency, CPU/GPU/memory. Same as any web service.
- Data quality — schema, missing-value rates, out-of-range values, unseen categories. Often the first sign of a broken upstream pipeline.
- Input & prediction drift — has the distribution of features or of model scores moved away from the training reference? Available immediately, no labels needed.
- 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)
- 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
| Shift | What changes | Example | Detectable without labels? |
|---|---|---|---|
| Data / covariate drift | P(X) changes, P(Y|X) stays | App launches in a new city; users are younger | Yes — compare feature distributions |
| Label / prior shift | P(Y) changes, P(X|Y) stays | Flu season: many more positive cases | Partly — via prediction distribution |
| Concept drift | P(Y|X) changes — the relationship itself | Fraudsters change tactics; same features now mean something else | Mostly 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
- 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
| PSI | Interpretation | Typical action |
|---|---|---|
| < 0.1 | Stable | None |
| 0.1 – 0.25 | Moderate shift | Investigate, watch closely |
| > 0.25 | Significant shift | Alert; check data pipeline; consider retraining |
Kolmogorov–Smirnov (KS) test
- 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
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).
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)Try it: drift detector
- 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.
- 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.
- 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.
- 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).
- 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.
- 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
- Check the data pipeline first. Most “drift” alerts are bugs: a unit change (cents → dollars), a renamed category, a broken join that fills nulls.
- 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.
- Measure performance on fresh labels (or a quickly labelled sample).
- 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.
▸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
monthly_charges this week is 0.31. Using the common rule of thumb, what is the best first step?References
- [1]
- [2]scipy.stats.ks_2sampDocsSciPydocs.scipy.org
- [3]Evidently AI documentationDocsEvidently AIdocs.evidentlyai.com
- [4]Designing Machine Learning Systems (ch. 8: Data Distribution Shifts and Monitoring)BookChip Huyen2022oreilly.com
- [5]Failing Loudly: An Empirical Study of Methods for Detecting Dataset ShiftPaperRabanser et al.2019arxiv.org