Sub topic 14
Detecting data drift and concept drift
This chapter assumes you can train and evaluate a supervised model in Python, know basic Git and the command line, and have a general idea of how a web service is deployed. You should also have met production monitoring from the previous chapter: logging inputs and predictions, and tracking latency and error rates.
Why a model's accuracy decays
A model is trained on a snapshot of the world. Production keeps moving after the snapshot is taken. Customers change behavior, sensors age, upstream teams rename columns, and seasons turn. The model's code and weights do not change, yet its predictions get worse. This is the main reason ML systems need monitoring that ordinary software does not.
Two terms cover most of the problem:
- Data drift (also called covariate shift) is a change in the distribution of the inputs, P(X). The model sees feature values it rarely or never saw in training.
- Concept drift is a change in the relationship between inputs and the target, P(y | X). The same inputs now deserve different answers.
A related case is label drift (prior shift), where the share of each class, P(y), changes. A fraud model sees the same transaction patterns, but fraud becomes twice as common.
| Type | What changes | Example | Needs labels to detect? |
|---|---|---|---|
| Data drift | Input distribution P(X) | Average customer age rises after a marketing campaign | No |
| Concept drift | Relationship P(y given X) | A pandemic changes what a "normal" purchase pattern means | Yes, usually |
| Label drift | Class balance P(y) | Fraud rate doubles | Yes, or a proxy |
| Data quality break | Pipeline produces wrong values | A unit changes from meters to feet, or a field becomes null | No |
The last row is not drift in the statistical sense, but it shows up in the same detectors, and it is the most common cause of sudden alerts. Check for it first.
Data drift does not always hurt
Data drift is a signal, not a verdict. If a feature the model barely uses shifts, accuracy may not change. If the shift stays inside the range the model learned well, the damage may be small. Conversely, a model can lose accuracy with no input drift at all, which is concept drift.
Treat drift detection as an early warning. It tells you where to look. Only performance metrics tell you whether the model is actually failing.
Detecting data drift with a statistical test
The standard approach compares a reference window (usually the training data) with a current window (recent production inputs), one feature at a time. For a numeric feature, a two-sample Kolmogorov-Smirnov (KS) test measures the largest gap between the two empirical cumulative distributions. It returns a statistic (the gap, from 0 to 1) and a p-value.
import numpy as np
from scipy.stats import ks_2samp
rng = np.random.default_rng(0)
reference = rng.normal(loc=0.0, scale=1.0, size=5000) # feature values seen at training time
live_same = rng.normal(loc=0.0, scale=1.0, size=5000) # production data, unchanged
live_shifted = rng.normal(loc=0.5, scale=1.0, size=5000) # production data after a shift
for name, live in [("same", live_same), ("shifted", live_shifted)]:
result = ks_2samp(reference, live)
drifted = result.pvalue < 0.01
print(name, round(result.statistic, 3), "drift" if drifted else "no drift")The unchanged sample produces a small statistic and no alert. The sample with its mean shifted by half a standard deviation produces a statistic near 0.2 and a p-value far below 0.01, so it is flagged.
Other common choices:
- Population Stability Index (PSI) bins a feature and sums the differences in bin proportions. Teams in credit risk often use thresholds of about 0.1 (watch) and 0.25 (act).
- Jensen-Shannon divergence or Wasserstein distance give a distance rather than a yes/no test, which is easier to chart.
- Chi-squared test suits categorical features.
- Domain classifier: train a classifier to tell reference rows from current rows. If it succeeds (AUC well above 0.5), the windows differ, and its feature importances show how.
Gotchas with p-values
With large samples, a p-value flags tiny, harmless shifts. With 5,000 or more rows per window, nearly any real difference becomes "significant". Alert on the effect size (the KS statistic, PSI, or a distance) as well as the p-value, and choose thresholds from history rather than from a textbook.
Testing many features also creates false alarms. If you test 200 features at 0.01, expect about two alerts per window by chance alone. Apply a correction such as Bonferroni, or alert only when a fraction of features drift together or when a high-importance feature drifts.
Window design matters too. A reference window that is too small is noisy. A current window that is too small cannot detect anything. A window spanning a weekly cycle will drift every weekend unless the reference covers the same cycle.
Detecting concept drift
Concept drift cannot be seen in the inputs alone. You need evidence about the outcomes. There are three practical routes.
- Delayed ground truth. When labels arrive (a loan defaults, a user clicks or does not), join them to the logged predictions and compute accuracy, precision, recall or error on a rolling window. This is the most direct signal. Its weakness is delay: for some problems labels take weeks or months.
- Prediction and confidence monitoring. Track the distribution of model outputs. A shift in the average predicted probability, or in the share of low-confidence predictions, is a label-free proxy. It is imperfect, because a stable output distribution can hide errors.
- Error-based drift detectors. Algorithms such as DDM and ADWIN watch the stream of errors and signal when the error rate rises beyond what chance explains. They need labels, but they work on a stream without fixed windows.
Compare the live metric against the offline value measured at release time, and against the release criteria you set earlier. A drop below the floor in your release gate is a natural alert threshold.
Wiring detection into a monitoring job
A drift check usually runs as a scheduled job, for example daily, as part of the pipeline. A minimal version loops over features, applies the test, and returns a report that an alerting system can consume.
import numpy as np
from scipy.stats import ks_2samp
def drift_report(reference, current, min_stat=0.1, alpha=0.01):
"""Return {feature: (statistic, pvalue, drifted)} for columns of two 2D arrays."""
n_features = reference.shape[1]
corrected_alpha = alpha / n_features # Bonferroni correction
report = {}
for i in range(n_features):
result = ks_2samp(reference[:, i], current[:, i])
drifted = result.pvalue < corrected_alpha and result.statistic >= min_stat
report[f"feature_{i}"] = (round(result.statistic, 3), result.pvalue, drifted)
return report
rng = np.random.default_rng(1)
reference = rng.normal(size=(4000, 3))
current = rng.normal(size=(4000, 3))
current[:, 2] += 0.6 # only the third feature shifts
for name, (stat, p, drifted) in drift_report(reference, current).items():
print(name, stat, "drift" if drifted else "ok")The function requires both a corrected p-value and a minimum effect size, which addresses the two gotchas above. Only feature_2 is reported as drifted.
Edge cases and failure modes
- Gradual versus sudden drift. A sudden break (a broken pipeline) trips a threshold at once. Slow drift can stay under the threshold each day while the total shift becomes large. Compare against the training reference as well as against last week.
- Seasonality. Holiday traffic looks like drift. Use a reference from the same season, or model the seasonal pattern.
- Feedback loops. If the model's decisions shape future data (it approves only some loans, so you only observe outcomes for those), labels become biased and drift estimates mislead.
- Missing and unseen categories. New category values are drift that numeric tests miss. Track the share of unseen values and of nulls per feature.
- Multivariate drift. Each feature can look stable while their relationship changes. Per-feature tests miss this. A domain classifier or a check on correlations can catch it.
- Alert fatigue. Too many alerts teach people to ignore them. Prioritize by feature importance and by performance impact.
From detection to a decision
Detection feeds the next stage. A drift alert should lead to a triage with a small set of outcomes: fix the data pipeline, wait and watch, recalibrate the output, retrain on newer data, or roll back to an earlier model version. The next chapter covers retraining triggers and strategies in more detail. For now, record each alert, its cause and its outcome. Over a few months this history shows which thresholds are useful and which only add noise.
Exercise
A churn model's input features show a significant KS test result (p < 0.001) on 3 of 40 features, but the KS statistics are all about 0.03, and labeled outcomes over the same period show accuracy unchanged from release. What do you conclude, and what would you change in the monitoring setup?
Show answer
The shifts are statistically significant only because the samples are large. A KS statistic of 0.03 is a tiny effect, and unchanged accuracy confirms no practical harm, so do not retrain. Change the alert rule to require a minimum effect size (for example a statistic of at least 0.1, or PSI above 0.1) in addition to the p-value, and apply a multiple-testing correction across the 40 features. Keep logging the results so a slow trend would still be visible.
Exercise
A fraud model's input distributions are stable, but its precision, measured on confirmed labels that arrive after 30 days, has fallen from 0.85 to 0.70. Which type of drift is this, and why did input monitoring miss it?
Show answer
This is concept drift: the relationship between inputs and the fraud label changed (for example, fraudsters adopted behavior that looks like normal activity). Input monitoring only compares P(X), which did not change, so it cannot see a change in P(y given X). Only outcome-based metrics detect it, and here they lag by 30 days. To shorten the delay, add proxy metrics such as the score distribution and sample cases for faster manual labeling.