Most data leakage in machine learning does not come from a clever mistake. It comes from preprocessing the whole dataset before splitting it. scikit-learn’s Pipeline and ColumnTransformer exist to make the safe way the easy way: every preprocessing step is learned from training data only, every time.
The problem with preprocessing by hand
Suppose you standardize your features on the full dataset, then split into train and test sets. The scaler’s mean and standard deviation were computed using the test rows, so a small amount of test information has leaked into training, and your scores look slightly better than they should. The same happens with imputing missing values or encoding categories. This is the situation described in data leakage, and it is easy to do without noticing.
What a Pipeline does
A Pipeline chains steps together: zero or more transformers followed by a final model. When you call fit, each transformer learns its settings from the training data and passes its output to the next step. When you call predict, the same learned settings are applied to new data. Because the whole chain behaves like one model, you can cross-validate it, tune it and save it as a single object.
What ColumnTransformer adds
Real tables mix column types. Numeric columns usually need imputing and scaling, and categorical columns need encoding. A ColumnTransformer applies a different set of steps to each group of columns and joins the results, so one preprocessing object handles the whole table.
A complete example
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
numeric = ["tenure", "monthly_charges"]
categorical = ["contract"]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), numeric),
("cat", OneHotEncoder(handle_unknown="ignore"), categorical),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
Here X is a DataFrame containing those columns and y is the target. The key point is the last line: during cross-validation, the imputer, scaler and encoder are refit on each training fold, so the validation fold never influences them.
Why each step is there
- Imputation fills missing numbers using a statistic learned from training data only. Choosing the method well is covered in handling missing data.
- Scaling puts numeric features on a comparable scale, as explained in normalization vs standardization.
- Encoding turns categories into numbers. The option
handle_unknown="ignore"stops the model crashing when it meets a category it did not see in training. Other encodings are compared in categorical encoding methods.
Benefits beyond leakage
A pipeline gives you one object to save, version and load, so training and prediction use identical preprocessing, which prevents a whole class of bugs in production. The saved pipeline can be served directly, as in serving a model with FastAPI, and its settings and scores can be recorded with MLflow experiment tracking. The model step here is a logistic regression, and you can swap in any other estimator without touching the preprocessing.
Common mistakes
- Fitting a transformer on all the data and then putting only the model in a cross-validation loop.
- Forgetting that the target must not be part of the feature columns passed to the transformer.
- Tuning hyperparameters outside the pipeline, which leaks again. Pass the whole pipeline to the search object instead.
- Dropping columns by position, which breaks when the column order changes. Use column names.
See it in a project
My Telecom Churn Prediction project is built around a scikit-learn pipeline.
A quick checklist
- Is every preprocessing step inside the pipeline, not applied beforehand?
- Do numeric and categorical columns get their own treatment?
- Does the encoder handle unseen categories?
- Do you cross-validate and tune the whole pipeline together?
- Do you save and load the pipeline as one object?
If you want your models built and deployed this way, see my machine learning and MLOps service.
FAQ
What is a scikit-learn Pipeline?
It is an object that chains preprocessing steps and a final model into one, so fitting and predicting apply the same steps in the same order, with each step learned from training data only.
How does a Pipeline prevent data leakage?
During cross-validation or fitting, every transformer is refit on the training portion only, so statistics such as means and category lists never come from validation or test data.
What does ColumnTransformer do?
It applies different preprocessing steps to different columns, such as scaling for numbers and one-hot encoding for categories, and combines the results into one feature matrix.

