How to use scikit-learn Pipeline to avoid data leakage
You avoid data leakage by putting all preprocessing inside a scikit-learn Pipeline and handing that whole pipeline to cross-validation: fit runs only on the training fold, and the validation fold is only transformed. ColumnTransformer lets each group of columns get its own treatment without leaving the flow. The minimum code for both cases is below.
Why does preprocessing outside the pipeline leak data?
Leakage happens when any information from the validation rows reaches training. The classic example is computing the mean and standard deviation of a column over the full dataset, scaling everything, and only then splitting into train and test. The mean already carries information from rows the model is supposed to know nothing about.
In cross-validation the effect is easy to see: each round holds out one fold for validation. If the scaler was fit beforehand, every fold took part in computing its parameters. The validation score comes out optimistic and drops when the model meets genuinely new data.
A Pipeline fixes this by postponing the fit. fit_transform runs only on the training fold; on the validation fold the object only transforms, applying parameters learned from training.
- Warning sign: the validation score sits well above the score on a separate holdout.
- Warning sign: results change noticeably when you move preprocessing inside the pipeline.
- Warning sign: the imputer, scaler or encoder was fit before cross_val_score was called.
How do you build the first Pipeline with StandardScaler and a model?
A Pipeline is an ordered list of steps. Every step except the last needs fit and transform; the last needs fit and predict. The code below standardizes the features and trains a logistic regression.
from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression pipe = Pipeline([ ('scaler', StandardScaler()), ('model', LogisticRegression(max_iter=1000)), ]) pipe.fit(X_train, y_train) print(pipe.score(X_test, y_test))
Each step has a name. That lets you inspect pipe.named_steps['scaler'].mean_ and tune hyperparameters with the step name as a prefix, such as 'model__C'. The pipeline behaves like any other estimator: it has fit, predict and score, and it can be passed straight into cross_val_score.
How do you handle numeric and categorical columns with ColumnTransformer?
Numeric and categorical columns need different treatment. ColumnTransformer applies one transformer per column group and joins the results into a single matrix.
from sklearn.compose import ColumnTransformer from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder num = ['age', 'income'] cat = ['city', 'plan'] pre = ColumnTransformer([ ('num', Pipeline([('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]), num), ('cat', Pipeline([('imputer', SimpleImputer(strategy='most_frequent')), ('onehot', OneHotEncoder(handle_unknown='ignore'))]), cat), ]) model = Pipeline([('pre', pre), ('clf', LogisticRegression(max_iter=1000))])
handle_unknown='ignore' avoids an error when a category appears at predict time that was not in training: the column is encoded as zeros instead of breaking predict. The remainder parameter controls what happens to columns you did not list, and by default they are dropped.
Because the ColumnTransformer sits inside the Pipeline, the imputer and the encoder are also fit only on the training fold. The median and the category list never see the validation rows.
How do you use the pipeline inside cross_val_score and GridSearchCV?
The rule is simple: pass the whole pipeline, never a matrix you already transformed.
from sklearn.model_selection import cross_val_score, GridSearchCV scores = cross_val_score(model, X, y, cv=5, scoring='roc_auc') print(scores.mean(), scores.std()) params = {'clf__C': [0.1, 1, 10], 'pre__num__scaler': ['passthrough', StandardScaler()]} search = GridSearchCV(model, params, cv=5, scoring='roc_auc') search.fit(X, y) print(search.best_params_)
In GridSearchCV every hyperparameter combination refits the pipeline on every fold, so the choice of C is also evaluated without leakage. The same holds for feature selection when it is a pipeline step. After the search, search.best_estimator_ already carries the fitted preprocessing, so predict on new data applies exactly the transformations learned during training.
How do you check that the pipeline is really preventing leakage?
Two checks tell you whether the pipeline is doing its job. First, compare the cross-validation score of the pipeline with the score you get when you preprocess the full dataset first. The second number is usually higher, and that gap is the leakage. Second, confirm that no fit call touches the full X before the split: search your code for fit_transform on the whole frame.
The table below summarizes where each piece of information is allowed to come from in the two setups.
Where can you practice this end to end?
Pipeline and ColumnTransformer sit in the machine learning part of the Python for Data Science and Analytics course at python.paanalytics.net, next to feature selection and cross-validation. The course runs from the basics — IDE and Jupyter Notebook setup, NumPy and Pandas, user-defined functions, loops and conditionals, data visualization, cleaning and outlier detection — through linear and logistic regression, K-Means, SVM, Naive Bayes, decision trees, Random Forest, Gradient Boosting, XGBoost and LightGBM.
It closes with an end-to-end project covering exploratory analysis and machine learning. Lessons are recorded in high quality and watched at your own pace, with guided exercises and real market projects for your portfolio. Access is unlimited with no expiry, there is a certificate of completion and an exclusive community for networking, and you do not need to know how to program before starting. Enrollment goes through the Hotmart checkout, by card or boleto, at R$ 470 or 12 installments of R$ 20,37.
| Step | Preprocessing before the split | Preprocessing inside the Pipeline |
|---|---|---|
| Scaler parameters (mean, std) | Computed on all rows, validation included | Computed on the training fold only |
| Missing-value imputation | Median taken from the full dataset | Median taken from the training fold only |
| One-hot categories | Category list built from all rows | Category list built from the training fold |
| Cross-validation score | Optimistic, because validation rows shaped the parameters | Honest, because validation rows were only transformed |
| Grid search | Tuning and preprocessing share the same information | Each combination refits preprocessing per fold |
| Predicting on new data | Depends on remembering to reuse the old objects | best_estimator_ applies the stored transformations |
Behavior described follows the scikit-learn Pipeline, ColumnTransformer and model_selection APIs. No benchmark numbers are claimed.
See the course and enroll through the Hotmart checkout
Secure payment via Hotmart, up to 12 installments.
Enroll now Product siteFrequently asked questions
Does wrapping everything in a Pipeline make cross-validation slower?
Yes, in the sense that preprocessing is refit once per fold instead of once overall. That extra work is the price of an honest estimate: the parameters are learned from the training fold only, so the validation score reflects data the model has not seen.
Can feature selection live inside the Pipeline too?
Yes. SelectKBest, RFE and similar selectors implement fit and transform, so they can be a step before the estimator. Tune their parameters with the step prefix, for example 'select__k', and the selection is refit on each training fold rather than on the full dataset.
What if I need a custom transformation?
Write a class that inherits from BaseEstimator and TransformerMixin and implements fit and transform, storing anything learned in fit. Put it in the pipeline like any built-in step. The rule is that fit must only read the data it receives, which during cross-validation is the training fold.
Is it still leakage if I split with train_test_split before preprocessing?
No, as long as the split happens before any fit. Fitting the scaler on X_train only is already correct. The pipeline is the safer habit because it keeps that ordering automatic when you later move to cross-validation or grid search.
How does the pipeline handle missing values and unseen categories at predict time?
The imputer stores the statistic it learned from the training fold and applies it to new rows. For categorical columns, OneHotEncoder with handle_unknown='ignore' encodes a category it never saw as zeros, so predict returns a result instead of raising an error.