← Courses

Intermediate Machine Learning

AI / ML

Better Workflow · Lesson 4 of 7

Pipelines

Keeping your steps clean

So far, preprocessing (imputing, encoding) and modelling are separate steps you run by hand. That gets messy and error prone, especially once you split data. A pipeline bundles all the steps into one object you fit and predict with as a unit. The benefits:

  • Cleaner code: you stop juggling training and validation data through every step by hand.
  • Fewer bugs: you cannot forget a step or apply it inconsistently between train and validation.
  • Easier to deploy: the whole preprocessing-plus-model bundle moves as one piece.
  • Better validation: cross-validation (next lesson) needs this to work correctly.

You build one in three steps: define the preprocessing, define the model, then bundle them.

A ColumnTransformer applies the right preprocessing to each kind of column (numeric vs categorical), and a Pipeline chains that to the model:

Python

The payoff

Notice two things. First, you fit the whole bundle in one line: the pipeline imputes, encodes, and trains the model together. Second, you call predict on the raw validation data, and the pipeline preprocesses it for you automatically, the exact same way it preprocessed training. You can never forget a step, mismatch the columns, or leak validation data into preprocessing. This is how real projects are built.

Practice

Run the cell. Then change the model from RandomForestRegressor to DecisionTreeRegressor(random_state=1) (remember to import it) and re-run. Did the MAE go up or down? Pipelines make swapping models this easy.

You’re reading for free. Sign in to keep your progress and earn a certificate when you finish.Sign in to keep my progress →