Sub topic 7
Detecting data and prediction drift
This chapter assumes you know how to compute classification metrics, can read pandas and scikit-learn code, and have a prediction log with one row per scored case and its timestamp. It also assumes you have read the earlier chapters on the monitoring gap and on label-free proxy signals. Drift detection is the most common of those proxies.
What drift detection tells you
When labels arrive late, you cannot compute accuracy or AUC on this week's predictions. Drift detection answers a narrower question: has the data the model sees now stopped looking like the data it was evaluated on? If not, a result from the reference period probably still holds. If so, you should investigate and possibly switch to the estimation methods in the next chapters.
Drift detection does not measure performance. A model can be robust to a large shift, and it can fail badly with no visible shift. Treat a drift alarm as a prompt to look, not as proof of damage.
Kinds of drift
Three quantities can change, and they need different handling.
| Name | What changes | Visible without labels? |
|---|---|---|
| Covariate shift (data drift) | The distribution of inputs, P(x) | Yes |
| Prediction drift | The distribution of model outputs, P(score) | Yes |
| Label (prior) shift | The class rate, P(y) | Only indirectly |
| Concept drift | The relationship P(y given x) | No |
Concept drift is the dangerous one, because it changes the correct answer for the same input. A fraud model whose fraudsters adopt new tactics suffers concept drift. No test on features or scores can see it directly. You detect it only through late labels, which is why the final chapters cover backtesting and reconciliation.
Choosing a reference and a window
Every drift test compares two samples, and the choice of samples matters more than the choice of test.
- Reference: usually the validation set, or a recent period when you know the model performed well. A reference from training data can be stale or filtered differently from production.
- Current window: large enough for the test to have power, small enough to react. For a daily batch with thousands of rows, a day or a week is common. With a small window, noise triggers alarms.
- Seasonality: if traffic has weekly cycles, compare Monday with a reference of Mondays, or use a window that covers whole cycles. Otherwise the weekend triggers an alarm every week.
Univariate tests for features
Run one test per feature, using a test that fits the feature type.
- Kolmogorov–Smirnov (KS) test for continuous features. It measures the largest gap between the two empirical distributions.
- Chi-squared test for categorical features, applied to the table of category counts.
- Population Stability Index (PSI), a score from credit risk. It sums the differences between bin proportions weighted by the log ratio. A common rule of thumb reads below 0.1 as stable, 0.1 to 0.25 as moderate, and above 0.25 as large. These thresholds are conventions, not statistics.
The code below implements PSI and runs both PSI and KS on a simulated shift.
import numpy as np
from scipy.stats import ks_2samp
def psi(reference, current, bins=10, eps=1e-4):
"""Population Stability Index with bins from reference quantiles."""
reference = np.asarray(reference, dtype=float)
current = np.asarray(current, dtype=float)
inner = np.unique(np.quantile(reference, np.linspace(0, 1, bins + 1))[1:-1])
def fractions(x):
idx = np.searchsorted(inner, x, side="right")
counts = np.bincount(idx, minlength=len(inner) + 1)
return np.clip(counts / len(x), eps, None)
ref_f, cur_f = fractions(reference), fractions(current)
return float(np.sum((cur_f - ref_f) * np.log(cur_f / ref_f)))
rng = np.random.default_rng(0)
reference = rng.normal(0.0, 1.0, 5000)
stable = rng.normal(0.0, 1.0, 2000)
shifted = rng.normal(0.4, 1.0, 2000)
for name, current in [("stable", stable), ("shifted", shifted)]:
stat = ks_2samp(reference, current)
print(f"{name}: PSI={psi(reference, current):.3f} "
f"KS={stat.statistic:.3f} p={stat.pvalue:.2g}")Bin edges come from the reference only, so the comparison stays fixed over time. The eps clip avoids a division by zero or a log of zero when a bin is empty.
Statistical significance versus practical size
With 100,000 rows, the KS test flags differences too small to affect the model, because p-values shrink as sample size grows. With 200 rows, it misses real shifts. Prefer an effect-size measure such as the KS statistic or PSI, and set thresholds from your own history: compute the statistic between pairs of past windows that you know were fine, and alarm above the upper range of those values.
Many features, many false alarms
If you test 100 features at a 5% significance level, you expect about five false alarms per window even with no drift. Options include a stricter threshold (Bonferroni or Benjamini–Hochberg correction), alarming only when several features move, or ranking features by effect size and watching the top few. Weight attention toward features the model relies on, using feature importance from training.
Multivariate drift with a domain classifier
Per-feature tests miss shifts in the relationships between features. Two features can each keep their usual distribution while their correlation flips. A domain classifier catches this. Label reference rows 0 and current rows 1, train a model to tell them apart, and measure its ROC AUC on held-out predictions. An AUC near 0.5 means the two samples are indistinguishable. A high AUC means they differ, and the classifier's feature importances show where.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, cross_val_predict
def domain_classifier_auc(ref: pd.DataFrame, cur: pd.DataFrame, seed=0):
X = pd.concat([ref, cur], ignore_index=True)
y = np.r_[np.zeros(len(ref)), np.ones(len(cur))]
clf = RandomForestClassifier(n_estimators=200, min_samples_leaf=10,
random_state=seed, n_jobs=-1)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=seed)
proba = cross_val_predict(clf, X, y, cv=cv, method="predict_proba")[:, 1]
auc = roc_auc_score(y, proba)
importances = pd.Series(
clf.fit(X, y).feature_importances_, index=X.columns
).sort_values(ascending=False)
return auc, importances
rng = np.random.default_rng(1)
n = 3000
ref = pd.DataFrame({"a": rng.normal(size=n)})
ref["b"] = ref["a"] + rng.normal(scale=0.3, size=n) # b tracks a
cur = pd.DataFrame({"a": rng.normal(size=n)})
cur["b"] = -cur["a"] + rng.normal(scale=0.3, size=n) # relationship flipped
auc, imp = domain_classifier_auc(ref, cur)
print(f"domain AUC = {auc:.2f}")
print(imp)Here each column has the same marginal distribution in both samples, so univariate tests stay quiet, but the domain AUC is close to 1. Use cross-validated predictions as shown. Scoring the classifier on its own training rows overstates the AUC. The same classifier is the first step of importance weighting, which a later chapter builds on.
Prediction drift
Compare the distribution of model scores, or of the predicted class rate, between reference and current windows. Use the same tools: PSI or KS on the scores, and a comparison of the positive-call rate at your decision threshold.
Prediction drift is often the most useful single alarm. It is one number for the whole model, and it reflects the features the model weights most. Its limits matter:
- A score shift can reflect a real change in the population, such as more risky applicants. In that case, the model may be working correctly.
- A model can fail with a stable score distribution. If concept drift swaps which cases are risky while the overall mix of scores stays the same, the score histogram looks unchanged.
- Upstream bugs show up here too. A feature that becomes null, gets a new unit, or is silently imputed often moves the score distribution first.
Common errors
- Using a p-value alone. Large windows make trivial shifts significant. Pair it with an effect size.
- A moving reference. If the reference is always last week, slow drift never alarms, because each week resembles the one before. Keep a fixed reference and sometimes a rolling one, and read both.
- Ignoring missing values. A rising null rate is drift. Track it as its own metric before running tests on the filled values.
- Mixing up scales. Compute bins and category lists from the reference, and handle unseen categories explicitly, for example by pooling them into an "other" bucket.
- Treating no alarm as good news. No drift detected means the inputs look familiar. It says nothing about concept drift.
From alarms to action
A practical setup keeps three layers. First, cheap per-feature and per-score checks run on every window with thresholds calibrated from history. Second, a domain classifier runs daily or weekly as a multivariate check. Third, when either layer fires, you move to a performance estimate, such as calibrated-probability estimation or importance weighting, and finally compare against late labels when they mature. The last chapter of this tutorial covers how to combine these into one alerting policy.
Exercise
A model's 50 input features each pass a KS test at p > 0.05 for the current week, yet a domain classifier trained to separate reference rows from current rows reaches a cross-validated AUC of 0.93. Name one likely cause, one way to locate it, and say whether the model's accuracy has necessarily dropped.
Show answer
Likely cause: the joint structure changed (for example, the correlation between two features flipped, or a new combination of values appeared) while each marginal distribution stayed the same, so univariate tests cannot see it. Locate it by reading the domain classifier's feature importances, then inspecting the top features' pairwise relationships or partial dependence. Accuracy has not necessarily dropped: the shift may fall in a region the model handles well, or may not involve the relationship the model relies on. A drift signal calls for a performance estimate or late labels, not a conclusion about accuracy.