🎓 A1Learner
🔍
0 of 50 lessons completed

Python ML Pipelines: Preprocessing Plus Model in One Object

A pipeline joins cleaning steps and a model into one object. You fit it once, and it runs every step in order.

One object holds the steps

A pipeline lists its steps by name. Clean runs first, then the model runs.

from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([("clean", StandardScaler()), ("model", LogisticRegression(max_iter=1000))])
print([name for name, step in pipe.steps])

Different columns get different cleaning

Numbers are filled and scaled. Words are filled and one-hot coded. Eight columns come out.

import seaborn as sns
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = sns.load_dataset("titanic")
numbers = ["age", "fare", "pclass"]
words = ["sex", "embarked"]
cleaner = ColumnTransformer([("num", Pipeline([("fill", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numbers), ("cat", Pipeline([("fill", SimpleImputer(strategy="most_frequent")), ("code", OneHotEncoder(handle_unknown="ignore"))]), words)])
changed = cleaner.fit_transform(df[numbers + words])
print(changed.shape)

Fit once, predict at once

One fit call cleans the training rows and trains the model. Predict then needs only the raw test rows.

import seaborn as sns
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = sns.load_dataset("titanic")
numbers = ["age", "fare", "pclass"]
words = ["sex", "embarked"]
cleaner = ColumnTransformer([("num", Pipeline([("fill", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numbers), ("cat", Pipeline([("fill", SimpleImputer(strategy="most_frequent")), ("code", OneHotEncoder(handle_unknown="ignore"))]), words)])
pipe = Pipeline([("clean", cleaner), ("model", LogisticRegression(max_iter=1000, random_state=42))])
X = df[numbers + words]
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
pipe.fit(X_train, y_train)
print([int(p) for p in pipe.predict(X_test[:3])])

Example

import seaborn as sns
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

df = sns.load_dataset("titanic")
numbers = ["age", "fare", "pclass"]
words = ["sex", "embarked"]
X = df[numbers + words]
y = df["survived"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

def build_pipeline():
    cleaner = ColumnTransformer([("num", Pipeline([("fill", SimpleImputer(strategy="median")), ("scale", StandardScaler())]), numbers), ("cat", Pipeline([("fill", SimpleImputer(strategy="most_frequent")), ("code", OneHotEncoder(handle_unknown="ignore"))]), words)])
    return Pipeline([("clean", cleaner), ("model", LogisticRegression(max_iter=1000, random_state=42))])

first = build_pipeline()
first.fit(X_train, y_train)
first_score = accuracy_score(y_test, first.predict(X_test))

second = build_pipeline()
second.fit(X_train, y_train)
second_score = accuracy_score(y_test, second.predict(X_test))

names = first.named_steps["clean"].get_feature_names_out()
print("Columns after cleaning:", len(names))
print("First fit score:", round(first_score, 4))
print("Second fit score:", round(second_score, 4))

Key points

  • Pipeline: one object that holds cleaning steps plus a model, in order
  • ColumnTransformer: a step that gives different columns different cleaning
  • Use a Pipeline to fit the cleaning and the model with one call
  • Use a ColumnTransformer to scale numbers and encode words in one pass
  • Pipeline step: one named job inside a pipeline, like fill, scale, or model
  • The same pipeline gives the same score every time it is fit on the same data

In this example, the pipeline is built by a small helper, so both fits use the same steps. The ColumnTransformer fills and scales the three number columns, and it fills and one-hot codes the two word columns. The model is logistic regression. The pipeline is fit twice on the same training rows, and each fit scores the same test rows. Both scores match, because the same steps run the same way every time. The cleaning turns five raw columns into eight columns, and the printout shows that count.

Note

A pipeline still needs a split first, because the test rows stay untouched until scoring.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

What does a Pipeline do when you call fit on it?