Validate models on time-ordered or grouped data
scikit-learn 1.9.1
Avoid training on the future or on records from the same entity as the evaluation rows.
On this page
Keep training before evaluation
In forecasting, a shuffled split can allow future observations into training. Sort by time and validate against later observations. TimeSeriesSplit expands training windows and can leave a gap before evaluation. Standard folds assume evenly spaced observations for comparable time intervals.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
rows = np.arange(8)
for train, test in TimeSeriesSplit(n_splits=2, test_size=2, gap=1).split(rows):
print(train[-1], test[0])
Example output
2 4 4 6
Keep each entity in one fold at a time
If several rows share a customer, order, or session, group by that entity. GroupKFold keeps test groups disjoint from train groups in each split. Choose the group that matches what will be new at prediction time.