Sub topic 2
Using Pipelines to Keep Preprocessing Inside the Training Data
Assume you know features, labels, train/test splits, and scikit-learn’s fit, transform, and predict methods.
Pipelines Prevent Preprocessing Leakage
A preprocessing step learns information from data. For example, StandardScaler learns a mean and standard deviation. If it learns them from the full dataset before splitting, test information enters the training features.
A scikit-learn pipeline chains preprocessing and modeling. During cross-validation, each step is fitted only on the training portion of the current fold.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(
n_samples=500,
n_features=10,
random_state=0,
)
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=1000),
)
scores = cross_val_score(model, X, y, cv=5)
print(scores.mean())The scaler is fitted again for each training fold. It then transforms that fold’s validation data without learning from it.
Leakage Inside Cross-Validation
Cross-validation divides data into training and validation folds. A common mistake is to select features or calculate statistics on all rows before cross-validation.
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.pipeline import make_pipeline
model = make_pipeline(
SelectKBest(f_classif, k=20),
LogisticRegression(max_iter=1000),
)
scores = cross_val_score(model, X, y, cv=5)
print(scores.mean())Here, SelectKBest is fitted separately inside every fold. Selecting features before calling cross_val_score would let validation labels influence feature selection and usually inflate the score.
Temporal Leakage and Time-Aware Splits
Random folds are unsuitable when rows represent time. Random splitting can place future observations in training while older observations are used for validation. This makes the evaluation unlike production.
Use TimeSeriesSplit when training must always precede validation:
from sklearn.model_selection import TimeSeriesSplit
time_cv = TimeSeriesSplit(n_splits=3)
scores = cross_val_score(model, X, y, cv=time_cv)
print(scores.mean())Also check engineered features. A rolling average must use only values available before the prediction time.
Exercise
Why should scaling be inside a pipeline during cross-validation?
Show answer
The pipeline fits the scaler only on each training fold, preventing validation statistics from influencing the model.