Sub topic 12
Splitting Grouped and Dependent Samples
This chapter assumes you can already use train_test_split and cross_val_score, and that you know why a test set must stay untouched. It covers the case where rows are not independent. A random split then lets near-copies of the same entity land on both sides, and the score you get is too high.
Why random splits assume independence
train_test_split and shuffled k-fold treat each row as an independent draw from the same population. The test score estimates performance on new rows only if new rows resemble the test rows the way a stranger would. That holds when each row comes from a different, unrelated source.
In many datasets it does not hold:
- Several rows per patient, such as repeated visits or scans.
- Several photos of the same object, or several sentences from the same document.
- Several sensor readings from the same machine.
- Several purchases by the same customer.
- Augmented copies of one original image.
Rows from the same source share traits. These can be a patient's physiology, a camera's noise pattern, or a writer's vocabulary. A flexible model can learn these traits and use them to recognize the source instead of learning the pattern you care about. If the source appears in both training and test data, the model is rewarded for recognizing it. This is data leakage through shared identity. In deployment, you will usually see sources the model has never met, so the leaky score overstates real performance.
The question to ask is: what is the unit of generalization? If you will predict for new patients, the unit is the patient, and the split must be by patient.
Seeing the leak
The script below builds a dataset with no real signal. Each patient has a fingerprint (a random offset in feature space) and a random label. Nothing in the features predicts the label for a new patient. Any score above chance comes from recognizing patients.
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_patients, per_patient = 60, 10
groups = np.repeat(np.arange(n_patients), per_patient)
patient_offset = rng.normal(size=(n_patients, 5)) * 3
patient_label = rng.integers(0, 2, size=n_patients)
X = patient_offset[groups] + rng.normal(size=(len(groups), 5))
y = patient_label[groups]
model = RandomForestClassifier(n_estimators=100, random_state=0)
shuffled = KFold(n_splits=5, shuffle=True, random_state=0)
print("Row-level KFold: ", cross_val_score(model, X, y, cv=shuffled).mean())
grouped = GroupKFold(n_splits=5)
print("GroupKFold: ", cross_val_score(model, X, y, cv=grouped, groups=groups).mean())Row-level k-fold reports accuracy close to 1.0. Grouped k-fold reports accuracy near 0.5, which is chance for two balanced classes. The grouped number is the honest one, because the data holds no transferable signal.
Splitters that respect groups
Every group-aware splitter in scikit-learn takes a groups array with one label per row. The label can be an integer or a string. The splitter keeps all rows with the same label on the same side.
| Splitter | What it does | Use it for |
|---|---|---|
| `GroupShuffleSplit` | Random train/test split(s) by group | A held-out test set |
| `GroupKFold` | K folds, each group in exactly one test fold | Cross-validation with grouped rows |
| `StratifiedGroupKFold` | Grouped folds that also try to keep class proportions | Grouped data with imbalanced classes |
| `LeaveOneGroupOut` | Each group is the test set once | Few groups, and per-group scores wanted |
You can check the guarantee directly:
import numpy as np
from sklearn.model_selection import GroupKFold
X = np.arange(12).reshape(-1, 1)
groups = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3])
for fold, (train_idx, test_idx) in enumerate(GroupKFold(n_splits=4).split(X, groups=groups)):
train_groups = set(groups[train_idx])
test_groups = set(groups[test_idx])
assert train_groups.isdisjoint(test_groups)
print(fold, "train groups", sorted(train_groups), "test groups", sorted(test_groups))The assert is a cheap safeguard. Put a similar check in any pipeline where leakage through identity would be costly.
A complete grouped workflow
The test-set discipline from earlier chapters still applies. Separate the test set first, then do all model selection inside the training portion. The only change is that every split is by group.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import (
GroupShuffleSplit,
StratifiedGroupKFold,
cross_val_score,
)
rng = np.random.default_rng(0)
n_patients, per_patient = 60, 10
groups = np.repeat(np.arange(n_patients), per_patient)
patient_offset = rng.normal(size=(n_patients, 5)) * 3
patient_label = rng.integers(0, 2, size=n_patients)
X = patient_offset[groups] + rng.normal(size=(len(groups), 5))
y = patient_label[groups]
# 1. Hold out whole patients for the final test.
splitter = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
train_idx, test_idx = next(splitter.split(X, y, groups=groups))
X_train, y_train, g_train = X[train_idx], y[train_idx], groups[train_idx]
X_test, y_test, g_test = X[test_idx], y[test_idx], groups[test_idx]
assert set(g_train).isdisjoint(g_test)
# 2. Cross-validate inside the training portion, still by patient.
model = RandomForestClassifier(n_estimators=100, random_state=0)
cv = StratifiedGroupKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(model, X_train, y_train, cv=cv, groups=g_train)
print("CV accuracy:", scores.mean())
# 3. Fit on all training rows and score the test patients once.
model.fit(X_train, y_train)
print("Test accuracy:", model.score(X_test, y_test))Both numbers should sit near 0.5 here, because the data has no transferable signal. On real data, a drop from a row-level score to a grouped score tells you how much of the earlier performance was identity recognition.
Pass groups= to cross_val_score, cross_validate, GridSearchCV.fit or cross_val_predict. A Pipeline passes it through to the splitter, and preprocessing inside the pipeline is refit on the training folds as before. If you forget groups=, GroupKFold raises an error. Some other splitters ignore groups silently, so verify that the one you chose uses it.
Choosing and sizing group splits
Group sizes and balance
GroupKFold assigns groups to folds so that fold sizes are as equal as possible, counted in rows. It is deterministic. Calling it twice gives the same folds. If you want shuffling, use StratifiedGroupKFold(shuffle=True) or GroupShuffleSplit. Recent scikit-learn versions also let GroupKFold shuffle through a shuffle argument, but check your installed version before relying on it.
Group sizes can vary a lot. One patient with 5,000 rows and many with 10 rows will give uneven folds, and test_size in GroupShuffleSplit is a fraction of groups, not of rows. The resulting test set may be noticeably larger or smaller than 20% of the rows. Print the row counts after splitting.
Few groups
With 8 patients, a 5-fold grouped split leaves test folds of one or two patients. Fold scores will vary widely, and one unusual patient can dominate a fold. Report the spread of fold scores as well as the mean. LeaveOneGroupOut gives one score per group, which shows which groups the model fails on.
Class balance across groups
Stratifying by row label does not work when groups must stay intact. StratifiedGroupKFold approximates it. It tries to keep class proportions similar per fold, but exact balance is impossible if one group holds most of a rare class. Inspect y[test_idx].mean() per fold when classes are imbalanced.
Other kinds of dependence
Repeated measurements of one entity are the common case, but they are not the only one.
- Duplicates and near-duplicates. The same record may appear twice under different row IDs. Deduplicate before splitting, or define the duplicate cluster as a group.
- Augmentation. Create augmented copies after splitting, and only for training data. If you augment first and split afterward, copies of one image straddle the split.
- Hierarchies. Rows nested in sessions, which are nested in users. Group by the highest level you want to generalize across. If you group by session but deploy to new users, user identity still leaks.
- Spatial neighbors. Nearby locations resemble each other. Group by region or tile when predicting for new areas.
- Derived groups. When no ID exists, you can build one, for example by clustering near-duplicate documents. The split is only as good as the grouping.
The hierarchy case is the most common error. Choose the group column by asking what the model will see for the first time in production.
Common errors
- Splitting by row, then checking by group. Check group overlap on the actual split indices, as the
assertabove does. - Grouping by the wrong column. A
visit_idis not apatient_id. - Group leakage in the final test set only. Doing grouped cross-validation but a random
train_test_splitfor the test set means the test score is still leaky. UseGroupShuffleSplitfor the outer split too. - Using grouped CV scores to compare against row-level scores. The two numbers answer different questions. Compare models under the same splitter.
- Treating grouped splits as free. They reduce effective sample size, because the number of independent units is the number of groups, not rows. Confidence in the estimate depends on group count.
Exercise
A dataset has 3,000 rows from 150 customers. You will use the model only for customers who join after training. A teammate runs 5-fold KFold(shuffle=True) cross-validation and reports 96% accuracy. Which splitter should you use instead, which argument must you pass to the scoring call, and why will the new score probably be lower?
Show answer
Use GroupKFold (or StratifiedGroupKFold if classes are imbalanced) and pass groups=customer_ids to cross_val_score. Shuffled KFold puts rows from the same customer in both training and test folds, so the model can score well by recognizing customers. Grouped folds test only on customers the model has not seen, which matches deployment, so the score is usually lower and more honest.
Exercise
You use GroupShuffleSplit(test_size=0.2) on 100 groups, and one group holds 40% of all rows. What can go wrong with the resulting test set, and how do you check it?
Show answer
test_size applies to groups, so about 20 groups go to the test set. If the large group is among them, the test set will hold well over 20% of the rows, and the score will depend heavily on that one group. If it is not among them, the test set may be much smaller than 20%. Check by printing len(test_idx) / len(X) after the split, and re-split with another random_state or handle the large group deliberately.