Group splits
Quick answer
Group-aware splitting keeps all observations belonging to one entity together. GroupKFold is appropriate when evaluating generalization to entirely new entities such as unseen customers, machines or patients. Static examples tested locally with Python 3.13.5, scikit-learn 1.8.0 SciPy 1.17.0 and NumPy 2.3.5 where imported. ByteMind package execution is unverified.
Find overlapping entities
groups=["a","a","b","c","c","d"]train=[0,2,3];valid=[1,4,5]print(sorted({groups[i] for i in train}&{groups[i] for i in valid}))Observed local output:
['a', 'c']Row IDs differ but two entities cross the boundary.
How it works
Imagine two duplicate records per machine. A model can identify a machine from a fingerprint and memorize its label. Random row splits may put one duplicate in training and the other in validation, giving an unrealistically high score for unseen-machine deployment. Define group IDs before splitting using the true dependency unit (or connected components linking overlapping entities). GroupKFold assigns each group to one validation fold and excludes it from that fold's training set. Pass groups separately from features: the group field is a splitting constraint, not automatically a valid predictor. At least k distinct groups are required for k folds. Fold row counts and class proportions may differ. StratifiedGroupKFold attempts to preserve class proportions while keeping groups intact; exact balance may be impossible when entire groups share a label. Report group counts, class counts, overlap and the target population. If predicting future events for already-known customers, a chronological design might better match deployment. Different split designs answer different questions.
Enforce entity disjointness
from sklearn.model_selection import GroupKFoldg=["a","a","b","b","c","c"]for tr,va in GroupKFold(n_splits=3).split(g,groups=g): print(len(set(g[i] for i in va)),len(set(g[i] for i in tr)&set(g[i] for i in va)))Observed local output:
1 01 01 0Every held-out group is new to its fitted model.
Common mistakes
Do not assign a different group ID to each duplicate, stratify rows instead of groups, or silently include entity identity as a predictor. A zero-overlap audit must reflect real dependencies, not merely exact row IDs.
Practice and next steps
Given patient groups A,A,B,C,C,D, propose two validation folds with disjoint patients. Compare their row counts and explain which metric aggregation matches the patient-level objective. Complete the knowledge check and staged exercise. Next: Chronological and gap splits.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Group splits — knowledge check
Apply group splits to new scenarios.
Which is the unit of a group split?
Can GroupKFold guarantee equal class counts?
Why could duplicate rows inflate row CV?
What does StratifiedGroupKFold attempt?
What if deployment predicts new machines?