Sub topic 13
Splitting Time-Ordered Data
This chapter assumes you can already use train_test_split, know why a test set must stay untouched, and have seen cross_val_score with k-fold splitting. It also assumes you know what data leakage is (information from outside the training data influencing the model). Here you will see why random splits break down when rows have an order in time, and how to build splits that respect it.
Why random splits fail on time-ordered data
A random split assumes rows are interchangeable. Any row could be in training or in testing, and nothing is lost by shuffling. Time-ordered data breaks that assumption in two ways.
- Neighbours are similar. Today's sensor reading, price or user count looks like yesterday's. If yesterday is in training and today is in the test set, the model only has to interpolate between values it has already seen.
- The future is not available in deployment. A deployed forecaster only has the past when it predicts. A random split lets training rows come from after the test rows, so the model is evaluated under conditions it will never meet.
Both problems are forms of leakage. The test score is optimistic because the training set contains information about the test period. The fix is to make the evaluation match deployment. Train on the past, test on the future, and never let that order be reversed.
The chronological holdout
The simplest valid split sorts the rows by time and cuts at a point. Everything before the cut is training data, and everything after is the test set. There is no shuffling and no train_test_split, which shuffles by default.
The example below builds a series with a trend and a seasonal wave. Each row's features are the three previous values, and the target is the next value. It then compares a random split with a chronological one.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 300
t = np.arange(n)
y = 0.05 * t + 5 * np.sin(t / 10) + rng.normal(0, 0.5, n)
# Row i uses y[i], y[i+1], y[i+2] to predict y[i+3].
X = np.column_stack([y[:-3], y[1:-2], y[2:-1]])
target = y[3:]
# Random split: test rows sit between training rows.
Xr_train, Xr_test, yr_train, yr_test = train_test_split(
X, target, test_size=0.2, random_state=0
)
model = Ridge().fit(Xr_train, yr_train)
print("Random split MAE:", mean_absolute_error(yr_test, model.predict(Xr_test)))
# Chronological split: the last 20% of rows are the test set.
cut = int(len(X) * 0.8)
Xc_train, Xc_test = X[:cut], X[cut:]
yc_train, yc_test = target[:cut], target[cut:]
model = Ridge().fit(Xc_train, yc_train)
print("Chronological MAE:", mean_absolute_error(yc_test, model.predict(Xc_test)))The random split usually reports the smaller error. That error is the less honest of the two, because the chronological split is the one that resembles forecasting.
Rows must be sorted by time before you cut. If your table is not already in time order, sort it by the timestamp column first. Cutting an unsorted table gives you an arbitrary split that merely looks chronological.
Overlap at the boundary
Even a chronological cut can leak when rows overlap in time. This happens in two common ways.
- Lag and window features. In the example above, the last training row has a target
y[cut+2], and the first test row usesy[cut],y[cut+1]andy[cut+2]as features. The test features contain the training target, so the two sets share raw observations. - Long-horizon targets. If the label is "did the customer churn within 30 days?", a training row from 10 days before the cut has a label that depends on events inside the test period.
The remedy is a gap, a stretch of rows dropped between training and test. Make the gap at least as long as the longest window or horizon that a row's features or label look across. For the lag-3 features above, a gap of a few rows is enough. For a 30-day label, the gap should be 30 days.
Cross-validation that respects order
A single holdout gives one estimate from one period. It can be noisy, and the period may be unusual. Ordinary k-fold cross-validation cannot fix this, because it shuffles or interleaves rows and puts future rows in training folds. Scikit-learn provides TimeSeriesSplit for this case.
TimeSeriesSplit makes an expanding window. Each fold trains on everything up to a point and tests on the block right after it. Later folds have more training data.
You can print the indices to confirm that every test index is larger than every training index. The gap argument drops that many rows between the two sides.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(12).reshape(-1, 1)
print("No gap:")
for train_idx, test_idx in TimeSeriesSplit(n_splits=3).split(X):
print("train", train_idx, "test", test_idx)
print("Gap of 1:")
for train_idx, test_idx in TimeSeriesSplit(n_splits=3, gap=1).split(X):
print("train", train_idx, "test", test_idx)With 12 rows and 3 splits, each test block has 3 rows (12 // (3 + 1)). With the gap of 1, the first fold trains on rows 0 and 1 and tests on rows 3 to 5, so row 2 is skipped.
Two properties differ from ordinary k-fold:
- The earliest rows never appear in a test set. The first block is only ever training data.
- Early folds train on little data. Fold 1 scores may be worse simply because the model saw less. Look at the trend across folds, not only the mean.
You can pass TimeSeriesSplit anywhere a cv argument is accepted, including cross_val_score and GridSearchCV. Combine it with a pipeline so that preprocessing is refit inside each fold, as in the earlier chapter on pipelines.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
n = 300
t = np.arange(n)
y = 0.05 * t + 5 * np.sin(t / 10) + rng.normal(0, 0.5, n)
X = np.column_stack([y[:-3], y[1:-2], y[2:-1]])
target = y[3:]
cut = int(len(X) * 0.8)
X_train, X_test = X[:cut], X[cut:]
y_train, y_test = target[:cut], target[cut:]
model = make_pipeline(StandardScaler(), Ridge())
cv = TimeSeriesSplit(n_splits=5, gap=3)
scores = cross_val_score(
model, X_train, y_train, cv=cv, scoring="neg_mean_absolute_error"
)
print("Fold MAE:", -scores)
print("Mean CV MAE:", -scores.mean())
model.fit(X_train, y_train)
test_pred = model.predict(X_test)
print("Test MAE:", np.mean(np.abs(y_test - test_pred)))The structure matches the earlier validation workflow. The test set is cut off first and stays untouched while you compare models with cross-validation on the training part. It is scored once at the end.
Choosing a splitter
| Situation | Splitter | Note |
|---|---|---|
| Rows are independent and exchangeable | `train_test_split`, `StratifiedKFold` | Random order is fine. |
| Rows belong to entities (patients, users) | `GroupKFold` | Keeps each entity on one side. |
| Rows are ordered in time and you forecast forward | `TimeSeriesSplit` or a chronological cut | Training always precedes testing. |
| Features or labels span a window of rows | Add `gap` | Gap at least as long as the window. |
| Several entities, each with a time series | Split by time and keep entities together as needed | Decide which one you must generalize to: new periods, new entities, or both. |
The last row of the table needs a decision before you choose a method. If the model will score new customers in the future, then neither a pure time split nor a pure group split fully matches deployment.
Common errors
- Shuffling by default.
train_test_splitshuffles unless you passshuffle=False. For a simple chronological holdout,train_test_split(X, y, test_size=0.2, shuffle=False)works on sorted data, but slicing by index makes the cut explicit and is easier to review. Also note thatstratifycannot be combined withshuffle=False. KFold(shuffle=True)on a time series. It mixes the future into training folds. Scores look fine and the model fails after deployment.- Scaling or imputing on the full series. Means and standard deviations from the test period leak backward. Fit them on training rows only, which a pipeline does for you.
- Tuning on the final test block, then reporting it. The same discipline applies as for any test set. Each look at the test score that influences a decision uses up some of its honesty.
- Reporting only the mean fold score. Look at the individual folds. If error rises steadily in later folds, the data is changing over time, which connects to the next chapter on distribution shift.
Check your understanding
Exercise
You are predicting next-week sales per store. Each row has features computed from the previous 28 days, and the label is the sales of the following 7 days. You split chronologically at 1 March, with training rows before and test rows after. Why can this still leak, and what would you change?
Show answer
Rows near the cut overlap. A training row from late February has a label covering days after 1 March, and a test row from early March has features built from late-February days. The training labels and test features therefore share raw observations. Add a gap between the two sets that is at least as long as the longest window involved (28 days for the features, and 7 days for the label horizon), and make sure the last training row's label period ends before the first test row's feature window begins. In cross-validation, pass the same gap to TimeSeriesSplit.
Exercise
A colleague evaluates a demand forecaster with crossvalscore(model, X, y, cv=KFold(nsplits=5, shuffle=True, randomstate=0)) and reports a cross-validated error far below the error seen in production. Give two reasons the estimate is too optimistic, and name a replacement for the cv argument.
Show answer
First, shuffled folds put rows from after the test rows into the training folds, so the model is trained on the future relative to what it is tested on, which never happens in production. Second, neighbouring rows are similar, so a test row has near-duplicate training rows on both sides, and the model only has to interpolate. Replace the cv argument with TimeSeriesSplit (adding a gap if features or labels span several rows) so that every test block comes after its training rows.