scikit-learn Pipelines and Model Persistence

Composing preprocessing and models into a single leak-proof, tunable, saveable object ready for reuse and deployment.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Hyperparameter Tuning

A Pipeline chains transformers and a final estimator so that fit and predict run every step in the right order. It is the single best habit for avoiding leakage and for shipping models.

Building blocks

  • Pipeline / make_pipeline: sequential steps.
  • ColumnTransformer: different preprocessing per column group (numeric, categorical, text).
  • FunctionTransformer and custom transformers (subclass BaseEstimator, TransformerMixin) for your own feature code.
  • Parameter names like model__max_depth let you tune any step's settings in GridSearchCV.

Why it matters

  • Preprocessing is refit inside every CV fold automatically.
  • The same object transforms training data and live requests, so there is no training/serving skew from reimplemented preprocessing.
  • One artifact to version and deploy.

Persistence

Save with joblib.dump or skops. Pickled models are tied to library versions, so record them, and never load pickles from untrusted sources because unpickling can execute code. For cross-language serving consider ONNX.

Good enough to move on when your whole modelling workflow is one pipeline that you tune with CV, save to disk, reload in a fresh process and use to predict on raw input rows.

Key concepts

  • Pipeline and make_pipeline
  • ColumnTransformer
  • Custom transformers
  • Tuning pipeline parameters
  • joblib and skops persistence
  • ONNX export

Mini project

Package your best Telco Churn model as a single Pipeline with ColumnTransformer, tune it with GridSearchCV, save it with joblib, and write a small script that loads it and scores a CSV of raw customers.

Check yourself

How does using a Pipeline prevent training/serving skew?

Free resources