Concepts / Understanding Pipelines

Understanding Pipelines

The Pipeline class packages those steps into one Python object that follows the fit, predict, and transform interface.

  • Programming

The Model Is Rarely the Whole Workflow

Many beginners picture a machine learning workflow as a single step. You choose a model, fit it on the training data, and then call predict on new data. In that picture the model is the whole story. Any cleaning, scaling, or feature extraction that happened earlier looks like a one-time preparation that can be forgotten once the model exists.

What do you think happens?

Before the model ever sees the training data, what might happen to that data along the way?

  • Nothing, the model reads the raw data directly

  • Several steps transform it, and each step passes its output to the next

Reveal answer
Answer:

Several steps transform it, and each step passes its output to the next

Real applications of machine learning rarely use a model in isolation. Several processing steps transform the data before the model receives it, and the output of one step becomes the input of the next.

This article follows one idea from start to finish. The mistake in the single-step picture is not really about the model. The workflow was treated as a set of separate actions the programmer has to remember, when it is really one connected chain. The Pipeline class is the tool that turns that chain into something the programmer can hold in one hand.

A Workflow as a Chain of Steps

A processing step is any operation that takes data in, changes it, and hands the result onward. Each step has its own job. A scaler adjusts the numbers in the features, and a classifier takes those adjusted features and produces predictions. The important rule is that the output of one step becomes the input of the next, so the steps form a path rather than a pile of unrelated actions.

Raw featuresFeature scalertransforms the featuresClassifierreceives scaled featuresPredictionspasses data inhands over scaled outputproduces output
How does raw data move from one processing step to the next, and where does the model receive its input?

The diagram shows the chain as a single path. Data enters at one end, each step hands its result to the next, and the classifier produces the output. The model is only the last link. If you think only about the last link, the earlier links are easy to overlook, and that is exactly where the risk lies.

The Pipeline Object and Its Interface

The Pipeline class packages those steps into one Python object. The phrase single Python object is the important part. Once the chain is wrapped in one object, the programmer works with that object instead of juggling each step separately. The object follows the fit, predict, and transform interface, so calling fit on the pipeline trains the whole chain, and calling predict on the pipeline runs new data through the whole chain.

Definition

A pipeline is a single object that holds an ordered list of processing steps and passes data through them in order, so that fit and predict act on the whole chain at once.

python
Notes on the code
  • Each step is a (name, object) pair, so every step has a label the programmer can refer to later
  • The steps are listed in the order the data should travel through them
  • fit on the pipeline trains the scaler and then the classifier on the training data
  • predict on the pipeline sends the new data through the scaler and then the classifier

In this example X_train, y_train, and X_test are assumed to already exist, holding training features, training labels, and test features. The example is an original illustration of the idea, not a listing from the source. The point to notice is that the programmer writes the chain once, inside the pipeline, and then calls fit and predict on a single object.

Following Data Through fit and predict

Worked example

Tracing one training call and one prediction call

Using the pipe object above, what happens when fit is called on the training data, and what happens when predict is called on the test data?

  1. 1
    Call fit on the pipeline

    The pipeline passes X_train to the scaler first. The scaler learns what it needs from the training features and then transforms them.

  2. 2
    Hand the transformed data onward

    The scaled training features become the input of the classifier. The classifier is trained on those scaled features and the training labels y_train.

  3. 3
    Call predict on the pipeline

    The new data X_test goes through the same scaler and the same classifier. The programmer does not write a separate transform line for the test data.

  4. 4
    Receive the output

    The classifier produces predictions, and those predictions come back as the output of the single predict call.

Result

One fit call trained the whole chain, and one predict call ran new data through the whole chain. Each hand-off between steps happened inside the pipeline rather than in the programmer's code.

Notice what the pipeline is doing for you. The hand-offs between steps are written down once, inside the object. The programmer does not repeat each hand-off by hand every time the workflow runs.

Two Mistakes in Hand-Built Chains

The source names two mistakes that happen when processing chains are built without the Pipeline class. Both come from the same root problem: each step has to be remembered and applied correctly in the right place. The code below shows the same workflow written by hand, with the steps called explicitly.

