Sub topic 9
Resampling only the training folds: pipelines and leakage
This chapter assumes you know stratified splitting, cross-validation, and scikit-learn estimators and pipelines. It also assumes you have seen random oversampling and SMOTE.
Why resampling can leak
Leakage means information from the data you evaluate on reaches the model during training. Resampling is an easy way to cause it. Oversampling copies or synthesizes minority rows. If you do that before splitting, a copy of one row can land in the training set and another copy in the validation set. The model has then seen the validation row, so the score looks better than it should.
SMOTE has a similar problem. A synthetic point is an interpolation between real minority neighbors. If those neighbors come from the validation fold, the training data carries information about them.
The rule is simple. Split first. Resample only the training part. Leave validation and test data with their natural class ratio, because that is what the model will meet in production.
The wrong way
This code resamples the whole dataset and then cross-validates. It runs, and the score it prints is inflated.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score
from sklearn.linear_model import LogisticRegression
from imblearn.over_sampling import SMOTE
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
)
# Wrong: SMOTE sees every row before the folds are made.
X_res, y_res = SMOTE(random_state=42).fit_resample(X_train, y_train)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
bad = cross_val_score(
LogisticRegression(max_iter=1000), X_res, y_res,
cv=cv, scoring="average_precision",
)
print("leaky score:", bad.mean())Each validation fold now contains synthetic points built from rows that also sit in the training folds, and the validation fold's class ratio is about 50/50 instead of 95/5. Both effects make the number unreliable.
The right way: resample inside a pipeline
The Pipeline from imbalanced-learn (imblearn) fits a sampler only during fit. At prediction time it skips the sampler. Cross-validation then refits the whole pipeline on each training fold, so SMOTE never touches the validation fold.
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import SMOTE
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
# Continues from the first example (X_train, y_train).
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(scores.mean())Common errors
- Using scikit-learn's
Pipelinewith a sampler. It rejects steps that lacktransform. ImportPipelinefromimblearn.pipeline. - Resampling before
train_test_split. The test set then contains duplicates or synthetic rows. Always split first. - Scaling or selecting features before the pipeline. The same leak applies. Put scalers and feature selectors inside the pipeline too.
- Balancing the validation or test set. Metrics from a 50/50 set do not describe real-world performance.
- Judging with accuracy. Use average precision, recall, or F1, as covered earlier.
Checking the result on the test set
Fit the pipeline on all of the training data, then score once on the test set, which was never resampled.
from sklearn.metrics import average_precision_score
# Continues from the previous example (pipe, X_train, X_test, y_train, y_test).
pipe.fit(X_train, y_train)
test_scores = pipe.predict_proba(X_test)[:, 1]
print("test average precision:", average_precision_score(y_test, test_scores))The test score should be close to the pipeline's cross-validation score. A large gap in the other direction, where the leaky score is much higher than the test score, points to leakage.
Exercise
A colleague runs RandomOverSampler on the full dataset, then calls crossvalscore with a plain LogisticRegression. Why is the score unreliable, and how do you fix it?
Show answer
Oversampling creates duplicate minority rows before the folds are made, so the same row can appear in both a training fold and a validation fold, and the validation folds are no longer 95/5. The model is scored on rows it has already seen. Fix it by putting RandomOverSampler and the classifier in an imblearn Pipeline and passing that pipeline to crossvalscore, so the sampler is fitted on each training fold only.