Sub topic 8
Group and Duplicate Leakage
This chapter assumes you know how to split data into train and test sets, how scikit-learn's fit, transform, and predict work, and why held-out evaluation exists. Earlier chapters covered splits, preprocessing, and pipelines. Here the problem is different. The split itself is wrong because the rows are not independent.
Why random splits fail on related rows
A random split assumes each row is an independent draw from the same population. Many datasets break that assumption:
- Several rows come from one patient, user, device, or store.
- Several images or sentences come from one source document.
- The same record appears twice, because of a data-entry error, a join, or oversampling done before the split.
If one row lands in training and a related row lands in the test set, the model can recognize the entity instead of learning a general pattern. It scores well on the test set by remembering. In production it meets new patients or new users, and the score drops.
This is leakage because information about the test rows reaches the model during training, through the relationship between rows.
Group-aware splitting
When rows belong to groups, split by group. GroupKFold takes a groups array with one label per row. It guarantees that all rows of a group fall in the same fold.
import numpy as np
from sklearn.model_selection import GroupKFold
X = np.arange(12).reshape(-1, 1)
y = np.array([0, 1] * 6)
groups = np.repeat([0, 1, 2, 3], 3) # e.g. three rows per patient
for train_idx, test_idx in GroupKFold(n_splits=2).split(X, y, groups):
assert set(groups[train_idx]).isdisjoint(groups[test_idx])The assertion checks that no group appears in both the training and test indices. If you replaced GroupKFold with a plain KFold here, the assertion would fail.
The same idea works inside cross_val_score. Pass groups=groups and cv=GroupKFold(...). For a single train/test split, GroupShuffleSplit does the job.
Finding the right group
The hard part is often knowing what the group is. Ask these questions:
- What does one row represent, and what real-world entity does it belong to?
- Will the model see that entity during training and again at prediction time?
- Can one source produce many rows, such as one video giving many frames?
If the answer to the second question is "no", that entity must be the group.
Duplicate leakage
Exact or near-duplicate rows cause the same problem without any obvious group column. Common sources:
- Rows copied during data collection or merged from several files.
- Oversampling or augmentation applied before splitting, which creates copies of one row and spreads them across both sides.
- Near-duplicates, such as the same text with different whitespace, or the same image resized.
Check for exact duplicates before you split:
import pandas as pd
df = pd.DataFrame({"a": [1, 2, 2, 3], "b": [5, 6, 6, 7], "y": [0, 1, 1, 0]})
print(df.duplicated().sum()) # number of repeated rows
df = df.drop_duplicates()For near-duplicates, normalize the data first (lowercase text, strip whitespace, round numbers) and then compare. Another option is to build a key that identifies a duplicate cluster and use that key as the group for GroupKFold. This is safer than deleting rows when the duplicates carry information you want to keep.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Using `KFold` or `train_test_split` on repeated measurements | Same entity on both sides, inflated score | Use `GroupKFold` or `GroupShuffleSplit` |
| Forgetting to pass `groups` to `split` | `GroupKFold` raises an error, since it needs the groups | Pass `groups=` in `split` or `cross_val_score` |
| Dropping duplicates after the split | Duplicates may already sit on both sides | Deduplicate before splitting |
| Oversampling before the split | Copies of one row in train and test | Resample inside the training fold only |
| Grouping at the wrong level | Leakage remains, for example grouping by visit when you should group by patient | Group by the entity unseen at prediction time |
A sanity check
Compare the score from a random split with the score from a group split on the same model. If the random split is much higher, the model is probably using entity identity. A large gap is a strong sign that grouping matters for your data.
Exercise
A dataset has five photos of each of 200 plants, and the goal is to classify disease from a photo of a plant the model has never seen. You split photos randomly and get 98% accuracy, but accuracy drops sharply in the field. What went wrong, and which scikit-learn tool fixes it?
Show answer
Photos of the same plant were in both train and test, so the model could recognize individual plants instead of learning disease. Use the plant ID as the group and split with GroupKFold (or GroupShuffleSplit for a single split), passing groups=plant_id so that all five photos of a plant stay on one side.