Lesson 21 · Practical engineering
Evaluation you can trust
The problem
The pizza shop builds a model to predict delivery times, so it can tell customers when to expect their pizza. It's a linear regression on four features: distance, traffic, rain, and whether the order was sent in the rush (18:00 to 19:59).
The shop has a year of deliveries, 100 a month. It shuffles them, holds back a quarter, and scores the model on that quarter. The mean absolute error is 3.5 minutes. Good enough to launch.
But a model is used on the future. Suppose the shop had built it at the end of month 9 and used it for months 10 to 12. On those months its mean error is 5.9 minutes: two-thirds worse than the test said.
Nothing was wrong with the model's code. The evaluation didn't match how the model would be used. This lesson is about evaluations you can trust. It covers splits that match the job, how much one score wobbles, how test sets wear out, and why offline scores aren't the final word.
Split like you'll predict
The year's data has two features that matter here. Times creep up slowly, by about 0.4 minutes a month (the drivers' cars are getting older, say). And in month 10, the shop opens a second branch further out, on hillier roads.
Predict first
The same linear model is scored two ways: (a) a random quarter of all 12 months held out; (b) trained on months 1–9, tested on months 10–12. Which test error is lower?
Test error: 3.50 minutes. A random quarter of every month is held out. The model trains on the rest, including months 10–12.
Solid bars: test rows. Dashed outlines: training months (error on rows the model saw). Dashed line: overall test error.
Things to notice:
- Under the random split, months 10 to 12 are already worse: 4.4 to 5.6 minutes. One straight line can't fit both branches well. But those months are only a quarter of the test rows, so the overall 3.5 hides them.
- Under the time-based split, months 10 to 12 are worse still: 5.3 to 6.2 minutes. The model has never seen a delivery from the new branch.
- The random split's 3.5 answers a different question. It asks how well the model fills in gaps in a year it has already seen. Nobody needs that.
Training on earlier data and testing on later data is a time-based split. Use one whenever the model will predict the future: sales, demand, delivery times, prices, fraud. It's the same rule as the lesson on train, validation and test sets gave: the piles must look like the data the model will meet.
A random split here is a mild form of data leakage. Information from the future (the new branch, the slower months) reaches training. The model couldn't have had it on the day it was built.
Cross-validation through time
Cross-validation shuffles rows into folds, so it has the same problem. The time-ordered version keeps every validation fold after its training data:
| Fold | Train on rows | Validate on rows |
|---|---|---|
| 1 | 1–150 | 151–300 |
| 2 | 1–300 | 301–450 |
| 3 | 1–450 | 451–600 |
| 4 | 1–600 | 601–750 |
| 5 | 1–750 | 751–900 |
This is for the 900 deliveries of months 1 to 9, in time order. The training window grows, and each fold predicts the next block. scikit-learn calls this TimeSeriesSplit. Its five scores here average 3.01 minutes, close to the shuffled 2.96, because months 1 to 9 change slowly. The big shift comes in month 10, and no split of months 1 to 9 can see it coming. That's what monitoring is for (later in this lesson).
Groups: the same customer twice
The shop has about 150 customers, and each one orders about 8 times. Some regulars live up a long drive or always chat at the door. Their deliveries take a couple of minutes longer than the features say.
Predict first
Each customer appears in about 8 rows. You split rows at random into folds. Will the validation score be honest for a new customer?
Give a random forest the customer number as an extra feature, and score it two ways on months 1 to 9:
| Split | Mean error |
|---|---|
| Rows at random (customers on both sides) | 3.23 minutes |
| All of a customer's rows kept on one side | 3.44 minutes |
Keeping all of one group's rows on the same side of the split is a group split. scikit-learn calls it GroupKFold. Here the gap is small, because each regular's personal delay is only about 2 minutes. In medicine, where one patient can have dozens of scans, the gap can be the whole result.
Which split to use comes down to one question: what will be new when the model is used?
| When the model is used on… | Split by | scikit-learn |
|---|---|---|
| Rows like the training rows, independent of each other | Random rows | KFold, train_test_split |
| The future | Time | TimeSeriesSplit |
| New customers, patients, shops or drivers | Group | GroupKFold |
| New customers in the future | Time, then group | combine them by hand |
How much does one score wobble?
Every test score is an average over a sample of rows. A different sample gives a different number. As in the lesson on A/B testing, the question is how much of a gap is luck.
The figure runs 5-fold cross-validation on months 1 to 9, again and again, with a fresh shuffle each time. Same model, same data; only the shuffle changes.
Single folds: 2.60 to 3.24 minutes. 5-fold averages: 2.95 to 2.96.
Things to notice:
- Single folds spread from about 2.6 to 3.2 minutes. Each fold has only 180 deliveries. One 80/20 split is one of these dots.
- The averages barely move: 2.95 to 2.98 across 20 reshuffles in the code below. Averaging five folds cuts most of the noise.
- So a single split can mislead by a few tenths of a minute. If two models differ by less than that, one split can't tell them apart.
Some habits, as rules of thumb:
- Report the mean and the spread of the fold scores, not one number.
- Compare models on the same folds. Then the shuffle's luck hits both models alike, and their gap is steadier than either score.
- Treat a gap smaller than the fold-to-fold spread as a tie until other evidence says otherwise. Prefer the simpler model.
A test set wears out
The test set is meant to be opened once, at the end. In practice, people peek. They score a model on it, tweak, score again, and keep whatever does best. Each look leaks a little of the test set into the choice.
Here's an extreme case. Suppose late-or-not were a pure coin flip, so no model could beat 50% on new deliveries. You try one model after another and keep whichever scores best on the same 200 test deliveries.
After 1,000 models: the kept one scores 61.0% on the test set it was chosen on, and 50.0% on 10,000 fresh deliveries.
Things to notice:
- The test score climbs. It's 48% after one model, 58.5% after 100, and 61% after 1,000. Every one of those models is guessing.
- The fresh score stays at 50%. The "improvement" exists only on those 200 deliveries.
- It climbs fastest at the start. You don't need 1,000 tries to fool yourself; 20 get you to 56%.
This is overfitting, one level up. The model didn't fit the test set; you did, by choosing. The same thing happens with a validation set during hyperparameter search, which is why the final score comes from a separate test set.
Real projects aren't this extreme, because real models carry some signal. But the effect is the same in kind. A test set used for many decisions gets more optimistic with every one.
Dwork and colleagues studied this in "The reusable holdout" (Science, 2015) and proposed ways to reuse a holdout set more safely. Competition sites guard against it too. Kaggle shows a public leaderboard during a contest. But it ranks the final entries on a separate, private part of the test data.
Offline scores versus real results
A score on held-out data is an offline score. What happens after the model goes live is the online result. They can differ, for two reasons.
The first is that the world changes. Here are three candidate models, scored the way the shop would have scored them at the end of month 9, and then after launch:
■ offline: cross-validation on months 1–9 ■ after launch: months 10–12
Things to notice:
- Offline, the three are nearly tied: 2.91, 2.96 and 3.13 minutes. The gaps are about the size of the noise from the last section.
- After launch, they're far apart: 4.84, 5.88 and 6.97. And all three are much worse than their offline score.
- The model with the month as a feature does best after launch. It learned the slow upward trend and carries it forward. The forest can't predict anything outside the range of times it was trained on, so it does worst.
When the data a model meets in use differs from the data it was trained on, that's distribution shift. Here, the inputs moved: the new branch has longer trips. And the link between inputs and time moved too: hillier roads take 5.5 minutes per km instead of 4. A new menu, a new town, winter, a competitor opening next door: all of these shift the data.
The second reason is that the offline score isn't what the business cares about. The shop doesn't want low mean error for its own sake. It wants fewer angry phone calls and more repeat orders. A model with lower error might still annoy more people, for example if it's wrong mostly on the long trips where waiting hurts most.
The way to measure the real result is the one from the A/B testing lesson. Send a random half of orders through the new model and half through the old one, and compare the metric that matters. A better offline score earns a model the right to an A/B test, not a launch.
Watching after launch
Distribution shift can't be caught before launch: the new branch doesn't exist yet. So you watch the model in use. Track its inputs, its outputs and, when the true answers arrive, its errors, month by month.
The whole year. The first alert comes in month 10. Press play to watch it month by month. Month 12: mean distance 4.16 km, 37% of orders from the new branch, mean error 6.2 minutes. ⚠ Above the alert line.
Things to notice:
- Months 1 to 9 are quiet. Mean distance wanders between 3.2 and 3.7 km; the error stays near 3 minutes.
- In month 10, both jump. Mean distance rises to about 4 km and the error to 6.1 minutes, well over the alert line.
- The input moved first. Mean distance is known the moment an order comes in. The error needs the delivery to finish. Watching inputs gives a faster, if rougher, warning.
Pizza is easy: the true delivery time arrives within the hour. For many models the truth arrives late or never (did that loan get repaid? would this customer have left anyway?). Then input monitoring is all you have. The Serving and deployment course covers monitoring properly.
When the alert fires, the usual fix is to retrain on recent data, here including months 10 to 12. Check the new model with a time-based split, and confirm it with an A/B test.
Case studies
Google Flu Trends
From 2008, Google estimated how much flu there was in the US from the search terms people typed. In a 2014 article in Science, "The parable of Google Flu: traps in big data analysis", Lazer and colleagues described what went wrong.
- Fitting many candidates to few data points. The original method searched 50 million search terms for the best matches to 1,152 data points. The odds of finding terms that matched flu by coincidence were high. The authors write that the first version was "part flu detector, part winter detector".
- It missed the 2009 H1N1 pandemic, which came outside the usual winter season.
- It kept overestimating. It missed high in 100 out of 108 weeks starting in August 2011. In February 2013, Nature reported that it was predicting more than double the share of doctor visits for flu-like illness that the CDC measured.
- The world under it changed. Google kept changing its own search engine, for example by suggesting searches. That changed what people typed. The authors call this "algorithm dynamics": distribution shift caused by the system itself.
Lessons: an impressive fit on the past is not evidence about the future; and a model in use needs checking against an independent measure.
KDD Cup 2008: the patient ID that knew the answer
The KDD Cup 2008 competition asked teams to find breast cancer in mammogram data. The winning IBM team (Perlich and colleagues, 2008; Rosset and colleagues, 2010) found that the patient ID number predicted cancer. The IDs had been assigned in ranges that reflected where each patient's data came from. And the source was strongly linked to whether the patient had cancer.
A model using the ID could win the contest and be useless in a clinic, where a new patient's ID says nothing about her health. The team described the leak openly in their reports. This is data leakage by a group label, and a group split by data source would have exposed it.
Online experiments at Bing and Microsoft
Kohavi and Thomke describe experiments at Microsoft in "The surprising power of online experiments" (Harvard Business Review, 2017).
- Ideas mostly fail. At Google and Bing, only about 10% to 20% of experiments produce positive results. At Microsoft as a whole, about a third of ideas prove effective, a third are neutral and a third are negative. Expert judgement didn't pick the winners well.
- One small change, a big win. An idea to change how Bing showed ad headlines sat in the backlog for more than six months. When an engineer finally tested it, revenue rose so fast that an alert fired: results "too good to be true" usually mean a bug. This time it was real: a 12% revenue increase, worth more than $100 million a year in the US alone.
- Be sceptical of surprises. Kohavi, Tang and Xu name this rule in their book Trustworthy Online Controlled Experiments (2020). They call it Twyman's law: any figure that looks interesting or different is usually wrong. Check for bugs, then repeat the experiment.
Booking.com: better models, same business
Bernardi and colleagues wrote "150 successful machine learning models: 6 lessons learned at Booking.com" (KDD 2019). They measure each model's value with randomised experiments on business metrics. One of their main findings: a gain in a model's offline performance does not necessarily turn into a gain in business value. Offline evaluation, for them, is a health check. The A/B test decides.
The summer model and the first snow (a made-up example)
This one is invented, to show the pattern.
A pizza shop trains a delivery-time model from April to September and tests it with a random split: 3 minutes of error. In December, the first snow arrives. Every delivery takes 10 minutes longer, and the model has never seen snow. Its error triples overnight, and customers stop trusting the times.
A time-based test wouldn't have helped, because there was no snow in the data. But a monitor on the errors would have caught it in the first evening.
Pitfalls checklist
The mistakes that cost the most, roughly in order:
- A random split on data that will be used to predict the future. Use a time-based split.
- The same customer, patient or device on both sides of the split. Use a group split.
- Leakage: a feature or preprocessing step that uses information not available at prediction time (see data leakage and pipelines).
- Reusing the test set until it's a second validation set. Reporting the best of many test runs.
- Trusting one split. Report the spread across folds; compare models on the same folds.
- Optimising a metric nobody cares about. Check that the offline metric tracks the business goal, for example recall on late pizzas, or calibrated probabilities if you quote them to customers.
- Launching without an A/B test, when you could run one.
- No monitoring after launch. Watch inputs, outputs and errors, and set alerts.
In scikit-learn
The data, in time order:
rows = load("deliveries-year")["rows"] # already in time order: month 1 first
month = np.array([row["month"] for row in rows])
customer = np.array([row["customer"] for row in rows])
x = np.array(
[[row["distance_km"], row["traffic"], row["rain"], int(18 <= row["hour"] <= 19)] for row in rows],
dtype=float,
) # (1200, 4): km, traffic level, rain, rush hour
minutes = np.array([row["minutes"] for row in rows])
print(f"{len(rows)} deliveries over {month.max()} months")Random split against time-based split:
# Random split: shuffle all 12 months together, test on a random quarter.
x_tr, x_te, y_tr, y_te = train_test_split(x, minutes, test_size=0.25, random_state=0)
random_mae = mean_absolute_error(y_te, LinearRegression().fit(x_tr, y_tr).predict(x_te))
# Time-based split: train on months 1-9, test on months 10-12, as the model would be used.
past, future = month <= 9, month >= 10
model = LinearRegression().fit(x[past], minutes[past])
time_mae = mean_absolute_error(minutes[future], model.predict(x[future]))
print(f"random split: MAE {random_mae:.2f} minutes") # 3.50
print(f"time-based split: MAE {time_mae:.2f} minutes") # 5.88random split: MAE 3.50 minutes
time-based split: MAE 5.88 minutesShuffled folds against forward-chaining folds, and how much the shuffle matters:
# Months 1-9 only: what you'd have on the day you choose a model.
x9, y9, c9 = x[past], minutes[past], customer[past]
mae = "neg_mean_absolute_error" # scikit-learn maximises scores, so errors come negated
shuffled = -cross_val_score(LinearRegression(), x9, y9, cv=KFold(5, shuffle=True, random_state=0), scoring=mae)
forward = -cross_val_score(LinearRegression(), x9, y9, cv=TimeSeriesSplit(n_splits=5), scoring=mae)
print("KFold (shuffled) folds:", shuffled.round(2), f"mean {shuffled.mean():.2f}")
print("TimeSeriesSplit folds: ", forward.round(2), f"mean {forward.mean():.2f}")
# The same 5-fold score with 20 different shuffles: how much does the average move?
means = [-cross_val_score(LinearRegression(), x9, y9, cv=KFold(5, shuffle=True, random_state=s), scoring=mae).mean()
for s in range(20)]
print(f"20 reshuffles: mean MAE from {min(means):.3f} to {max(means):.3f}")KFold (shuffled) folds: [3.14 2.95 3.05 2.74 2.92] mean 2.96
TimeSeriesSplit folds: [2.92 3. 2.68 3.15 3.28] mean 3.01
20 reshuffles: mean MAE from 2.951 to 2.977TimeSeriesSplitassumes the rows are already in time order. Sort them first.KFold(shuffle=True)needs arandom_stateto give the same folds every run. Withoutshuffle=Trueit cuts the rows in order, which on time-sorted data is neither a random split nor a forward one.- Scorers follow "higher is better", so errors come back negated (
neg_mean_absolute_error); flip the sign.
Group split:
# A forest that can see the customer number can learn each regular's personal speed.
forest = RandomForestRegressor(n_estimators=100, random_state=0)
with_id = np.column_stack([x9, c9])
rows_split = -cross_val_score(forest, with_id, y9, cv=KFold(5, shuffle=True, random_state=0), scoring=mae).mean()
by_customer = -cross_val_score(forest, with_id, y9, cv=GroupKFold(n_splits=5), groups=c9, scoring=mae).mean()
print(f"rows split at random: MAE {rows_split:.2f}") # 3.23: same customers on both sides
print(f"customers kept together: MAE {by_customer:.2f}") # 3.44: what a new customer getsrows split at random: MAE 3.23
customers kept together: MAE 3.44GroupKFold takes a groups array, one group label per row, and never splits a group. StratifiedGroupKFold also keeps class shares even.
Offline against after launch:
candidates = {
"linear": (LinearRegression(), x),
"linear + month": (LinearRegression(), np.column_stack([x, month])),
"random forest": (RandomForestRegressor(n_estimators=100, min_samples_leaf=3, random_state=0), x),
}
for name, (est, features) in candidates.items():
offline = -cross_val_score(est, features[past], minutes[past], cv=KFold(5, shuffle=True, random_state=0),
scoring=mae).mean()
online = mean_absolute_error(minutes[future], est.fit(features[past], minutes[past]).predict(features[future]))
print(f"{name:15s} offline (months 1-9, CV) {offline:.2f} after launch (months 10-12) {online:.2f}")linear offline (months 1-9, CV) 2.96 after launch (months 10-12) 5.88
linear + month offline (months 1-9, CV) 2.91 after launch (months 10-12) 4.84
random forest offline (months 1-9, CV) 3.13 after launch (months 10-12) 6.97And the reused test set, in NumPy:
rng = np.random.default_rng(0)
def reuse_test_set(tries: int, n_test: int = 200, n_fresh: int = 10_000) -> tuple[float, float]:
"""Late or not is a coin flip, so no model can beat 50%. Try `tries` models; keep the best on the test set.
Returns the kept model's test accuracy and its accuracy on fresh deliveries.
"""
test_labels = rng.integers(0, 2, n_test)
guesses = rng.integers(0, 2, (tries, n_test)) # each model's predictions: no better than guessing
test_acc = (guesses == test_labels).mean(axis=1)
fresh_acc = rng.binomial(n_fresh, 0.5) / n_fresh # any model scores about 50% on new data
return float(test_acc.max()), float(fresh_acc)
for tries in [1, 10, 100, 1000]:
test_acc, fresh_acc = reuse_test_set(tries)
print(f"best of {tries:4d} on the test set: {test_acc:.1%} on fresh data: {fresh_acc:.1%}")best of 1 on the test set: 54.5% on fresh data: 50.3%
best of 10 on the test set: 56.5% on fresh data: 50.0%
best of 100 on the test set: 58.5% on fresh data: 50.7%
best of 1000 on the test set: 62.0% on fresh data: 51.0%The numbers differ a little from the figure's, because the random draws differ. The pattern is the same.
Putting it together
How the shop should have evaluated its delivery-time model:
- Ask what will be new in use. The future, and some new customers. So split by time, and keep customers together where it matters.
- Cross-validate through time on the data you have (
TimeSeriesSplit), and report the mean and spread of the fold scores. - Compare candidates on the same folds. Treat small gaps as ties: the three models here were within 0.2 minutes.
- Open the test set once. Here, months 10 to 12 would have been the test, and they'd have shown the problem: 5.9 minutes, not 3.
- Confirm with an A/B test on the metric the shop cares about, such as complaints about late pizzas.
- Monitor after launch. Mean distance and error both jumped in month 10. An alert would have fired in the first month of the new branch.
Common misconceptions
"A random split is always the fair choice." It's fair only when the rows the model will meet look like randomly chosen training rows. For the future, it was too hopeful by 2.4 minutes.
"A high test score means the model will work." It means the model worked on that test set, under those conditions. After the new branch opened, every model's error rose by about two-thirds or more.
"If I only look at the test score, I haven't trained on it." Every decision based on it leaks a little. Picking the best of 1,000 guessers on one test set gave 61% where the truth was 50%.
"Cross-validation gives the true score." It gives an estimate with its own noise. Single folds here ranged from 2.6 to 3.2 minutes.
"Better offline means better in the business." Offline, the three models were within 0.2 minutes. After launch they were 2.1 minutes apart, and Booking.com found that offline gains don't necessarily turn into business gains. Test online.
"Once it's launched and tested, it's done." Data drifts. Watch inputs and errors, and retrain when they move.
Recap
- Split the way the model will be used. Use a time-based split to predict the future, and a group split for new customers or patients.
TimeSeriesSplitis cross-validation through time: each fold validates on the block after its training data.- One split's score wobbles. Report the spread across folds, compare models on the same folds, and treat small gaps as ties.
- A test set used for many decisions becomes too optimistic. Open it once.
- Distribution shift makes offline scores too hopeful; and the offline metric isn't the business goal. Confirm with an A/B test.
- After launch, monitor inputs, outputs and errors, with alerts.
- scikit-learn names in this lesson:
train_test_split,KFold,TimeSeriesSplit,GroupKFold,StratifiedGroupKFold,cross_val_score,LinearRegression,RandomForestRegressorandmean_absolute_error.