Sub topic 14
When the test set does not match the real world
This chapter assumes you can split data with train_test_split, know why the test set is used only once, and can read basic scikit-learn code. Here you will learn why a clean test score can still overstate how a model behaves after deployment.
The test set is only a sample of the past
A properly held-out test set tells you how the model performs on data drawn from the same source as the training data. That is a narrow promise. If production data comes from a different source, the test score answers a question nobody is asking.
This mismatch is called distribution shift. The distribution of the data seen in deployment differs from the distribution of the data used for training and testing. No amount of careful splitting fixes it, because the test rows share the training set's blind spots.
Common kinds of shift
| Kind | What changes | Example |
|---|---|---|
| Covariate shift | The input features, but not the relationship between features and label | A skin-lesion model trained on photos from one clinic is used with a different camera |
| Label shift | How often each class occurs | A fraud model trained when fraud was 1% of transactions faces a campaign where it is 10% |
| Concept drift | The relationship between features and label | Customers' spending habits change after a price rise, so the same features now mean something different |
In practice these overlap. You rarely know which one you have until you measure.
Checking for covariate shift with adversarial validation
If you have a sample of deployment features, you can test whether they differ from your training features. Train a classifier to tell the two sets apart. If it cannot beat chance, the sets look alike. If it can, they differ.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(0)
X_train = rng.normal(loc=0.0, scale=1.0, size=(500, 3))
X_deploy = rng.normal(loc=0.8, scale=1.0, size=(500, 3)) # shifted mean
X_all = np.vstack([X_train, X_deploy])
is_deploy = np.r_[np.zeros(500), np.ones(500)]
clf = RandomForestClassifier(n_estimators=100, random_state=0)
auc = cross_val_score(clf, X_all, is_deploy, cv=5, scoring="roc_auc").mean()
print(f"Train-vs-deploy AUC: {auc:.2f}")An AUC near 0.5 means the classifier cannot separate the sets. Here the AUC is well above 0.5, which signals shift. Feature importances from the fitted forest can then point to the features that moved.
This check only sees features. It cannot detect label shift or concept drift, because deployment data usually has no labels yet.
What to do about it
- Make the test set resemble deployment. Build it from the newest data, the target population, or the target devices, not a random sample of everything you have.
- Split by time or by source when the future will differ from the past. The earlier chapters on time-ordered and grouped splits apply directly.
- Monitor after release. Track input feature statistics, prediction rates, and accuracy once labels arrive. A falling metric is the only direct evidence of drift.
- Plan to retrain. Schedule retraining or set triggers, such as a drop in monitored accuracy.
Common mistakes
- Treating a random split of old data as a forecast of future performance.
- Re-tuning against the test set after seeing shifted results, which spends the test set and brings back the leakage problem.
- Ignoring shift because the training and test scores agree. They agree because they share the same source.
Exercise
A churn model scores 91% accuracy on a random held-out test set. Two months after launch, accuracy on newly labeled customers is 78%. The company changed its pricing between training and launch. Name the likely type of shift and one change to your evaluation that would have exposed the problem earlier.
Show answer
This is most likely concept drift, because the pricing change altered how customer features relate to churn. A time-based split would have exposed it earlier: train on older customers and test on the most recent ones. Monitoring accuracy on newly labeled customers after launch would also have caught it.