الانتقال إلى المحتوى
Machine Learningتقييم الموديلات· 7 دقائق للقراءة

Random Splits Lie on Time Series and Grouped Data

Shuffled K-fold assumes independent rows. With repeated patients or time-ordered data, split the way production will see new data.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • scikit-learn 1.9
محتويات المقال

A health-tech startup detects a condition from one-minute sensor recordings: 60 volunteers, 20 recordings each. A random forest scores 0.985 in shuffled 5-fold cross-validation, and the pilot with new patients is planned around that number. The pilot goes far worse. Re-evaluated with each volunteer's recordings kept in a single fold, the same model scores 0.686. It's better than chance, but most of the 0.985 was the model recognizing people it had already met.

The common misconception

Many developers treat shuffled K-fold as a valid evaluation for any dataset. It's an easy belief to hold:

  • It's the default in tutorials, and train_test_split shuffles 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.

The half-truth: K-fold is a sound estimator when rows are independent. It answers "how well will the model do on new rows like these?" With groups or time, the rows production sends aren't like a random slice of your table.

What actually happens

Cross-validation simulates deployment: train on what you'd have, test on what you'd meet. A random split simulates a world where tomorrow's rows are random draws from the same pool as yesterday's, the assumption. scikit-learn's guide notes that this assumption rarely holds in practice, and recommends time-aware splits for data generated over time and group-wise splits for data collected from different subjects, experiments or devices.

Groups: the model recognizes the person

Each patient's recordings share a personal signature: body shape, sensor placement, habits. Shuffle the rows and every validation fold holds recordings from patients whose other recordings are in training. A flexible model learns "this signature belongs to a sick patient" and looks brilliant. The script gives each patient a random signature and adds a real but weaker sign of the condition:

Python
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.985

GroupKFold 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

Time series have : days next to each other look alike. Shuffle them and each test day sits between training days from just before and just after it, so the model interpolates. scikit-learn's guide warns that shuffling time-ordered data inflates the validation score for exactly this reason. The script forecasts a growing shop's daily sales from the last seven days, with a random forest and a linear model:

Python
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.69

Shuffled, the two models look close: 1.73 against 1.58. Forward, the forest's error triples to 5.48 while the linear model barely moves, 1.69. A tree can only predict values in the range it saw in training, and a growing shop keeps reaching sales levels it has never had. Shuffling hid that, because every test day had training days at the same level around it. TimeSeriesSplit 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.

Your dataProduction asks aboutUse
Independent rows, no time effectNew rows like theseKFold or StratifiedKFold
Several rows per patient, user or deviceNew groupsGroupKFold or StratifiedGroupKFold
One holdout set with groupsNew groupsGroupShuffleSplit
Time-ordered observationsThe futureTimeSeriesSplit, with a gap if windows overlap
Groups observed over timeNew groups in the futureSplit by date, and keep test groups out of training

How to apply it in your project

  1. Name what production sendsNew patients, next month's orders, a new store? Write down the unit the model must generalize to.
  2. Find the dependency in the dataLook for an identifier that repeats, such as a patient, user, device or session, and for a timestamp.
  3. Pick the matching splitterPass groups= to GroupKFold or StratifiedGroupKFold, or sort by time and use TimeSeriesSplit.
  4. Hold out the test set the same wayKeep 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.
  5. Compare against the shuffled scoreA 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: GroupKFold for new groups, TimeSeriesSplit for the future.

📚 المصادر

  1. Cross-validation: evaluating estimator performance — scikit-learn User Guide
  2. TimeSeriesSplit — scikit-learn API Reference
  3. Visualizing cross-validation behavior in scikit-learn — scikit-learn examples
  4. Kapoor and Narayanan, Leakage and the Reproducibility Crisis in ML-based Science (2022)
  5. Rules of Machine Learning — Google for Developers

التعليقات (0)