Sub topic 6
Data leakage: how results get inflated
Data leakage happens when information from outside the training data influences the model. The model then looks better during evaluation than it will on new data. This chapter assumes you can split data with scikit-learn, fit a transformer, and read a classification score. It builds on the previous chapter on train, validation and test splits.
What leakage is and why it hides
A leaked score is a number that is correct for the experiment you ran and wrong for the experiment you meant to run. You wanted to know how the model does on rows it has never seen. Leakage means some of those rows, or facts about them, were available during training or preprocessing.
Leakage is hard to notice because nothing fails. The code runs, the score is high, and the report looks good. The damage appears later, when the deployed model performs worse than the evaluation promised.
There are two main families:
- Train-test contamination. Information from validation or test rows reaches the fitting step. Fitting a scaler on the full dataset is the standard example.
- Target leakage. A feature contains information that would not exist at prediction time, often because it is a consequence of the target.
A third case, duplicate or grouped rows, sits between the two. The same entity appears on both sides of a split, so the model memorizes instead of generalizing.
Train-test contamination from preprocessing
Any step that learns from data is part of the model. StandardScaler learns a mean and a standard deviation. SimpleImputer learns a median. OneHotEncoder learns the set of categories. Each of these must be fitted on training rows only.
The next example contrasts the leaky and correct approaches, and adds a baseline for comparison.
from sklearn.datasets import load_breast_cancer
from sklearn.dummy import DummyClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
# Leaky: the scaler sees the test rows before the split.
X_scaled_all = StandardScaler().fit_transform(X)
X_tr_bad, X_te_bad, y_tr, y_te = train_test_split(
X_scaled_all, y, test_size=0.2, stratify=y, random_state=0
)
# Correct: fit the scaler on training rows only, then reuse it.
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
scaler = StandardScaler().fit(X_tr)
clf = LogisticRegression(max_iter=1000).fit(scaler.transform(X_tr), y_tr)
print("test accuracy:", clf.score(scaler.transform(X_te), y_te))
# Baseline: always predict the most frequent class.
baseline = DummyClassifier(strategy="most_frequent").fit(X_tr, y_tr)
print("baseline accuracy:", baseline.score(X_te, y_te))In the leaky version, the mean and standard deviation include the test rows. The effect on this dataset is small, because a scaler only leaks summary statistics. Do not take that as permission. The same mistake with a target encoder, a feature selector, or a PCA step can change scores by a lot. The pattern is wrong even when the damage is small, and you can't tell in advance which case you are in.
The baseline line matters for a different reason. A model that scores 0.96 sounds good until you learn that always predicting the majority class scores 0.63. Comparing against a baseline tells you whether a score reflects skill.
Steps that commonly leak
| Step | What it learns | Leaks if fitted on |
|---|---|---|
| Scaling | Mean, standard deviation | All rows before the split |
| Imputation | Median or most frequent value | All rows before the split |
| Feature selection | Which columns correlate with the target | All rows, because it uses the target |
| Target or frequency encoding | Per-category statistics | All rows, or inside the same fold it is evaluated on |
| Oversampling (such as SMOTE) | Synthetic neighbors | Data before the split, so copies land in the test set |
| PCA | Directions of variance | All rows before the split |
Feature selection and oversampling are the most damaging. Both use labels or create near-copies of rows, so they can inflate scores by large margins.
The fix: put every learned step in a pipeline
Manual fitting works, but it depends on you remembering every step in every experiment. It also breaks under cross-validation. If you scale once and then run cross_val_score, each validation fold has already influenced the scaler.
A Pipeline solves both problems. When you pass a pipeline to cross_val_score or GridSearchCV, scikit-learn clones it and refits every step on each training fold only.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
pipe = Pipeline([
("scale", StandardScaler()),
("select", SelectKBest(f_classif, k=10)),
("clf", LogisticRegression(max_iter=1000)),
])
scores = cross_val_score(pipe, X_train, y_train, cv=5, scoring="f1")
print("CV F1 without leakage:", scores.mean())Here the scaler and the feature selector both see only the training portion of each fold. The selector's use of the target is safe because the validation fold is not part of its input.
The same idea applies to the full workflow in the tutorial. A ColumnTransformer inside a pipeline lets you impute, scale and encode by column type, and GridSearchCV then refits all of it on each training fold.
Target leakage
Target leakage is a modeling mistake, not a coding mistake. No pipeline can catch it, because the leak is in the meaning of a column.
Typical examples:
- Predicting loan default with a column called
collections_status. That value is only set after a borrower stops paying. - Predicting hospital readmission with a field recording the discharge destination, when the field is updated after the readmission happens.
- Predicting customer churn with
days_since_last_login, computed at the time of export rather than at the time of prediction. - Predicting house price with a column derived from the sale price, such as price per square foot.
The question to ask for every feature is: will this value exist, with this meaning, at the moment I need a prediction? If the answer is no or unclear, remove the feature or rebuild it using only data from before the prediction time.
Warning signs
- A single feature gives near-perfect performance by itself.
- Test performance is far better than you expected from similar published work.
- Feature importance is dominated by one column with an odd name, such as an ID or a status flag.
- The deployed model performs much worse than the evaluation.
Duplicates, groups and time
Random splitting assumes rows are independent. Often they are not.
- Duplicates. Exact or near-duplicate rows can land in both train and test. Check with
df.duplicated().sum()before splitting. - Groups. Several rows may belong to one patient, customer or device. A random split puts some of that person's rows in training and others in test, so the model recognizes the person instead of learning the pattern. Use
GroupKFoldorGroupShuffleSplitwith a group identifier. - Time. If the model will predict the future, test data must come after training data. A random split lets the model train on the future. Use a chronological cutoff or
TimeSeriesSplit. Features such as rolling averages must be computed using only past values.
The diagram shows where information is allowed to flow.
A checklist before you trust a score
- Split first, before any step that learns from data.
- Put every learned step inside a pipeline.
- Check for duplicates and for grouped or time-ordered rows.
- Review each feature for availability at prediction time.
- Compare against a baseline.
- Touch the test set once, at the end.
Exercise
A teammate scales all features with StandardScaler().fittransform(X), then runs crossval_score on a logistic regression with cv=5. Explain what leaks, and rewrite the setup so it does not.
Show answer
The scaler computed its mean and standard deviation from every row, so each validation fold influenced the transformation applied to the training folds. The fix is to split off a test set first, then put the scaler and classifier in one Pipeline, such as Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression(maxiter=1000))]), and pass that pipeline to crossvalscore using only the training data. crossval_score then refits the scaler on the training portion of each fold.
Exercise
You are predicting whether a customer will cancel a subscription next month. One feature is "supportticketsclosedascancellation". Why is it a problem, and how would you decide about similar features?
Show answer
The value is only recorded because the customer is already cancelling, so it would not exist at prediction time. It is target leakage. For each feature, ask whether it would be available, with the same meaning, at the moment of prediction. Remove it, or rebuild it using only data from before that moment.