Sub topic 9
Resampling only the training folds: pipelines and leakage
Earlier chapters showed random resampling and SMOTE as ways to rebalance training data. This chapter covers a mistake that makes those techniques look better than they are: resampling before the data is split. It also shows how to avoid it.
You should already be comfortable with scikit-learn estimators, Pipeline, train_test_split, stratified cross-validation, and the SMOTE and random resampling ideas from the previous chapters. You also need the imbalanced-learn package (pip install imbalanced-learn).
What leakage means here
Data leakage happens when information from the data you evaluate on influences the model you are evaluating. The score then estimates performance on data the model has partly seen, not on new data.
Resampling creates leakage in a specific way. Both methods produce rows that depend on other rows:
- Random oversampling copies existing minority rows. A copy can land in the training part of a fold while the original sits in the validation part (or the reverse). The model is then scored on a row it memorized.
- SMOTE builds each synthetic row by interpolating between a minority row and one of its nearest minority neighbors. If the source rows end up on both sides of a split, a synthetic training row lies on a line segment that ends at a validation point.
In both cases the validation fold contains points that the training fold was built from. The model looks good on the rare class, and the number you report is too high.
The rule is simple. Resample only the data a model is fitted on. Never resample data used for scoring, and never resample before you split.
The leaky workflow and the correct one
The first diagram compares the two orders of operations.
Here is the wrong order in code. The data setup is the same as in the first chapter's example, repeated so this block runs on its own.
from imblearn.over_sampling import SMOTE
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
# WRONG: resample first, then cross-validate.
X_res, y_res = SMOTE(random_state=42).fit_resample(X_train, y_train)
leaky = cross_val_score(
LogisticRegression(max_iter=1000),
X_res,
y_res,
cv=cv,
scoring="average_precision",
)
print("leaky average precision:", leaky.mean())This code runs without errors and prints a plausible number. That is what makes the mistake dangerous. Nothing fails. The score is simply optimistic. The validation folds now also contain synthetic rows, so they no longer represent the real 5% positive rate. Average precision depends on the class ratio, so even the scale of the metric has changed.
The correct workflow: an imbalanced-learn pipeline
scikit-learn's own Pipeline cannot hold a resampler. Its steps must be transformers that keep the same number of rows, and a resampler changes the row count. The imblearn.pipeline.Pipeline class accepts samplers and handles them correctly:
- During
fit, it callsfit_resampleon the sampler step and passes the resampled data to the next step. - During
predict,predict_probaandscore, it skips samplers entirely. New data is never resampled.
Cross-validation tools clone the whole pipeline for each fold and call fit on the training part only, so the sampler sees only that part.
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, train_test_split
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
pipe = Pipeline([
("smote", SMOTE(random_state=42)),
("clf", LogisticRegression(max_iter=1000)),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
scores = cross_val_score(pipe, X_train, y_train, cv=cv, scoring="average_precision")
print("honest average precision:", scores.mean())Run both blocks and compare. The pipeline score is usually lower than the leaky one, and it is the one that predicts how the model behaves on new data. The size of the gap depends on the dataset and the model. It tends to be larger with flexible models such as deep trees or k-nearest neighbors, which can memorize the leaked rows.
What happens inside one fold
It helps to see the pipeline written out by hand. This loop does what cross_val_score does for you, minus the convenience.
import numpy as np
from imblearn.over_sampling import SMOTE
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import average_precision_score
from sklearn.model_selection import StratifiedKFold, train_test_split
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
fold_scores = []
for train_idx, val_idx in cv.split(X_train, y_train):
X_fit, y_fit = X_train[train_idx], y_train[train_idx]
X_val, y_val = X_train[val_idx], y_train[val_idx]
# Resample the fitting part only.
X_fit_res, y_fit_res = SMOTE(random_state=42).fit_resample(X_fit, y_fit)
clf = LogisticRegression(max_iter=1000).fit(X_fit_res, y_fit_res)
# Score on the original, untouched validation part.
fold_scores.append(average_precision_score(y_val, clf.predict_proba(X_val)[:, 1]))
print(np.round(fold_scores, 3), np.mean(fold_scores))The validation arrays X_val and y_val are never passed to the sampler. That one fact is the entire guarantee.
Tuning hyperparameters without leakage
Resampler settings are hyperparameters too. Examples are k_neighbors for SMOTE and sampling_strategy, which sets the target ratio. If you tune them with GridSearchCV, put the sampler in the pipeline and address its parameters with the step__parameter naming convention.
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, StratifiedKFold, train_test_split
X, y = make_classification(
n_samples=10000,
n_features=20,
n_informative=5,
weights=[0.95, 0.05],
flip_y=0.01,
random_state=42,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
pipe = Pipeline([
("smote", SMOTE(random_state=42)),
("clf", LogisticRegression(max_iter=1000)),
])
param_grid = {
"smote__k_neighbors": [3, 5, 10],
"smote__sampling_strategy": [0.25, 0.5, 1.0],
"clf__C": [0.1, 1.0, 10.0],
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
search = GridSearchCV(pipe, param_grid, scoring="average_precision", cv=cv, n_jobs=-1)
search.fit(X_train, y_train)
print("best params:", search.best_params_)
print("cv average precision:", search.best_score_)
print("test average precision:", search.score(X_test, y_test))A sampling_strategy given as a float is the desired ratio of minority to majority samples after resampling. Here 1.0 means fully balanced and 0.25 means one minority row for every four majority rows. The grid has 27 combinations and five folds, so it fits 135 pipelines. Each fit includes a SMOTE run, so resampling cost matters on large data.
The last line scores the held-out test set. search.score calls predict_proba through the refitted best pipeline, which skips the sampler, so the test set is not resampled. The test set keeps its natural 5% positive rate. Its score is the one you report.
Common mistakes
| Mistake | Why it leaks or misleads | Fix |
|---|---|---|
| Calling `fit_resample` on the full dataset before `train_test_split` | Test rows are copies or neighbors of training rows | Split first, then resample only the training part |
| Calling `fit_resample` on `X_train`, then cross-validating the result | Same problem inside each fold | Put the sampler in an `imblearn` pipeline |
| Resampling the test set to "balance" it | Metrics no longer describe real traffic | Leave validation and test data at the natural ratio |
| Fitting a scaler on all data, then resampling in the pipeline | The scaler sees validation rows | Put the scaler in the pipeline before the sampler |
| Using `sklearn.pipeline.Pipeline` with a sampler | Raises an error, and people then work around it outside the pipeline | Import `Pipeline` from `imblearn.pipeline` |
| Comparing a resampled model's accuracy against an unresampled model's accuracy on different test sets | The two scores are not on the same data | Evaluate every candidate on the same untouched folds |
Scaling interacts with SMOTE. SMOTE uses distances to find neighbors, so features should be on comparable scales first. Put StandardScaler before SMOTE in the pipeline. The scaler is then fitted on the training part of each fold, and the sampler works on scaled data.
Limits of the pipeline approach
- Random state matters. A sampler with
random_stateset gives the same synthetic rows every time it is fitted on the same data. Different folds have different training data, so the rows differ anyway. Fix the seed for reproducibility, and expect small score changes when you change it. - Undersampling inside a pipeline throws away majority rows from each training fold, not from the whole dataset. Scores can vary more between folds, so report the standard deviation as well as the mean.
- Class weights avoid this whole problem. They change the loss function and create no new rows, so there is nothing to leak. If you cannot tell whether a pipeline is leak-free, weights are a safe baseline to compare against.
- Resampling inside a pipeline does not fix a threshold or calibration problem. The model is trained on a changed class ratio, so its predicted probabilities no longer match real frequencies. The next chapters on threshold tuning and calibration cover that.
Exercise
A teammate reports a cross-validated average precision of 0.92 for a fraud model. Their code runs RandomOverSampler().fit_resample(X, y) on the full dataset and then calls cross_val_score on a random forest with the resampled arrays. Why is 0.92 unreliable, and how do you fix the code?
Show answer
Random oversampling copies minority rows. After resampling, cross_val_score splits the enlarged dataset, so copies of the same fraud row fall in both training and validation folds. A random forest can memorize rows, so it scores them almost perfectly, and the validation folds also no longer have the real fraud rate. Fix it by putting the sampler in an imblearn.pipeline.Pipeline (RandomOverSampler followed by the forest), passing the original X and y to cross_val_score with StratifiedKFold, and keeping a separate test set that is never resampled.
Exercise
You tune smote__k_neighbors with GridSearchCV on a pipeline, then call search.score(X_test, y_test). Is the SMOTE step applied to X_test? Does this matter for the reported score?
Show answer
No. An imblearn pipeline applies samplers only during fit, and score goes through predict_proba or predict, which skip them. This matters because the test set keeps its real class ratio, so the score reflects what you will see on new data.