Sub topic 6
Choosing reference data and comparison windows
Every drift test compares two samples: a reference and a current window. The test only measures the difference between those two samples. If you pick a poor reference, you will get alerts that mean nothing, or you will miss real drift. This chapter covers how to choose both samples.
It assumes you can compute a two-sample test such as Kolmogorov-Smirnov (KS) on a numeric column. It also assumes you know the three kinds of drift from the previous chapter. The tests themselves come in the next chapter.
What the reference represents
The reference is the data that defines "normal" for your model. A drift alert says "the current data differs from the reference." That is only useful if the reference is what you actually care about being similar to.
There are three common choices.
- Training data. This is the data the model learned from. A difference from it means the model is being asked about inputs it has not seen in that proportion.
- A validation or early-production slice. This is a period after launch that you checked by hand and found healthy. It reflects real serving conditions, including pipeline quirks that training data lacks.
- A recent past window. This is the previous day, week, or month. A difference from it means something changed lately.
None of these is correct in every case. Each answers a different question, so choose by deciding which question you want the alert to answer.
Fixed versus rolling references
A fixed reference stays the same for the life of a model version. A rolling reference moves forward with time, for example "the 7 days before the current window."
| Property | Fixed reference | Rolling reference |
|---|---|---|
| Question answered | Has the data moved away from what the model was built for? | Did something change recently? |
| Slow, gradual drift | Detected, because the gap accumulates | Often missed, because each step is small |
| Sudden break (a bad deploy upstream) | Detected | Detected, then the alert fades as the reference absorbs the broken data |
| Seasonality | Flags every season change as drift | Mostly absorbs it, except around turning points |
| Alert noise over time | Rises until you retrain, and then stays high | Stays roughly level |
| Maintenance | Reset on each retrain | None, but the baseline silently changes |
The main weakness of a rolling reference is that it adapts to the problem. If a source system degrades slowly over three months, each week looks similar to the one before it, and no alert fires. The main weakness of a fixed reference is that it eventually alerts all the time. Once the world has legitimately moved on, the alert carries no new information.
Many teams run both. The fixed reference gives a slow, cumulative signal. The rolling reference gives a fast signal for sudden changes.
The following code shows the difference. It simulates a feature whose mean rises by 0.01 standard deviations per day, then compares each weekly window to both kinds of reference.
import numpy as np
import pandas as pd
from scipy.stats import ks_2samp
rng = np.random.default_rng(0)
# 63 days of data, 200 rows per day, slow upward drift in the mean
rows = []
for day in range(63):
rows.append(pd.DataFrame({
"day": day,
"x": rng.normal(loc=0.01 * day, scale=1.0, size=200),
}))
df = pd.concat(rows, ignore_index=True)
df["week"] = df["day"] // 7
# Fixed reference: the first two weeks, standing in for training data
fixed_ref = df.loc[df["week"] < 2, "x"].to_numpy()
print("week KS vs fixed KS vs previous week")
for week in range(2, 9):
current = df.loc[df["week"] == week, "x"].to_numpy()
previous = df.loc[df["week"] == week - 1, "x"].to_numpy()
d_fixed = ks_2samp(fixed_ref, current).statistic
d_prev = ks_2samp(previous, current).statistic
print(f"{week:>4} {d_fixed:>11.3f} {d_prev:>18.3f}")The statistic against the fixed reference grows from week to week, because the gap accumulates. The statistic against the previous week stays near the level you would expect from sampling noise, because each step is only about 0.07 standard deviations. Exact values depend on the seed, but the pattern holds.
Choosing the comparison window
The comparison window (also called the current window) is the batch of production data you test against the reference. Its size and alignment matter as much as the reference.
Window size
Window size is a trade-off between speed and statistical power.
- A small window (an hour, a few hundred rows) reacts quickly but gives noisy statistics. A KS test on 50 rows cannot detect a small shift.
- A large window (a month, millions of rows) gives stable statistics, but it dilutes a recent problem. A bug that started yesterday is 1 day out of 30.
- With very large windows, tests become too sensitive. A p-value will flag differences that are real but harmless. The next chapter returns to this.
A workable approach is to pick the shortest window that holds enough rows for the test, then check it against your expected detection delay. As a rough guide, aim for at least a few hundred rows per window for numeric features. For categorical features, you need enough rows that every category has an expected count of about five or more.
Window alignment
Windows can be tumbling (non-overlapping: Monday, Tuesday, Wednesday) or sliding (overlapping: the last 24 hours, recomputed every hour). Tumbling windows are simple and each row is counted once. Sliding windows react faster but produce correlated results, so consecutive alerts are not independent evidence.
Match the population
The reference and current window must describe the same population, or the comparison says nothing. Common mismatches:
- Traffic mix. If a marketing campaign sends a different set of customers, drift is real but expected. Compare within segments (for example by region or channel) if you can.
- Filtering. If training data excluded rows that production still serves, such as nulls, outliers, or a market, the two samples differ by construction.
- Preprocessing. Compare the model inputs after the same transformations. Comparing raw training data to scaled production features will always flag drift.
- Sampling. If you only log a sample of production requests, check the sampling is random and not biased toward certain users.
Handling seasonality
Many features follow daily, weekly, or yearly cycles. Traffic at 3 a.m. differs from traffic at 3 p.m., and weekends differ from weekdays. If the reference is a Monday and the current window is a Saturday, you will see drift every week.
Match the cycle:
- For daily cycles, compare windows that cover whole days, not partial days.
- For weekly cycles, compare a full week to a full week, or the same weekday to the same weekday.
- For yearly cycles, use the same period one year earlier as the reference, if you have it. For a model that has been live for less than a year, you may not have enough history. In that case, note the limitation and rely on the performance layer, covered later in this tutorial.
Keeping the reference clean
A reference is only useful if it is representative and healthy. Before you freeze it:
- Run the data quality checks on it (schema, missing values, ranges). A reference with a broken column makes the real data look like drift.
- Remove known incidents. If an outage produced a day of default values, exclude that day.
- Check the sample is large enough that its own sampling noise is small relative to the shifts you care about.
- Save it. Store the reference sample, or its summary statistics and bin edges, with a version tag tied to the model version. Without a stored reference, you cannot reproduce an old alert.
Refresh the reference when you retrain the model, since the new model learned from newer data. Do not refresh it automatically on every alert. If a reference resets whenever drift is flagged, it behaves like a rolling reference and hides gradual change.
A decision guide
The diagram summarizes how to pick between the options.
Common mistakes
- Using training data as the reference without checking it matches serving. Training data is often cleaned and filtered in ways production is not.
- Comparing windows of very different sizes. The smaller sample's noise dominates, and tests behave differently at different sizes.
- Letting the rolling reference include the problem. If the previous window already contains the broken data, the comparison looks clean.
- Ignoring segments. An average shift of zero can hide opposite shifts in two segments.
- Changing the reference without recording it. You can no longer compare alerts across time.
Exercises
Exercise
A feature drifts slowly, rising a little each week for six months. Your monitor compares each week to the previous week and has never alerted. Why, and what is a simple fix?
Show answer
Each weekly step is small, so week-versus-previous-week differences stay within noise, while the total change over six months is large. The rolling reference absorbs the change as it happens. Add a fixed reference, such as the training data or a vetted launch period, and test the current window against that too. The accumulated gap will show up there.
Exercise
Your model sees much higher traffic on weekends. You compare each Saturday to the preceding Friday and get a drift alert every week. What change to the reference or window would remove these false alarms?
Show answer
Align the windows to the weekly cycle. Compare each Saturday to the previous Saturday, or compare a full week to a full week. Matching the same point in the cycle removes the expected weekday-versus-weekend difference, so only unusual changes remain.