Sub topic 8
Grouped data: keeping related samples together
This chapter assumes you know how k-fold works, how to use cross_val_score, and what data leakage is. You should also be comfortable with scikit-learn pipelines.
Why random folds fail on grouped data
Ordinary k-fold treats every row as independent. Many datasets break that assumption. Several rows may come from the same patient, the same user, the same store, or the same photographed object. Rows in one group tend to resemble each other.
If a group is split across the training and test folds, the model can recognize the group instead of learning the pattern you care about. The test score then looks better than it will be on a new patient or a new user. This is a form of data leakage, but it comes from the splitting scheme, not from preprocessing.
The question to ask is: what will new data look like? If you will predict for new patients, the test fold must contain only patients the model has never seen.
Splitting with GroupKFold
GroupKFold takes a groups array with one label per row. It guarantees that no group appears in both the training and test sets.
import numpy as np
from sklearn.model_selection import GroupKFold
X = np.arange(12).reshape(6, 2)
y = np.array([0, 1, 0, 1, 0, 1])
groups = np.array([1, 1, 2, 2, 3, 3])
for train_idx, test_idx in GroupKFold(n_splits=3).split(X, y, groups):
print(sorted(set(groups[train_idx])), sorted(set(groups[test_idx])))Each printed line shows the groups in the training set, then the groups in the test set. The two lists never overlap. The number of splits cannot exceed the number of distinct groups.
Seeing the leak
The next example builds data where every group has its own signature and a label that does not depend on the features. A model can only score well by recognizing the group.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import GroupKFold, KFold, cross_val_score
rng = np.random.default_rng(0)
n_groups, per_group = 40, 10
groups = np.repeat(np.arange(n_groups), per_group)
offsets = rng.normal(size=(n_groups, 5)) * 3
X = offsets[groups] + rng.normal(size=(len(groups), 5))
y = rng.integers(0, 2, size=n_groups)[groups]
model = RandomForestClassifier(n_estimators=100, random_state=0)
kf = KFold(n_splits=5, shuffle=True, random_state=0)
random_scores = cross_val_score(model, X, y, cv=kf)
group_scores = cross_val_score(model, X, y, cv=GroupKFold(n_splits=5), groups=groups)
print(f"KFold: {random_scores.mean():.3f}")
print(f"GroupKFold: {group_scores.mean():.3f}")Random KFold scores close to 1.0 because the forest memorizes each group. GroupKFold scores near 0.5, which is chance and the honest answer. Note that groups is passed to cross_val_score, which forwards it to the splitter.
Choosing a grouped splitter
| Splitter | Use it when |
|---|---|
| `GroupKFold` | Groups are the unit of generalization and classes are balanced |
| `StratifiedGroupKFold` | Groups matter and you also want similar class proportions per fold |
| `LeaveOneGroupOut` | There are few groups and each is large, such as a handful of hospitals |
| `GroupShuffleSplit` | You want random, repeatable group-level train/test splits |
Common errors
- Forgetting
groups. Passing a group splitter withoutgroups=raises an error. Passing a random splitter silently ignores groups and leaks. - Choosing groups too finely. If groups are individual photos but the real unit is the person, leakage remains. Group at the level you will deploy at.
- Uneven folds. One very large group can dominate a fold, so the fold scores will vary a lot. Report the spread, not only the mean.
- Grouping inside a search. In
GridSearchCV, passgroupstofitso the inner splits respect groups too.
Exercise
A dataset has 500 X-ray images from 100 patients, about 5 per patient. You run 5-fold random KFold and get 97% accuracy. Why might this be too high, and what change fixes it?
Show answer
Images from the same patient land in both the training and test folds, so the model can match a test image to the same patient's training images. Use GroupKFold (or StratifiedGroupKFold if the classes are imbalanced) with the patient ID as groups, so every patient appears in only one side of each split.