Sub topic 8
Grouped data: keeping related samples together
This chapter assumes you know the k-fold procedure, cross_val_score, and scikit-learn pipelines from the earlier chapters. You should also be comfortable with NumPy indexing. Here you will learn when ordinary k-fold gives misleadingly high scores, and how to fix that with group-aware splitting.
The problem: samples that are not independent
Ordinary k-fold assumes each row is an independent draw from the same distribution. Many datasets break that assumption because several rows come from the same source. Examples:
- Several scans or visits from one patient.
- Several photos of the same object.
- Many sentences written by one author.
- Several transactions from one customer.
- Repeated sensor readings from one machine.
Rows from the same source share traits that have nothing to do with the label you want to predict, such as a patient's anatomy, a camera's color cast, or an author's style. If k-fold puts some of a patient's rows in the training set and others in the test set, the model can recognize the patient instead of learning the disease. The test rows are then not truly unseen, and the score estimates the wrong thing.
This is a form of data leakage. The leaked information is the identity of the group, not a preprocessing statistic as in the pipeline chapter.
The question to ask is: what will the model see in production? If it will score new patients, new cameras, or new authors, then your validation must hold out whole patients, cameras, or authors.
What goes wrong, concretely
The next script builds a dataset with no real signal. Each of 40 "patients" has a fixed feature fingerprint and a random label, and every one of their 10 rows shares that label. Nothing in the features predicts the label for a new patient. A model can still memorize the fingerprints.
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)
fingerprint = rng.normal(size=(n_groups, 5))
group_label = rng.integers(0, 2, size=n_groups)
X = fingerprint[groups] + rng.normal(scale=0.1, size=(n_groups * per_group, 5))
y = group_label[groups]
model = RandomForestClassifier(n_estimators=100, random_state=0)
plain = cross_val_score(
model, X, y, cv=KFold(n_splits=5, shuffle=True, random_state=0)
)
grouped = cross_val_score(
model, X, y, groups=groups, cv=GroupKFold(n_splits=5)
)
print(f"KFold: {plain.mean():.2f}")
print(f"GroupKFold: {grouped.mean():.2f}")Plain KFold scores close to 1.0, because every test row has near-duplicates of itself in the training set. GroupKFold scores around 0.5, which is chance. The second number is the honest one. The model has learned nothing that transfers to a new patient.
Real data is rarely this extreme, but the direction of the error is always the same: ignoring groups makes the estimate too optimistic. The size of the gap depends on how much of the signal is group-specific.
How GroupKFold works
GroupKFold takes a groups array with one label per row. It guarantees that every group lands entirely in one test fold, so no group appears on both sides of a split.
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])))With three groups and three splits, each fold holds out one whole group and trains on the other two. The order in which the folds appear can differ between scikit-learn versions, but the property that matters does not change: the two printed lists never share a value.
Behavior to know
- Fold sizes follow group sizes. Folds hold whole groups, so they cannot be exactly equal.
GroupKFoldassigns the largest groups first to the currently lightest fold, which balances row counts reasonably well. - It is not random by default. The older
GroupKFoldhas noshuffleargument. Its folds are deterministic given the group sizes. Recent scikit-learn versions addshuffleandrandom_stateto it. Check your installed version before relying on them. - You need at least as many groups as splits. With 4 groups,
n_splits=5raises an error. With very few groups, each fold's score rests on a handful of entities and is noisy. - Pass
groupswhere it is consumed.cross_val_score(..., groups=groups, cv=GroupKFold(...))works. If you forgetgroups,GroupKFoldraises an error. A splitter that ignores groups, such asKFold, accepts the argument silently and does nothing with it. That is a quiet way to reintroduce the leak.
Classification with groups: StratifiedGroupKFold
GroupKFold ignores the label. If some patients are positive and some are negative, a fold can end up with almost no positives. StratifiedGroupKFold (scikit-learn 1.0 and later) keeps groups intact and also tries to preserve the class proportions in each fold.
import numpy as np
from sklearn.model_selection import StratifiedGroupKFold
groups = np.repeat(np.arange(12), 5)
group_label = np.array([0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0])
y = group_label[groups]
X = np.arange(len(y) * 2).reshape(len(y), 2)
sgkf = StratifiedGroupKFold(n_splits=3, shuffle=True, random_state=0)
for fold, (train_idx, test_idx) in enumerate(sgkf.split(X, y, groups)):
overlap = set(groups[train_idx]) & set(groups[test_idx])
print(fold, "test groups:", sorted(set(groups[test_idx])),
"positive rate:", y[test_idx].mean(), "overlap:", overlap)The overlap set is always empty. The positive rate in each test fold should be near the overall rate of 1/3, though stratification is approximate here. Whole groups must stay together, so exact proportions are not always possible.
Choosing a splitter
| Situation | Splitter |
|---|---|
| Independent rows, regression | `KFold` |
| Independent rows, imbalanced classes | `StratifiedKFold` |
| Rows grouped by source | `GroupKFold` |
| Grouped rows and imbalanced classes | `StratifiedGroupKFold` |
| Rows ordered in time | `TimeSeriesSplit` (next chapter) |
Finding the right grouping variable
Choosing the group column is the real work, and no function can do it for you. Use these guidelines:
- Match the deployment unit. If you will predict for new customers, group by customer, not by transaction.
- Look for hidden duplicates. Near-identical rows, such as augmented images or repeated measurements, behave like groups even without an ID column. Cluster or hash them to create a group label.
- Group at the coarsest level that matters. If patients belong to hospitals and the model must work at new hospitals, group by hospital. Grouping by patient only would still leak hospital-specific effects such as scanner type.
- Check the group count. If one group holds 40% of the rows, that group will dominate one fold and the fold scores will vary widely.
A useful sanity check is to run both KFold and a group splitter. A large gap between the two scores is evidence that groups matter in your data. Report the group-aware number.
Grouping and the rest of the workflow
Group-aware splitting must apply to every place you split, not only the final evaluation.
- Holdout test set. Use
GroupShuffleSplitortrain_test_spliton the group IDs, then select rows by group. Otherwise a patient can appear in both your training and test data. - Hyperparameter search. Pass a group splitter to
GridSearchCVascv, and passgroupstofit. A search that tunes with random k-fold can pick hyperparameters that favor memorization, such as an overly flexible model. - Nested cross-validation. Both the inner and outer loops need group-aware splitters. Forwarding
groupsthroughcross_val_scoreinto the inner search needs extra care in scikit-learn, so check the documentation for your version. - Pipelines. Scalers and encoders fit inside each training fold as before. Group splitting changes which rows are in each fold, not how the pipeline works.
Limitations
- Group splitting lowers the effective sample size. With 30 patients, you have 30 independent units, not thousands of rows. Fold scores will be noisy, so report the standard deviation and consider repeating with different group assignments.
- Groups of very different sizes make folds uneven, so average scores by row can differ from averages by group. Decide which one matches your goal, and say which you report.
- A correct grouping protects you only against the leak you modeled. If a leak runs through a variable you did not group by, the estimate is still optimistic.
Exercise
A model predicts whether a skin image shows a malignant lesion. The dataset has 5,000 images from 400 patients, with 8 to 15 images per patient. A teammate reports 97% accuracy from 5-fold StratifiedKFold and plans to deploy the model in new clinics. Which splitter should you use instead, which argument must you pass, and why might the reported accuracy fall?
Show answer
Use StratifiedGroupKFold (or GroupKFold if class balance is not a concern) and pass the patient ID as groups. The model will score new patients, so validation must hold out whole patients. With plain stratified k-fold, images of the same patient appear in both training and test sets. The model can then match patient-specific traits such as skin tone, lighting, or lesion appearance, which inflates accuracy. The group-aware score is expected to be lower, and it is the one that reflects deployment. Since the clinics are new, grouping by clinic may be worth considering too, in case equipment differs between sites.