Sub topic 14
When the Test Set Does Not Match the Real World
This chapter assumes you can already build a train/validation/test split in scikit-learn, and that you know what data leakage is and why a test set stays untouched. Here we look at a different failure. Your split can be done correctly and your test score can be honest, and the model can still do worse in production. The cause is that the test set is a sample of the data you collected, not a sample of the data the model will see.
What a test score actually promises
A held-out test score estimates performance on new rows drawn from the same distribution as the training rows. That is the assumption behind random splitting. Each row is treated as an independent draw from one fixed process, so a random 20% is a fair stand-in for future data.
Deployment can break that assumption in several ways:
- The inputs change. Customers, sensors, or images look different from your collection.
- The class balance changes.
- The relationship between inputs and labels changes.
- Your dataset was never a fair sample of the target population.
In each case the test score is accurate for the world you sampled and optimistic for the world you serve.
Kinds of shift
Distribution shift is a general term. The kinds below fail differently and need different responses.
| Kind | What changes | Example | Typical symptom |
|---|---|---|---|
| Covariate shift | The distribution of features, P(x). The rule from x to y stays the same. | A skin-lesion model trained on light skin is deployed to a clinic with darker-skinned patients. | Errors concentrate in regions of feature space that were rare in training. |
| Label (prior) shift | The class proportions, P(y). | A fraud model trained when fraud was 0.5% of transactions faces a 3% fraud wave. | Precision falls, and probability outputs become miscalibrated. |
| Concept drift | The rule from x to y, P(y given x). | "Spam" changes as spammers adapt. A price model meets a new market regime. | Accuracy decays over time even when inputs look familiar. |
| Sampling or selection bias | How rows entered the dataset. | You only have outcomes for loan applicants you approved. | The test set shares the training set's blind spots, so it cannot reveal them. |
The last row is the most dangerous. A random split of a biased sample gives you a biased test set. The score looks fine and nothing in the data warns you.
Watching covariate shift happen
The example below keeps the labeling rule fixed and changes only where the inputs fall. The training data only covers x between 0 and 3. In that range the true rule "label 1 when |x| < 2" looks like a simple threshold at x = 2, which a linear model can learn. At deployment, x also covers negative values, and the rule is no longer a single threshold.
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
def label(x):
return (np.abs(x) < 2).astype(int)
# Collected data: x only covers 0 to 3.
X = rng.uniform(0, 3, size=(2000, 1))
y = label(X[:, 0])
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
model = LogisticRegression().fit(X_train, y_train)
# Deployment: x covers -3 to 3, with the same labeling rule.
X_live = rng.uniform(-3, 3, size=(2000, 1))
y_live = label(X_live[:, 0])
print("Test accuracy:", model.score(X_test, y_test))
print("Live accuracy:", model.score(X_live, y_live))The test accuracy is close to 1.0. The live accuracy is noticeably lower, around 0.8, because the model labels everything in the unseen region from -3 to -2 as class 1. Nothing was leaked and the split was correct. The test set simply never contained the region where the model fails.
Notice what did not change: the labeling rule. Covariate shift hurts here because the model is misspecified, since a linear model cannot represent the full rule. A flexible model with enough data in the new region would not suffer. In practice every model is somewhat misspecified, so shift usually costs something.
Detecting shift before it costs you
If you have unlabeled examples of deployment data, you can test whether your training data resembles them. You do not need labels for this.
Adversarial validation
Train a classifier to tell training rows from deployment rows. If it cannot beat chance, the two sets look alike. If it separates them well, they differ, and its feature importances show which features differ.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from scipy.stats import ks_2samp
rng = np.random.default_rng(0)
X_train = rng.uniform(0, 3, size=(1600, 1))
X_live = rng.uniform(-3, 3, size=(2000, 1))
# Label each row by where it came from: 0 = training, 1 = deployment.
X_all = np.vstack([X_train, X_live])
origin = np.r_[np.zeros(len(X_train)), np.ones(len(X_live))]
detector = RandomForestClassifier(n_estimators=100, random_state=0)
auc = cross_val_score(detector, X_all, origin, cv=5, scoring="roc_auc").mean()
print("Origin-detector AUC:", round(auc, 3))
# Per-feature check: two-sample Kolmogorov-Smirnov test.
stat, p_value = ks_2samp(X_train[:, 0], X_live[:, 0])
print("KS statistic:", round(stat, 3), "p-value:", p_value)An AUC near 0.5 means the detector cannot tell the sets apart. Here it lands well above 0.5, because any row with negative x is obviously from deployment. The Kolmogorov-Smirnov test compares one feature's distribution between the two samples. A large statistic with a tiny p-value flags that feature.
Limits of these checks
- With large samples, tiny and harmless differences become statistically significant. Look at the effect size (the KS statistic, the AUC), not only the p-value.
- Per-feature tests miss shifts in combinations of features. Adversarial validation catches those, but it needs enough rows and a sensible model.
- Neither method detects label shift or concept drift, because those need labels. Both show up only when you compare predictions to outcomes.
Failure modes to check for
- A random split of a time-dependent dataset. The test rows come from the same period as the training rows, so the score ignores drift. Use a time-ordered split (the previous chapter) and expect a lower, more honest number.
- A convenience sample. Data from one hospital, one country, or one app version is a fine training set and a poor claim about everyone else. State the population your test score covers.
- Train and test built by different pipelines. If training labels come from careful annotation and production inputs come from a noisy sensor, the shift is built in. Evaluate on data produced the way production data will be.
- Slicing by overall score only. An aggregate accuracy can hide a subgroup where the model fails. Report metrics per region, device, segment, or time window.
- Tuning against the deployment data. Once you use shifted data to select models, it is a validation set and no longer an unseen check. Keep a final slice untouched, as with any test set.
What you can do about it
No technique removes the problem. The options below trade effort against how much of the gap they close.
- Build the evaluation set to look like deployment. If you know the target population, sample or collect a test set from it, even a small one. A few hundred realistic labeled rows can be worth more than thousands of convenient ones.
- Use time-based or group-based splits. They simulate "future" and "new entity" conditions, which are the usual form of shift.
- Stress-test on slices. Evaluate on rare regions, edge cases, and subgroups on purpose.
- Reweight training data. For covariate shift, the adversarial detector's probabilities can be turned into importance weights, so training rows that resemble deployment count more. This helps only where the two distributions overlap. It cannot teach the model a region it never saw, like x below 0 in the example above.
- Collect more data in the missing region. When the shift is a coverage gap, this is the direct fix.
- Monitor after launch. Track input distributions, prediction distributions, and, when labels arrive, live accuracy. Set alerts, and plan to retrain on recent data.
Summary of decision rules
- If the data has a time order, split by time and expect drift.
- If you have unlabeled deployment data, run adversarial validation before trusting the test score.
- If the population is broader than your sample, say so, and gather a test set from the target population.
- Report scores per slice, not only overall.
- After launch, compare predictions with real outcomes on a schedule.
Exercise
A team trains a churn model on 2022 customer data using a random 80/20 split and gets 0.91 accuracy on the test set. In production in 2024 the accuracy is 0.78. A colleague says the test set must have been leaked. Give two other explanations, and say what check you would run for each.
Show answer
First, concept drift: customer behavior or pricing changed between 2022 and 2024, so the rule from features to churn changed. Check by re-evaluating on a time-ordered split (train on early months, test on later months) and by comparing live predictions with outcomes over time. Second, covariate shift or a changed customer mix: the 2024 customers differ from 2022 customers (new plans, new regions). Check by running adversarial validation between the 2022 training features and the 2024 features, and by reporting accuracy per customer segment. A random split puts 2022 rows in both the training and test sets, so it cannot reveal either problem, and leakage is not needed to explain the gap.