Sub topic 12
Splitting grouped and dependent samples
This chapter assumes you can use train_test_split and cross-validation, and that you know what data leakage is. Here you will learn when a random split leaks through related rows, and how to split so that related rows stay together.
Why random splits assume independence
train_test_split treats every row as an independent draw. If that is true, a test row tells you nothing about any training row, so the test score estimates performance on new data.
Many datasets break this assumption. Common cases:
- Several rows come from one patient, such as repeated scans or visits.
- Several photos show the same object or person.
- Several sentences come from one document or one author.
- Several sessions come from one user.
Rows in the same group share traits the model can memorize, such as a patient's physiology or a user's habits. With a random split, rows from one group land on both sides. The model then "recognizes" the group instead of learning the pattern you care about. The test score is too high, and it drops when the model meets new groups in production.
Splitting by group
The fix is to split on groups, not rows. Every row of a group goes entirely to training or entirely to testing. The model is then tested on groups it has never seen, which matches deployment if new patients, users or documents will arrive later.
Grouped splitters in scikit-learn
You pass a groups array, with one group label per row, to the splitter. These are the main options:
| Splitter | Use it for |
|---|---|
| `GroupShuffleSplit` | A single grouped train/test split |
| `GroupKFold` | Grouped cross-validation, with each group in exactly one test fold |
| `StratifiedGroupKFold` | Grouped cross-validation that also keeps class proportions roughly equal |
import numpy as np
from sklearn.model_selection import GroupKFold, GroupShuffleSplit
X = np.arange(12).reshape(-1, 1)
y = np.array([0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1])
groups = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3])
# One grouped train/test split
splitter = GroupShuffleSplit(n_splits=1, test_size=0.25, random_state=42)
train_idx, test_idx = next(splitter.split(X, y, groups=groups))
print("Test groups:", sorted(set(groups[test_idx])))
assert set(groups[train_idx]).isdisjoint(groups[test_idx])
# Grouped cross-validation
for train_idx, test_idx in GroupKFold(n_splits=4).split(X, y, groups=groups):
print("train groups", sorted(set(groups[train_idx])),
"test groups", sorted(set(groups[test_idx])))
assert set(groups[train_idx]).isdisjoint(groups[test_idx])The assert lines check the property you want: no group appears on both sides. Keep a check like this in real projects, because a wrong groups array fails silently.
To tune a model on grouped data, pass the groups to cross-validation too:
cross_val_score(model, X_train, y_train, groups=groups_train, cv=GroupKFold(n_splits=5))Slice groups with the same indices as X_train, so each label still matches its row.
Common errors
- Forgetting
groups.GroupKFold.splitneedsgroups=. Without it, scikit-learn raises an error, but a hand-built loop may quietly fall back to a row-level split. - Choosing the wrong group. The group should be the unit you will meet as new in deployment. If you predict for new patients, group by patient, not by visit.
- Splitting by group only once. If you make a grouped test set but then use plain
KFoldon the training data, the validation scores still leak. Use grouped splitting at every level. - Expecting exact proportions. Groups differ in size, so test fractions and class balance are only approximate. Check the class counts in each fold. Use
StratifiedGroupKFoldif balance matters. - Too few groups. With only a handful of groups, scores vary widely from fold to fold. Report the spread, not just the mean.
Exercise
A dataset has 5,000 chest X-ray images from 800 patients, with several images per patient. A random 80/20 split gives 97% test accuracy, but the model scores 85% on a new hospital's patients. Why, and how should you split?
Show answer
Images from the same patient appear in both train and test, so the model can match patient-specific features and score high on the test set. New patients have no such overlap. Split by patient: pass a patient ID array as groups to GroupShuffleSplit for the train/test split, and use GroupKFold or StratifiedGroupKFold for cross-validation.