The same shoppers appear in train and validation folds. What breaks?
Question
A shop predicts whether a shopper buys again next week. Each row is one shopper in one week: the average basket in euros and the number of visits. Six shoppers, A to F, have two rows each. The rows are sorted by week.
A teammate runs 3-fold cross-validation with plain KFold and a 1-nearest-neighbour model. Every fold scores 1.0.
The model will score shoppers it has never seen. Is 1.0 a fair estimate? What is wrong, and how do you fix the split?
import numpy as np from sklearn.model_selection import KFold, cross_val_score from sklearn.neighbors import KNeighborsClassifier users = np.array(list("ABCDEF") * 2) # week 1: A to F, then week 2 X = np.array([[31, 2], [19, 5], [44, 1], [26, 4], [52, 3], [38, 6], [33, 2], [18, 6], [45, 2], [27, 3], [50, 3], [37, 5]]) y = np.array([0, 1, 0, 1, 0, 1] * 2) # 1 = buys again next week model = KNeighborsClassifier(n_neighbors=1) scores = cross_val_score(model, X, y, cv=KFold(n_splits=3)) print(scores) # [1. 1. 1.]
Show hints (3)
- "WHO IS NEAREST"
Look at shopper A:
[31, 2]in week 1 and[33, 2]in week 2. For A's week 2 row, which training row will a 1-nearest-neighbour model pick? - "WHERE THE TWIN IS"
Without shuffling,
KFoldcuts the 12 rows into 3 blocks of 4, in order. When A's week 1 row is in validation, where is its week 2 row? - "SPLIT BY SHOPPER"
Keep all rows of one shopper on the same side.
GroupKFoldwithgroups=usersdoes that. Expect a lower score, and trust it more.
Show checked explanation
Each shopper has two very similar rows, and plain KFold puts one in training and the other in validation. The model just finds the same shopper's other week, so it scores 1.0. That tests recognizing known shoppers, not predicting new ones. Split by shopper with GroupKFold: the mean score drops to 0.67.
import numpy as np from sklearn.model_selection import GroupKFold, KFold, cross_val_score from sklearn.neighbors import KNeighborsClassifier users = np.array(list("ABCDEF") * 2) # week 1: A to F, then week 2 X = np.array([[31, 2], [19, 5], [44, 1], [26, 4], [52, 3], [38, 6], [33, 2], [18, 6], [45, 2], [27, 3], [50, 3], [37, 5]]) y = np.array([0, 1, 0, 1, 0, 1] * 2) # 1 = buys again next week model = KNeighborsClassifier(n_neighbors=1) mixed = cross_val_score(model, X, y, cv=KFold(n_splits=3)) by_user = cross_val_score(model, X, y, cv=GroupKFold(n_splits=3), groups=users) print("KFold: ", mixed, f"mean {mixed.mean():.2f}") print("GroupKFold:", by_user, f"mean {by_user.mean():.2f}")
KFold: [1. 1. 1.] mean 1.00 GroupKFold: [0.5 1. 0.5] mean 0.67
Code run on CPython 3.12 with scikit-learn 1.9 against the example above. Checked by an editor other than the author.
Walkthrough
The rows of one shopper are near copies. A spends 31 and then 33 euros and visits twice in both weeks. A's label is the same both weeks too. So the nearest row to A's week 2 is A's week 1.
Without shuffling, KFold cuts the 12 rows into 3 blocks of 4. The first block is A to D in week 1, and their week 2 rows sit in training. The other blocks are the same: each validation row has its twin, the same shopper's other week, in training. The model never meets a new shopper.
GroupKFold keeps all rows of a shopper in the same fold:
| validation shoppers | right | accuracy |
|---|---|---|
| C, F | C | 0.5 |
| B, E | B, E | 1.0 |
| A, D | D | 0.5 |
Now the nearest row always belongs to another shopper, as in production: a new shopper has no twin in the training data. The mean of 0.67 is lower and noisier, but it answers the right question.
The leak is not about row order. It is about the unit you predict for. Ask "what is new when the model runs?" and split by that: the shopper here, or a patient, a device, a document.
Common mistakes
- Shuffling the rows and calling it fixed. With
KFold(shuffle=True), a shopper's two rows still land in different folds 8 times in 11 here. Group by the shopper instead. - Grouping by the wrong key. If one household shares several accounts, their rows are still near copies. Group by the household.
- Using
StratifiedKFoldto keep the class balance and forgetting the groups.StratifiedGroupKFoldkeeps groups together and balances the classes as well as it can. - Fixing the folds but not the final test set. A shopper in both train and test makes the test score too optimistic for the same reason.
Follow-up questions
- "The model predicts next week's purchases. Is
GroupKFoldenough?" Not quite. Grouping still lets the model train on other shoppers' week 2 and validate on week 1. That uses the future. Train on weeks before a cut-off date and validate on the weeks after it.TimeSeriesSplitdoes this on rows sorted by time, but it cuts by row count. Make sure the cut falls between weeks. - "Why did the fold scores jump between 0.5 and 1.0?" Each fold holds out only 2 shoppers, so one shopper moves the fold score by 0.5. Report the spread, not just the mean, and use more shoppers if you can. With very few groups,
LeaveOneGroupOutholds out each group once.
What a strong answer covers
Sees that a row-level split lets the model recognize shoppers by their near-copy rows. Splits by what is new when the model runs, with GroupKFold. Knows shuffling doesn't help, and uses a time-based split when the model predicts the future.
Open in interactive practice deck →