
Random Splits Lie on Time Series and Grouped Data
- كاتب موثّق
- scikit-learn 1.9
محتويات المقال
The common misconception
It's the default in tutorials, and train_test_splitshuffles unless you tell it not to.Shuffling is often presented as good hygiene. scikit-learn's guide does say it can be essential when rows are sorted, for example by class. Every row is tested exactly once, so the method feels thorough and fair.
What actually happens
Groups: the model recognizes the person
import numpy as npfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import KFold, cross_val_scorerng = np.random.default_rng(2)patient = np.repeat(np.arange(60), 20) # 60 patients, 20 recordings eachy = (rng.random(60) < 0.5)[patient] # diagnosis, one per patientX = rng.normal(size=(60, 10))[patient] # each patient's own signatureX = X + 0.3 * rng.normal(size=(1200, 10)) # recording-to-recording noiseX[:, :2] += y[:, None] # the real, weaker sign of the conditionmodel = RandomForestClassifier(random_state=0)cv = KFold(5, shuffle=True, random_state=0) # rows dealt out at randomprint(f"accuracy {cross_val_score(model, X, y, cv=cv).mean():.3f}")# accuracy 0.985import numpy as npfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.model_selection import GroupKFold, cross_val_scorerng = np.random.default_rng(2)patient = np.repeat(np.arange(60), 20)y = (rng.random(60) < 0.5)[patient]X = rng.normal(size=(60, 10))[patient]X = X + 0.3 * rng.normal(size=(1200, 10))X[:, :2] += y[:, None]model = RandomForestClassifier(random_state=0)cv = GroupKFold(5) # all of a patient's recordings in one foldscores = cross_val_score(model, X, y, cv=cv, groups=patient)print(f"accuracy {scores.mean():.3f}")# accuracy 0.686GroupKFold guarantees that no patient appears in both the training and validation side of a fold, so the 0.686 answers the question the pilot asks: how well does it work on someone new? It also shows what the dataset really is: the diagnosis is decided once per patient, so you have 60 examples of sick or healthy people, not 1,200. Kapoor and Narayanan list this non-independence between training and test data as its own type of leakage, with a histopathology study that put different observations of the same patient on both sides.
Time: the model fills gaps instead of forecasting
import numpy as npfrom sklearn.ensemble import RandomForestRegressorfrom sklearn.linear_model import LinearRegressionfrom sklearn.model_selection import KFold, TimeSeriesSplit, cross_val_scorerng = np.random.default_rng(1)sales = 100 + np.cumsum(rng.normal(0.1, 2, 1010)) # a growing shopX = np.column_stack([sales[i:i + 1000] for i in range(7)]) # last 7 daysy = sales[7:1007] # the next day's salessplits = {"shuffled": KFold(5, shuffle=True, random_state=0), "forward": TimeSeriesSplit(5)}models = {"forest": RandomForestRegressor(random_state=0), "linear": LinearRegression()}for split_name, cv in splits.items(): for model_name, model in models.items(): mae = -cross_val_score(model, X, y, cv=cv, scoring="neg_mean_absolute_error").mean() print(f"{split_name:<8} {model_name}: MAE {mae:.2f}")# shuffled forest: MAE 1.73# shuffled linear: MAE 1.58# forward forest: MAE 5.48# forward linear: MAE 1.69TimeSeriesSplit always trains on the past and tests on the next stretch, with training sets that grow fold by fold. Note that plain cv=5 without shuffling doesn't fix this: it still trains on the future in every fold but the last. This isn't a toy problem either: Kapoor and Narayanan define temporal leakage as a test set holding data from before the training data, and found K-fold cross-validation on temporal data among the errors in the civil war prediction papers they tried to reproduce.
KFold or StratifiedKFold | ||
GroupKFold or StratifiedGroupKFold | ||
GroupShuffleSplit | ||
TimeSeriesSplit, with a gap if windows overlap | ||
How to apply it in your project
Name what production sends New patients, next month's orders, a new store? Write down the unit the model must generalize to. Find the dependency in the data Look for an identifier that repeats, such as a patient, user, device or session, and for a timestamp. Pick the matching splitter Pass groups=toGroupKFoldorStratifiedGroupKFold, or sort by time and useTimeSeriesSplit.Hold out the test set the same way Keep unseen groups or the latest period for the final test. Google's Rules of ML: train on data up to a date, test on data after it. Compare against the shuffled score A big drop from the shuffled score to the grouped or forward one measures how much the model was memorizing.
Key takeaways
Shuffled K-fold assumes independent rows; repeated subjects and time series break that assumption. Grouped data: 0.985 with shuffled folds, 0.686 when each patient stayed in one fold. Time series: shuffled folds hid that a forest's forecast error was 5.48, not 1.73. Split the way production meets new data: GroupKFoldfor new groups,TimeSeriesSplitfor the future.
📚 المصادر
Cross-validation: evaluating estimator performance — scikit-learn User Guide TimeSeriesSplit — scikit-learn API Reference Visualizing cross-validation behavior in scikit-learn — scikit-learn examples Kapoor and Narayanan, Leakage and the Reproducibility Crisis in ML-based Science (2022) Rules of Machine Learning — Google for Developers
التعليقات (0)