Sub topic 13
Splitting time-ordered data
This chapter assumes you know train_test_split, the role of a validation set, and what data leakage is. You should also be able to read a scikit-learn pipeline.
Why random splits fail on time data
A random split mixes past and future rows. Suppose you predict tomorrow's sales. With a random split, the model trains on Wednesday and Friday and is tested on Thursday. In deployment it never sees the future, so this setup leaks information. Neighboring rows are also strongly correlated, so a test row often has a near-twin in the training set. The score looks better than the model deserves.
The rule is simple: every training row must come earlier than every test row. This matches how the model will be used.
A chronological holdout
First sort the rows by time. Then cut at a point in time and keep the latest rows as the test set. Do not shuffle.
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(42)
n = 300
t = np.arange(n)
X = np.column_stack([t, np.sin(t / 10)])
y = 0.05 * t + 2 * np.sin(t / 10) + rng.normal(0, 0.5, n)
cut = int(n * 0.8)
X_dev, X_test = X[:cut], X[cut:]
y_dev, y_test = y[:cut], y[cut:]
model = make_pipeline(StandardScaler(), Ridge())
cv = TimeSeriesSplit(n_splits=5, gap=5)
scores = cross_val_score(model, X_dev, y_dev, cv=cv, scoring="r2")
print("CV R2 per fold:", scores.round(3))
model.fit(X_dev, y_dev)
print("Test R2:", round(model.score(X_test, y_test), 3))The first 80% of the rows is the development set, which you use for model selection. The last 20% is the test set, and you touch it once at the end.
Cross-validation that respects order
TimeSeriesSplit is a forward-chaining cross-validator. Each fold trains on an initial stretch of the data and tests on the block right after it. The training window grows with each fold.
The gap argument skips rows between the training and test blocks. It matters when features look back or ahead in time. For example, a 5-day rolling mean in the last training rows may overlap the first test rows. A gap at least as large as your look-back or forecast horizon removes that overlap.
You can check the ordering yourself:
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(12).reshape(-1, 1)
for train_idx, test_idx in TimeSeriesSplit(n_splits=3).split(X):
print("train", train_idx, "test", test_idx)The output shows train rows 0-2 with test rows 3-5, then train rows 0-5 with test rows 6-8, then train rows 0-8 with test rows 9-11. Every test index is larger than every training index in the same fold.
Common errors
- Shuffling. Passing
shuffle=Trueto a splitter, or usingKFold(shuffle=True), destroys the order. - Features built from the future. A rolling mean, a lag, or a "next-day" label computed over the whole dataset before splitting can include test-period values. Build such features with only past rows.
- Scaling on everything. Fit scalers and encoders on training rows only. Keep them inside the pipeline, as in the example.
- Early folds that are too small. The first fold trains on very little data, so its score is noisy. Look at the trend across folds instead of trusting one number.
- Ignoring the shift. If the process changes over time, older data may describe it badly. The last folds are usually the best guide to current performance.
Exercise
A teammate computes a 7-day rolling average of sales over the full dataset, then runs TimeSeriesSplit on the result. The CV scores look excellent. What is wrong, and how would you fix it?
Show answer
The rolling average for rows near a fold boundary uses values from the other side of the boundary. Test-period information therefore reaches the training features, which is leakage. Fix it by computing the rolling average using only past values (a trailing window per row), and set gap to at least 7 so the training and test windows do not overlap. Ideally, build the features inside a pipeline step so they are recomputed correctly on each training fold.