Monitoring ML models: data drift, concept drift and delayed labels
Set monitors for data quality, input drift, concept change, delayed-label performance, service health and cost.
By Invicly Tech, , in AI and Machine Learning with Python. About 11 minutes to read.
In short
A model can keep running without errors while its predictions quietly get worse. ML monitoring watches six different things: the quality of incoming data, drift in the inputs, changes in the relationship between inputs and outcomes, accuracy once true labels arrive, service health and cost. Each one fails in a different way and needs its own signal and threshold.
Think of it like this: Monitoring only server uptime is like checking that a weather station has power without checking that its thermometer still reads correctly.
Explained simply
A normal web service is broken when it crashes or returns errors. A model can fail more quietly. It can keep answering every request in 30 ms while its answers slowly become wrong, because the world it learned from has changed. ML monitoring exists to catch that quiet failure early.
Start with the basics. Is the data arriving complete and in the right shape? Are requests fast and error-free? Is the cost per prediction what you expected? These checks are cheap and catch most real incidents, such as a broken upstream table or a renamed column.
Next, watch for drift. Data drift means the inputs look different from the training data: customers are younger, prices are higher, a new product category appeared. Concept change means the right answer for the same input has changed, such as buying habits shifting after a price rise.
The best check is real accuracy, but the true outcome often arrives late. A loan default may take a year to show. Until labels arrive, drift and the spread of the model's own predictions act as early warnings. When labels do arrive, compare them with what the model predicted.
Press Play on a diagram to walk through it one step at a time.
- 1Service health
Latency, error rate, throughput: seconds
- 2Cost
Compute and storage per prediction: hours to days
- 3Data quality
Missing values, wrong types, out-of-range: per batch
- 4Input drift
Feature distributions move: days
- 5Concept change
Same inputs now lead to different outcomes
- 6Labelled performance
Accuracy once true outcomes arrive: weeks
- Data quality fails
- Block the batch or use fallback
- Fix the upstream pipeline
- Input drift high
- Check top features first
- Look for a pipeline or population change
- Consider a retraining trigger
- Labelled metric drops
- Confirm with enough labels
- Retrain or roll back
- Latency or errors up
- Treat as a service incident
- Scale or roll back the release
- Cost above budget
- Check traffic and model size
- Review batching and caching
In depth
Data quality checks at the input
Data quality checks run before or alongside the model and compare each batch or request with expectations taken from the training data. Typical rules: required columns present, types correct, missing-value rate below a limit, numeric values inside a plausible range, categories from a known list, and row counts close to normal.
These are the cheapest monitors and often the most valuable, because most production ML incidents start as data bugs: a join that duplicated rows, a unit changed from euros to cents, or a field that started arriving empty. A failing check should block a batch job, or flag online predictions and use a fallback. Libraries such as Pandera or Great Expectations help, but plain pandas assertions work for a start.
- Schema: columns and types
- Completeness: missing-value rates
- Validity: ranges and allowed categories
- Volume: row counts against normal
- Freshness: newest timestamp is recent
Measuring feature drift
To measure drift you compare a current window, such as last week's inputs, with a reference window, usually the training or validation data. For numeric features, common measures are the population stability index (PSI) and the two-sample Kolmogorov-Smirnov test, available as scipy.stats.ks_2samp. For categories, compare the share of each category, or use PSI or a chi-squared test.
Be careful with statistical tests on large samples: with a million rows, a KS test finds tiny, harmless shifts significant. Effect-size measures like PSI, with thresholds tuned on past data, are easier to act on. Weight attention by feature importance: drift in the top three features matters more than drift in a feature the model barely uses.
- One number per feature
- Works on binned numeric or category data
- Rule of thumb: over 0.25 is a big shift
- Easy to threshold and chart
- Numeric features only
- Gives a statistic and p-value
- Very sensitive on large samples
- Good for small daily batches
- Compare share of each value
- Catches new or vanished categories
- Simple to explain to owners
- Chi-squared test if needed
Concept change and delayed labels
Concept change is when P(target given inputs) moves. Input drift monitors cannot see it, because the inputs may look the same. The only direct evidence is labelled performance: compare predictions with true outcomes once they arrive.
When labels are delayed, plan for it. Record each prediction with an id, timestamp and model version, then join outcomes when they arrive and compute metrics per prediction week, so you compare like with like. Watch label coverage: if only approved loans get outcomes, your measured accuracy describes approved loans only. Meanwhile, use proxies: prediction distribution drift, early partial outcomes such as first missed payment, and business metrics. Treat proxies as warnings, not proof.
- Log prediction id, time, inputs digest and model version
- Join labels later and report by prediction cohort
- Track label coverage and bias
- Use proxy signals as early warnings only
Service health and cost
A model is also a service. Watch request rate, error rate and latency at p50, p95 and p99, the same signals you would use for any API. For batch jobs, watch run duration, success or failure and whether the output landed on time.
Cost is part of health. Track compute per thousand predictions, storage for logs and features, and the cost of retraining. A change that adds 2 percent accuracy but triples cost may not be worth it. Tools such as Prometheus and Grafana, or your cloud's monitoring service, handle these metrics. The DevOps with Python path covers dashboards and alerting in detail.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Check data quality at the input~35m
- 2Measure feature drift~35m
- 3Spot concept change~35m
- 4Track performance with delayed labels~35m
- 5Watch latency, errors and cost~35m
Key points
- Data quality checks catch broken pipelines before they reach the model.
- Input drift means the inputs changed; it does not prove the model got worse.
- Concept change means the link between inputs and outcomes changed, so the model is out of date.
- When labels arrive late, use drift and prediction distributions as early warnings and confirm with labelled metrics later.
- Every monitor needs a threshold, an owner and a written action, or it is just a chart.
Key terms
Tap a card to flip it. 0/6 known
Examples
import numpy as np
def psi(ref, cur, bins=10):
edges = np.quantile(ref, np.linspace(0, 1, bins + 1))
edges[0], edges[-1] = -np.inf, np.inf
r = np.histogram(ref, edges)[0] / len(ref)
c = np.histogram(cur, edges)[0] / len(cur)
r, c = np.clip(r, 1e-6, None), np.clip(c, 1e-6, None)
return float(np.sum((c - r) * np.log(c / r)))
# rule of thumb: under 0.1 stable, 0.1 to 0.25 watch, over 0.25 investigate
print(psi(train["monthly_spend"], last_week["monthly_spend"]))Population stability index for one numeric feature, using quantile bins from the reference data.
A drift report with PSI and KS on synthetic data
You trained a churn model on last year's data. This week, monthly_spend is higher because of a price change. Step 1: take the training column as reference and this week's column as current. Step 2: compute PSI and the KS statistic. Step 3: compare with your thresholds. Evidence you expect: PSI well above 0.25 and a large KS statistic for the shifted feature. Action: check whether the shift is real (prices rose) or a bug (cents instead of euros).
import numpy as np
from scipy.stats import ks_2samp
rng = np.random.default_rng(0)
ref = rng.normal(40, 10, 5000) # training monthly_spend
cur = rng.normal(48, 10, 2000) # this week, after a price rise
stat, p = ks_2samp(ref, cur)
print(f"KS statistic {stat:.3f}, p-value {p:.1e}")
print(f"PSI {psi(ref, cur):.3f}") # psi() from the explainer aboveMeasuring performance with delayed labels
Churn labels arrive 30 days after each prediction. Step 1: keep a prediction log with id, date, probability and model version. Step 2: each day, join outcomes that have matured. Step 3: compute recall per prediction week, plus label coverage. Step 4: compare with the recall from evaluation. A drop that persists for two mature weeks triggers a review. Weeks still inside the 30-day window are excluded, not counted as zero.
import pandas as pd
from sklearn.metrics import recall_score
preds = pd.read_parquet("logs/predictions.parquet") # id, date, proba, model_version
labels = pd.read_parquet("labels/churn_outcomes.parquet") # id, churned
cutoff = pd.Timestamp.today() - pd.Timedelta(days=30)
mature = preds[preds["date"] <= cutoff].merge(labels, on="id", how="left")
mature["week"] = mature["date"].dt.to_period("W")
for week, g in mature.groupby("week"):
known = g.dropna(subset=["churned"])
rec = recall_score(known["churned"], known["proba"] >= 0.5)
print(week, f"coverage {len(known)/len(g):.0%}", f"recall {rec:.2f}")Quick reference
- Monitor six things: data quality, input drift, concept change, labelled performance, service health, cost
- PSI rule of thumb: under 0.1 stable, 0.1 to 0.25 watch, over 0.25 investigate
- scipy.stats.ks_2samp compares two numeric samples; very sensitive on large data
- Drift is a warning, not proof the model is worse
- Log prediction id, time, model version so late labels can be joined
- Report labelled metrics by prediction cohort and track label coverage
- Every alert needs a threshold, an owner and a written action
Common mistakes
- Alerting on every drifted feature, so the team learns to ignore alerts.
- Assuming no drift means no problem; concept change can happen with identical inputs.
- Measuring accuracy on whatever labels arrived first, which are often a biased subset.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write three data quality assertions for a batch with columns tenure_months, monthly_spend and plan.
- Exercise 2medium
Compute PSI for every numeric feature between training data and last week's data, and print those above 0.25 sorted from highest.
- Exercise 3hard
Write a monitoring plan table for a churn model with labels 30 days late: for each of the six areas, give the signal, threshold, check frequency, owner role and action.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- What is the difference between data drift and concept drift?
- Data drift means the inputs look different from training data. Concept drift means the relationship between inputs and the right answer changed, even if the inputs look the same.
- Does drift always mean I must retrain?
- No. Drift is a reason to investigate. Retrain when labelled performance drops or when the drift is large in important features and you have evidence it hurts predictions.
- Which tools can I use for ML monitoring?
- You can start with pandas, SciPy and scheduled reports. Open-source libraries such as Evidently, and general tools such as Prometheus and Grafana for service metrics, add dashboards and alerts.