Leakage and duplicate records
Data leakage occurs when a model or its evaluation uses information that would not legitimately be available under the intended prediction and evaluation protocol. It can produce a deceptively strong score. A shipment delay classifier that receives the final delivery timestamp before dispatch is a simple target leakage example. Another is using evaluation records to choose a scaler, fill missing values or select features.
Audit duplicate records and related observations
Suppose a shipment is scanned twice. Two rows can have different timestamps yet refer to the same order. Removing identical rows alone will not prevent the same shipment from appearing across training and evaluation. When the goal is generalization to new orders, assign every row for an order to one subset. Decide how to handle exact duplicates before splitting using documented provenance, not by blindly deleting repeated observations that may be legitimate. Near-duplicates can require content fingerprints or manual review; a group ID check alone cannot detect them.
def group_overlaps(train_groups, validation_groups, test_groups): train, validation, test = map(set, (train_groups, validation_groups, test_groups)) return sorted((train & validation) | (train & test) | (validation & test))
print(group_overlaps(['A', 'A', 'B'], ['C'], ['A', 'D']))print(group_overlaps(['A', 'A', 'B'], ['C'], ['D']))Output: ['A'] then []. The first split has A in both training and test. Repeated A inside training is not itself a cross-boundary violation. The second split uses disjoint order groups. The function accepts lists of string IDs, returns each overlapping ID once in sorted order and checks all three pairs. Empty lists are allowed; an empty result only says there is no detected overlap, not that every split is valid. Allocate groups before fitting, and verify time boundaries too when both requirements apply.
Fit preprocessing only on permitted training examples
Min-max normalization learns two values: the smallest and largest training feature values. For any input x, transform it as (x - training_min) / (training_max - training_min). With training weights 2, 4 and 6 kg, the learned bounds are 2 and 6. A future weight of 8 kg becomes (8-2)/(6-2)=1.5. Values outside the original range may legitimately transform outside [0, 1]. Do not refit the bounds on evaluation data to force them inside that range.
def fit_minmax(values): if not values: raise ValueError('Training values required') low, high = min(values), max(values) if low == high: raise ValueError('Constant training feature: choose a policy') return low, high
def transform_minmax(values, bounds): low, high = bounds if low >= high: raise ValueError('Invalid fitted bounds') return [(x - low) / (high - low) for x in values]
bounds = fit_minmax([2, 4, 6])print(bounds)print(transform_minmax([2, 4, 6], bounds))print(transform_minmax([8, 0], bounds))Output: (2, 6), [0.0, 0.5, 1.0], [1.5, -0.5]. If the evaluation value 8 had been included during fitting, the training value 4 would transform to 1/3 instead of 1/2. The training representation would now depend on held-out information. This teaching function rejects empty and constant training features; a production pipeline may instead adopt a documented constant-feature policy. It accepts finite numeric values within ordinary arithmetic ranges and does not clip or impute values. It is not a drop-in implementation of a library scaler.
Other ways information crosses the boundary
A final delivery status encoded in a feature leaks the target. A fill value calculated using the entire dataset leaks evaluation statistics. Selecting features based on test correlations leaks evaluation labels. Repeatedly choosing the best model using test accuracy contaminates the final evaluation even without copying any rows into training. Keep the feature availability contract, fit preprocessing within each training fold, and use validation results only for model selection. A pipeline can organize these steps, but it does not automatically make a poor split safe.
| Symptom | Investigation | Correction |
|---|---|---|
| Very high test accuracy | Check outcome-derived inputs | Remove features unavailable at prediction time |
| Same order in two subsets | Audit group IDs and duplicate families | Assign whole groups to a subset |
| Validation values always scaled into [0, 1] | Inspect where bounds were fitted | Reuse training bounds, unless clipping was a predefined policy |
| Many changes after test evaluation | Review experiment history | Freeze the procedure and obtain fresh final evidence |
Practice: audit a shipment experiment
Training weights are 2 and 6; validation weight is 4; test weight is 10. Compute train-only normalized values: training [0, 1], validation 0.5, test 2. Next, suppose order B appears in validation and training. Fix the group assignment and recompute any affected fitted parameters from the new training subset. Never repair a split and keep parameters fitted on the earlier contaminated data. Record the change and explain how it affects comparability with older results.
Further reading
For library-specific workflows, consult scikit-learn common pitfalls, grouped and temporal cross-validation and dataset splitting guidance. The examples here are original, small Python fixtures; library versions and native runner support are not established by these examples.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Leakage and duplicate records quiz
Apply split and leakage concepts to original shipment scenarios.
Training groups are A and B, validation C, test B and D. Which group leaks across subsets?
Training minimum 2 and maximum 6; what is the transformed value of 10?
Which preprocessing workflow leaks held-out information into fitting?
What does group_overlaps returning [] establish?
A model predicts delay at dispatch but receives the eventual delivery timestamp as a feature. Why is this leakage?