Preprocessing pipelines and data leakage
scikit-learn 1.9.1
Combine preprocessing and prediction so that each learned step sees only training data.
On this page
Keep the test set out of fitting
Leakage means information unavailable at prediction time affects training or evaluation. Split before fitting scalers, imputers, or feature selectors. A Pipeline fits transforms on training data and reuses those fitted transforms on test rows.
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
model = make_pipeline(StandardScaler(), LinearRegression())
model.fit([[2], [4], [6]], [5, 9, 13])
print(round(float(model.predict([[8]])[0]), 2))
Download image
Example output
17.0
Handle mixed data types
Use ColumnTransformer when different columns need different transformations. For example, impute or scale numeric values and one-hot encode category values. Put the ColumnTransformer inside the pipeline so its fitted parameters stay within each training fold.