python
Notes on the code
  • fit_transform learns from the training features and transforms them in one call
  • The test features must also be transformed, and this line is easy to forget or to write incorrectly
  • Every hand-off is a variable the programmer must track and pass to the right place
  • Common mistake

    Forgetting to apply a transformer to the test set

    What it looks like

    The model is fit on scaled training features, but predict is called on the raw X_test.

    Why it fails

    The model was trained on values in one scale and is asked to predict on values in another, so its predictions are not meaningful for the data it will actually see.

    Do this instead

    Keep every transformer in the chain so that the same transformation is applied to the test data automatically, as in the pipeline version.

  • Common mistake

    Applying the steps in the wrong order

    What it looks like

    The classifier is fit on the raw features, and the scaler is applied afterwards.

    Why it fails

    Each step's output is supposed to be the next step's input. When the order is wrong, the classifier never sees the data in the form the workflow was designed for.

    Do this instead

    Write the steps in the order the data should travel, which is how a pipeline is defined as an ordered list.

The source states that a pipeline reduces the likelihood of these errors. It does not promise that errors become impossible. What changes is that the order and the set of transformations are fixed once, in one place, instead of being re-typed each time the workflow runs.

How Leakage Hides in a Split

A subtler version of the same problem appears when a preprocessing step is fit on the full dataset before the data is split into training and test portions. The step then learns something about the test data, and the evaluation no longer measures how the workflow would behave on truly unseen data. The source makes the related point that if a scaler sits outside the evaluation loop while the model sits inside it, the scores can be misleading, because the evaluation is no longer testing the complete workflow.

Fit scaler on alldataSplit into trainand testSplit into train andtestFit scaler ontraining partScore on testScore on testthenthenthenthen
What changes when a scaler is fit on all the data before the train/test split compared with fitting it only on the training portion?

In the before column, the scaler has already seen the test portion when it learned its settings. In the after column, the scaler is fit only on the training part, and the test portion is transformed using those training-based settings. Placing the whole chain in a single pipeline keeps the evaluated object identical to the workflow you intend to use, so the split and the fitting happen in the correct order.

Every Step Refits Inside Each Fold

The source singles out two evaluation methods where the Pipeline class matters most: model evaluation using cross-validation, and parameter selection using grid search. In both cases the processing steps are repeatedly applied to different portions of the data, so the steps must be captured together rather than treated as one-off actions. Cross-validation splits the data into several folds. For each fold, a portion is held out for scoring and the rest is used for training. When the workflow is a pipeline, the scaler and the classifier are both refit on that fold's training portion, and the held-out portion is scored with the result.

python
Notes on the code
  • The whole pipeline object is passed in, so every step is refit within each fold
  • cv=5 requests five folds in this illustration
  • The result is one score per fold
Fold 1 training partscaler and classifier refitScore held-out partfold 1 scoreFold 2 training partscaler and classifier refitScore held-out partfold 2 scoreFold 3 training partscaler and classifier refitScore held-out partfold 3 scorethennext foldthennext foldthen
What happens in each cross-validation fold, and which steps are refit on that fold's training data?

The loop repeats the same pattern for every fold. Because the scaler is part of the pipeline, it is refit on each fold's training portion, just as the classifier is. If the scaler sat outside the loop, it would be fit once on data that includes the held-out portions of later folds, and the scores would again stop reflecting the complete workflow.

Trial and Error Over Processing Choices

The source observes that choosing the right combination of feature extraction, preprocessing, and models is somewhat of an art, and often requires trial and error. Pipelines make that search far simpler. Because each candidate combination can be packaged as a pipeline, the programmer can swap one step for another and rerun the same workflow without rebuilding every hand-off by hand.

The benefit is not that the pipeline chooses a good combination for you. It is that the cost of trying a combination drops, so more combinations can be tested with less chance of an error creeping in during each attempt. Parameter selection with grid search applies the same idea: the settings of different steps are varied together as one search over the whole chain, and every candidate is evaluated on the complete workflow.

Check Your Understanding of the Chain

EASY

A colleague builds a workflow with a scaler and a classifier. They call scaler.fit_transform on X_train, call model.fit on the scaled result, and then call model.predict directly on X_test without transforming it. Which mistake from this article is happening, and how would you rewrite the workflow so the mistake cannot recur?

Hints
  • Compare which steps are applied to the training data with which steps are applied to the test data.
  • Think about how a single pipeline object fixes the set of steps and their order.

Key Takeaways

  • A real machine learning workflow is usually a sequence of processing steps, and the output of each step becomes the input of the next, so the model is only the final link in the chain.
  • The Pipeline class packages those steps into one Python object that follows the fit, predict, and transform interface, so fit trains the whole chain and predict runs new data through the whole chain.
  • Hand-built chains are prone to forgetting transformers on the test set and applying steps in the wrong order, and a pipeline reduces the likelihood of these errors by fixing the steps and their order in one place.
  • Capturing every step in a pipeline matters for cross-validation and grid search, because each fold or candidate must refit the complete workflow, and a scaler left outside the loop can make the scores misleading.

Related concepts

More concepts starting with U