Sub topic 8
Group and duplicate leakage
This chapter assumes you can run scikit-learn cross-validation and know why a random train/test split is usually fine. You should also have read the earlier chapters on splits, pipelines, and cross-validation leakage. Here we cover leakage that comes from the rows themselves. Random splitting is valid only when rows are independent. When they are not, the split puts near-copies of the same information on both sides.
Why random splits fail on related rows
A random split assumes each row is an independent draw from the population. Real datasets often break that assumption in two ways:
- Group structure. Several rows come from the same entity: repeated measurements of one patient, many photos of one product, many sessions from one user, many sentences from one document.
- Duplicates. The same row, or a trivially altered version of it, appears more than once. Causes include double-logged events, merged data sources, scraped pages, and augmentation applied before splitting.
In both cases, a random split puts some related rows in training and others in test. The model can then score well by recognizing the entity or the copy, not by learning a rule that transfers. The test score measures recall of seen entities. Production data brings new entities, so the deployed model does worse.
The question to ask is: what is the unit I want to generalize to? If the answer is "new patients", then a patient is the unit, and the split must keep each patient entirely on one side.
Group leakage in action
The following script builds 60 patients with 10 rows each. Each patient has a characteristic feature vector, and the label is a per-patient coin flip. There is nothing to learn that transfers to a new patient, so an honest score should be near 0.5.
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, rows_per_patient = 60, 10
patient_vec = rng.normal(size=(n_patients, 5))
patient_label = rng.integers(0, 2, size=n_patients)
groups = np.repeat(np.arange(n_patients), rows_per_patient)
X = patient_vec[groups] + rng.normal(scale=0.1, size=(len(groups), 5))
y = patient_label[groups]
model = RandomForestClassifier(n_estimators=100, random_state=0)
leaky_cv = KFold(n_splits=5, shuffle=True, random_state=0)
leaky = cross_val_score(model, X, y, cv=leaky_cv).mean()
honest = cross_val_score(model, X, y, groups=groups, cv=GroupKFold(n_splits=5)).mean()
print(f"random KFold: {leaky:.2f}")
print(f"GroupKFold: {honest:.2f}")The random KFold score is close to 1.0 because the forest memorizes each patient's vector. The GroupKFold score is close to chance. Only the second number says anything about new patients.
Notice that the code never changed the model or the data. Only the splitter and the groups argument changed.
Group-aware splitters
scikit-learn provides splitters that take a groups array with one entry per row. The array can hold any hashable label, such as patient ID, user ID, or document ID.
| Splitter | Behavior | Use when |
|---|---|---|
| `GroupKFold` | Each group appears in exactly one test fold. Folds are balanced by row count. | Standard grouped cross-validation. |
| `StratifiedGroupKFold` | Keeps groups intact and tries to preserve class proportions per fold. | Imbalanced classification with groups. |
| `GroupShuffleSplit` | Random group-level train/test splits, repeated. | One hold-out split, or many random repeats. |
| `LeaveOneGroupOut` | Each group is the test set once. | Few groups, and you want per-group scores. |
The core guarantee is that no group appears on both sides of any split. You can check it directly:
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])
print("test groups:", sorted(set(groups[test_idx])))Group-aware splitting also applies to your final hold-out set. If you carve out a test set with plain train_test_split, you reintroduce the leak at the outermost level. Use GroupShuffleSplit instead:
import numpy as np
from sklearn.model_selection import GroupShuffleSplit
X = np.arange(40).reshape(-1, 1)
y = np.tile([0, 1], 20)
groups = np.repeat(np.arange(10), 4)
splitter = GroupShuffleSplit(n_splits=1, test_size=0.3, random_state=0)
train_idx, test_idx = next(splitter.split(X, y, groups))
assert set(groups[train_idx]).isdisjoint(groups[test_idx])
print(len(train_idx), len(test_idx))Note that test_size applies to the number of groups, not rows. If groups have unequal sizes, the row proportions will differ from what you asked for.
Choosing a splitter
If your data has both time and group structure, such as many patients observed over many months, you may need to combine constraints. A common choice is to cut by time first and also exclude from the test set any group that appears in training, if you want to estimate performance on new entities.
Defining groups well
Choosing groups is a modeling decision, not a mechanical step. Some guidance:
- Pick the deployment unit. If the model will score new users, group by user. If it will score new sessions from known users, grouping by session may be enough. State which one you chose.
- Look for hidden groups. Columns like
patient_idare obvious. Less obvious ones are the same photographer, same hospital, same scanner, same author, same source website, or same recording day. Rows sharing these often share style or bias that the model can pick up. - Merge groups that overlap. If a row can belong to two entities, for example a message sent between two users, a single ID column is not enough. You may need to build connected components and use the component ID as the group.
- Watch group sizes. One huge group can dominate a fold.
GroupKFoldcannot split a group, so with very uneven sizes, fold sizes and class balance will be uneven too. With fewer groups than folds, scikit-learn raises an error.
Groups must flow through everything that does splitting. That includes hyperparameter search. GridSearchCV.fit(X, y, groups=groups) passes the groups to its internal cv splitter, so set cv=GroupKFold(...) on the search as well as the outer loop. In nested cross-validation, make both the inner and the outer splitters group-aware. Otherwise the inner loop still leaks, and the model chosen is biased toward memorizers.
Duplicate leakage
Duplicates are group leakage where the group is "all copies of this example". They matter for several reasons:
- Exact copies in train and test make the test score reflect memorization.
- Models with high capacity, such as k-nearest neighbors, deep trees, and neural networks, benefit most from the copies, so their scores inflate more than those of simple models. This can make you pick the wrong model.
- Duplicates distort the data's real distribution. A row that appears five times counts five times in training, which may or may not be what you intend.
Sources of duplicates include:
- Joining tables on a non-unique key, which multiplies rows.
- Concatenating overlapping data exports.
- Scraping the same page under different URLs.
- Oversampling the minority class (for example, with SMOTE or random oversampling) before splitting, which places synthetic or repeated copies on both sides.
- Data augmentation (flips, crops, paraphrases) performed before splitting.
The last two are easy to miss because the leak is created by your own code. Resample and augment only inside the training fold. In scikit-learn terms, use imblearn.pipeline.Pipeline from the imbalanced-learn package, which applies resamplers during fitting only, or augment manually after the split.
Finding exact duplicates
Decide which columns define "the same example", usually the features and not the label or an ID column. Then check:
import pandas as pd
df = pd.DataFrame(
{
"age": [34, 51, 51, 29, 34],
"city": ["Oslo", "Rome", "Rome", "Lyon", "Oslo"],
"label": [0, 1, 1, 0, 1],
}
)
feature_cols = ["age", "city"]
dupe_mask = df.duplicated(subset=feature_cols, keep=False)
print(df[dupe_mask])
# Copies whose labels disagree point to label noise or a bad join
label_counts = df.groupby(feature_cols)["label"].nunique()
print(label_counts[label_counts > 1])Here rows 1 and 2 are full duplicates. Rows 0 and 4 have identical features but different labels, which tells you the features do not determine the label, or the data is mislabeled. Both findings are worth investigating before modeling.
Two ways to handle duplicates
- Drop them with
df.drop_duplicates(subset=feature_cols)before splitting. Do this only if the duplicates are errors. If repeated rows reflect real frequency, dropping changes the distribution. - Keep them but group them. Assign each distinct feature combination an ID and use it as the group, so all copies land on the same side:
import pandas as pd
from sklearn.model_selection import GroupShuffleSplit
df = pd.DataFrame(
{
"age": [34, 51, 51, 29, 34, 60, 60, 41],
"city": ["Oslo", "Rome", "Rome", "Lyon", "Oslo", "Kyiv", "Kyiv", "Bonn"],
"label": [0, 1, 1, 0, 1, 0, 0, 1],
}
)
feature_cols = ["age", "city"]
groups = df.groupby(feature_cols).ngroup()
splitter = GroupShuffleSplit(n_splits=1, test_size=0.25, random_state=0)
train_idx, test_idx = next(splitter.split(df, df["label"], groups))
train_keys = set(map(tuple, df.iloc[train_idx][feature_cols].to_numpy()))
test_keys = set(map(tuple, df.iloc[test_idx][feature_cols].to_numpy()))
assert train_keys.isdisjoint(test_keys)The assertion at the end is a useful habit. After any split, confirm that no feature key appears on both sides.
Near-duplicates
Exact matching misses copies that differ slightly. Examples are a text with different whitespace, an image resized or re-encoded, a record with a typo in a name, or a float rounded differently. Strategies include:
- Normalize first. Lowercase, strip whitespace, round floats, and then compare.
- Hash a canonical form. For images or documents, compute a perceptual or content hash and group by it.
- Use nearest-neighbor distance. For each test row, find the closest training row. A cluster of distances near zero signals near-copies.
- Cluster, then group. Cluster the data and use cluster IDs as groups, so similar rows stay together. This also covers cases where "same group" has no explicit column.
There is no universal threshold for "near". Choose it by looking at examples around the cutoff.
Checking for leakage after the split
Even with care, verify. A short audit on any split:
- Compute overlap of group IDs between train and test. It should be empty if you grouped.
- Compute overlap of feature keys or hashes. It should be empty or tiny.
- Compare the score under random splitting and under group splitting. A large gap, like the 1.0 versus 0.5 above, shows that group structure drives the score.
- Look at the model's per-group performance. A model that is perfect on every group it saw and poor on new ones is memorizing.
Trade-offs and limits
Group splitting is not free. Fewer effective samples means higher variance in your estimate, especially with few groups. Group-aware scores are usually lower than random ones, and the lower number is the honest one. Stratifying by class and keeping groups intact compete, so StratifiedGroupKFold gives approximate balance, not exact. And if production data will contain entities the model has already seen, such as returning customers, then a grouped split can understate performance. Match the split to the deployment setting, and write that assumption down.
Exercise
A dataset has 5,000 rows of skin-lesion photos from 800 patients, with several photos per patient. A colleague reports 97% accuracy using cross_val_score(model, X, y, cv=5) on shuffled folds. You want to estimate accuracy on new patients. Which splitter would you use, what extra argument must you pass, and why might the true score be much lower?
Show answer
Use GroupKFold (or StratifiedGroupKFold if the classes are imbalanced) with cv= set to that splitter, and pass groups=patient_ids to cross_val_score. Plain shuffled folds put photos of the same patient in both training and test, so the model can recognize patient-specific features such as skin tone, lighting, or scars instead of learning lesion features that transfer. With whole patients held out, the score measures performance on unseen patients, and it is usually noticeably lower.
Exercise
You oversample the minority class with random duplication on the full dataset, then run 5-fold cross-validation. Why is the score inflated, and how do you fix it?
Show answer
Duplicated minority rows end up in both training and test folds, so the model is tested on exact copies of rows it trained on. Fix it by splitting first and oversampling only inside each training fold, for example with an imbalanced-learn pipeline that applies the resampler during fitting only. Test folds must keep the original, un-resampled distribution.