Sub topic 3
Group and Duplicate Leakage
Assume you know features, labels, estimators, and cross-validation. This chapter focuses on rows that are not independent and on model-selection mistakes.
Keep Related Rows Together
Group leakage occurs when related rows appear in both training and test data. For example, several measurements from one patient can let the model recognize that patient. The test score then measures memorization rather than generalization.
Use GroupKFold when a group, such as a patient, account, or device, must occur in only one fold. Duplicate or near-duplicate records need the same treatment.
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(["A", "B", "C", "D"], 3)
for train, test in GroupKFold(n_splits=2).split(X, y, groups):
assert set(groups[train]).isdisjoint(groups[test])Tune Without Reusing Evaluation Data
Choosing hyperparameters from repeated test-set scores makes the test set part of training. A separate test set can remain untouched until the final evaluation. For a less biased estimate while tuning, use nested cross-validation: an inner loop selects settings, and an outer loop evaluates that selection.
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV, KFold, cross_val_score
from sklearn.svm import SVC
X, y = make_classification(n_samples=200, random_state=0)
inner = KFold(3, shuffle=True, random_state=1)
outer = KFold(5, shuffle=True, random_state=2)
search = GridSearchCV(SVC(), {"C": [0.1, 1, 10]}, cv=inner)
scores = cross_val_score(search, X, y, cv=outer)
print(scores.mean())Feature Engineering and Encodings
A feature must use only information available when the prediction is made. Do not calculate a customer’s lifetime average using future transactions. Do not compute target encoding, which replaces a category with an average label, before splitting. Fit the encoder inside each training fold.
> callout warning > A feature created after the outcome, such as “claim approved date,” can reveal the target even if it looks like an ordinary input column.
Detect Existing Leakage
Investigate unusually high scores, especially scores near perfection. Compare random and time-aware splits. Inspect the most important features and ask when each value became available. Search for duplicate entities across folds and compare repeated or near-identical rows. Re-run evaluation after removing suspicious columns.
Prevention Checklist
- Define the prediction time and eligible data.
- Split by time, group, or entity when rows are dependent.
- Fit preprocessing, selection, and encoders inside each training fold.
- Keep the final test set untouched during tuning.
- Check duplicates and suspicious features before trusting metrics.
Exercise
Several rows from the same patient occur in both training and test data. Which split should you use?
Show answer
Use a group-aware split such as GroupKFold, with patient ID as the group value.