MLDay 45 of 50ML in Production
Validate for Production Data
Cross-validation says your bike-rental model misses by about 42 rentals an hour.
Cross-validation says your bike-rental model misses by about 42 rentals an hour. Replay the last four months of 2012 as if they were the future, and it misses by 68. Same model, same data: only the split changed.
The idea
A validation score is only honest if the test rows relate to the training rows the way tomorrow's data will relate to today's. Production data breaks the random split in two ways.
Time. In use, the model always predicts rows that come after everything it learned from. A random split
hides future rows in training, so the model fills gaps instead of forecasting
(Day 6).
scikit-learn's TimeSeriesSplit turns this into cross-validation
(Day 10).
It cuts the time-ordered rows into 6 nearly equal parts, and each fold trains on the past and tests on the next part:
| Fold | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|
| Train on parts | 1 | 1–2 | 1–3 | 1–4 | 1–5 |
| Test on part | 2 | 3 | 4 | 5 | 6 |
Groups. Rows often come in bundles that share a hidden cause: the hours of one day share its weather and
events, and the rows of one customer share their habits. Call each bundle a group. If some of a group's
rows sit in training, the model has already met the group. GroupKFold keeps every group whole: each group's
rows all land in the same test fold.
A third gap no split can show: train–serving skew, when a feature means something different in training than in the live service. This data has the recorded temperature of each hour. A service that plans tomorrow only has a forecast, so the score you measure is better than the one you'll get. Train on what the service will really see.
Before you trust a score, run this leakage audit:
- Is every feature known at the moment you predict?
- Is every preprocessing step fitted inside the folds, in a
Pipeline(Day 11)? - Does the split match the job: future rows, unseen groups, or both?
- Do copies of the same row appear in both training and test?
- Will the service compute each feature the same way, from the same source?
- Is the test set used once, at the end?
A tiny example
Two days at one dock. Tuesday was rainy.
| Hour | 7 am | 8 am | 9 am |
|---|---|---|---|
| Monday | 300 | 520 | 410 |
| Tuesday | 120 | 210 | 160 |
A random fold tests Tuesday 8 am but trains on Tuesday 7 am and 9 am. Averaging those neighbours gives
(120 + 160) / 2 = 140, a miss of 70. Now hold out all of Tuesday, as GroupKFold would. The closest known
hour is Monday 8 am, so the guess is 520, a miss of 310.
The first score is easy because it peeks at Tuesday. In production, when you plan Tuesday on Monday night, no Tuesday hour is known yet.
Try it
Sixteen months of rentals: test on the future
The line is fitted on the training rows only. The test rows are the exam it never studied for: their RMSE is the honest score.
training row (12)test row (4)
train RMSE 32.67test RMSE 109.66test is 76.98 worse
These are the real monthly averages from the data. It starts on Split by time: the test is September to December 2012, when rentals fall from 304 to 167 an hour. The line learned a year of growth and keeps climbing, so the test RMSE is about 110 against 33 in training. Switch to Random split and the test RMSE drops to 44. No random split can show this: the line has never seen rentals turn down, just as fold 3's trees never saw 2012.
In code
This scores one model three ways: a HistGradientBoostingRegressor (boosted trees, from
Day 25) on
Day 8's 12
features. Phase 5's credit data has one row per customer and no dates, so it has no time order or groups to split on;
the bike-share hours have both. Only the cv splitter changes. GroupKFold takes the date of each row as its group.
# script_id: day_045_production_validation/three_cvs
import os
from pathlib import Path
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.model_selection import GroupKFold, KFold, TimeSeriesSplit, cross_val_score
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets"))
df = pd.read_csv(DATA_DIR / "bike_sharing" / "hour.csv", parse_dates=["dteday"])
features = ["season", "yr", "mnth", "hr", "holiday", "weekday", "workingday",
"weathersit", "temp", "atemp", "hum", "windspeed"]
X, y, days = df[features], df["cnt"], df["dteday"] # rows are in time order
model = HistGradientBoostingRegressor(random_state=42)
splits = {
"random KFold": (KFold(5, shuffle=True, random_state=42), None),
"GroupKFold by day": (GroupKFold(5), days),
"TimeSeriesSplit": (TimeSeriesSplit(5), None),
}
for name, (cv, groups) in splits.items():
rmse = -cross_val_score(model, X, y, groups=groups, cv=cv, scoring="neg_root_mean_squared_error")
print(f"{name:<18} mean {rmse.mean():5.1f} folds {rmse.round(1)}")
for fold, (train, test) in enumerate(TimeSeriesSplit(5).split(X), start=1):
print(f"fold {fold}: train {len(train):>6,} hours to {days[train[-1]]:%Y-%m-%d}, "
f"test {days[test[0]]:%Y-%m-%d} to {days[test[-1]]:%Y-%m-%d}")
random KFold mean 41.7 folds [40.9 41. 42.7 40.9 43.2]
GroupKFold by day mean 44.6 folds [46.9 44.6 43.6 44.7 43. ]
TimeSeriesSplit mean 74.5 folds [ 62.1 52.3 119.4 70.7 68.1]
fold 1: train 2,899 hours to 2011-05-05, test 2011-05-05 to 2011-09-03
fold 2: train 5,795 hours to 2011-09-03, test 2011-09-03 to 2012-01-02
fold 3: train 8,691 hours to 2012-01-02, test 2012-01-02 to 2012-05-02
fold 4: train 11,587 hours to 2012-05-02, test 2012-05-03 to 2012-08-31
fold 5: train 14,483 hours to 2012-08-31, test 2012-08-31 to 2012-12-31
Grouping by day costs 2.9 rentals: the weather columns already tell the model most of what a day's other hours
would. Time order costs far more, and the mean RMSE rises by about 80%. Fold 3 is the worst at 119.4. It trains on
2011 and two days of 2012, so it has barely seen yr = 1, and trees can't extend a trend they never saw. Rentals grew in 2012,
which is exactly what production looks like: the future isn't a copy of the past. Fold 5 is closest to the
real job, training on everything before September and missing by 68.1. Part of that is the season: random KFold
scores those same autumn hours at 51.8, so about 16 rentals an hour is the cost of not knowing the future. Early
folds also train on less data, which is one more reason fold 5 is the fairer number.
Quick check
Quick check
1. Random KFold tests Tuesday 8 am and trains on Tuesday 7 am. Why does that flatter the score?
2. TimeSeriesSplit(5) runs on rows sorted by time. What does fold 3 train and test on?
3. You trained on each hour's recorded temperature, but the live service only has yesterday's forecast. What is this?
Next
With a score you can trust, Day 46 puts the credit model behind an API that other programs can call.
Data: Bike Sharing Dataset (UCI Machine Learning Repository, dataset 275), CC BY 4.0; cite Fanaee-T, H. and Gama, J. (2013), "Event labeling combining ensemble detectors and background knowledge", Progress in Artificial Intelligence, doi:10.1007/s13748-013-0040-3.