Skip to content

34. The scikit-learn workflow

Module 33 turned raw columns into features, one transformer at a time. This module turns those pieces into a workflow that you can trust and reuse. You learn the one interface that every scikit-learn object shares, split the data so the test score is honest, chain every step into a single Pipeline, treat numeric and text columns differently with a ColumnTransformer, write your own transformers, measure a model with cross-validation and save the whole thing to a file. Every example uses the churn data in data/customers.csv.

You also close a loop from Part 3. In modules 18 to 22 you built minilearn, a small scikit-learn look-alike in pure Python. Here you rebuild its StandardScaler and its KNNClassifier (with the distance strategy of module 22) with NumPy on scikit-learn’s real base classes, prove that they give the same numbers as the library, pass scikit-learn’s own estimator checks, and run them inside a real Pipeline.

  • Use the estimator API: fit, predict, transform and score, hyperparameters versus learned _ attributes, get_params, set_params and clone.
  • Split data with train_test_split, keep the class balance with stratify, and compare a model with a baseline.
  • Chain preprocessing and a model with Pipeline and make_pipeline, read its steps and set nested parameters with the __ syntax.
  • Preprocess numeric and categorical columns in one step with ColumnTransformer, make_column_selector, FunctionTransformer, get_feature_names_out and set_output(transform="pandas").
  • Write custom transformers and classifiers on BaseEstimator, TransformerMixin and ClassifierMixin, and test them with scikit-learn’s estimator checks.
  • Estimate performance with KFold, StratifiedKFold, cross_val_score and cross_validate, report mean ± standard deviation, and save a fitted pipeline with joblib.

The lesson page runs top to bottom in one namespace. The first block fixes the pandas display and loads the 5,000 customers.

import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.max_columns", 12)
pd.set_option("display.precision", 3)
customers = pd.read_csv("data/customers.csv")
print(customers.shape)
print(customers.dtypes.value_counts())
Output
(5000, 15)
str 6
int64 6
float64 3
Name: count, dtype: int64

The file has 15 columns: an id, a signup date, 4 text columns, 8 numeric columns and the target churned (1 when the customer cancelled). In pandas 3, text columns load with the str dtype.

The estimator API: one interface for every model

Section titled “The estimator API: one interface for every model”

scikit-learn has more than 200 models and preprocessing tools. You can learn them one by one because they all share one small interface, the estimator API. An estimator is any object that learns from data with fit(). On top of fit(), each kind adds one or two methods:

Kind Methods Examples Output
transformer fit, transform, fit_transform StandardScaler, OneHotEncoder, SimpleImputer a new feature matrix
classifier fit, predict, predict_proba, score (accuracy) LogisticRegression, KNeighborsClassifier class labels or probabilities
regressor fit, predict, score (R²) LinearRegression, RandomForestRegressor numbers
meta-estimator the methods of the estimators it wraps Pipeline, ColumnTransformer, GridSearchCV depends on its parts

A classifier and a regressor are both predictors: estimators with a predict() method. A meta-estimator is an estimator built from other estimators. Every estimator reads its input in the same shape: X is a 2-D table with one row per sample and one column per feature (a DataFrame or an array of shape (n_samples, n_features)), and y is a 1-D array of targets.

Here is the whole interface in six lines. A scaler learns the mean and spread of two columns, a logistic regression learns to predict churn from the scaled values, and score() returns the accuracy: the share of correct predictions.

from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
X_small = customers[["tenure_months", "logins_last_30d"]]
y_small = customers["churned"]
scaler = StandardScaler()
X_scaled = scaler.fit(X_small).transform(X_small) # fit returns the estimator
model = LogisticRegression().fit(X_scaled, y_small)
print(X_scaled.shape, model.predict(X_scaled[:8]))
print(round(model.score(X_scaled, y_small), 3))
Output
(5000, 2) [0 0 0 0 0 0 0 0]
0.807

fit() returns the estimator itself, so you can chain .fit(...).transform(...). This model is scored on the rows it learned from, which flatters it. The section Train/test split fixes that.

An estimator holds two kinds of values:

  • A hyperparameter is a setting that you choose before training, such as C (the inverse of the regularization strength) or max_iter of LogisticRegression. You pass it to the constructor. The constructor only stores it, unchanged, as an attribute of the same name.
  • A learned attribute is a value that fit() computes from the data, such as the coefficients coef_. Its name ends with an underscore. It does not exist before fit().

This is the convention you followed in minilearn. print() shows an estimator with only the hyperparameters that differ from their defaults:

model = LogisticRegression(C=0.5, max_iter=500)
print(model)
print(hasattr(model, "coef_"))
model.fit(X_scaled, y_small)
print(hasattr(model, "coef_"), model.coef_.round(3), model.intercept_.round(3))
print(model.classes_, model.n_features_in_)
Output
LogisticRegression(C=0.5, max_iter=500)
False
True [[-1.148 -0.31 ]] [-1.793]
[0 1] 2

classes_ lists the labels the model saw, and n_features_in_ records how many columns fit() received. Asking an unfitted estimator for a prediction raises NotFittedError, the scikit-learn version of the error you wrote for minilearn:

fresh = LogisticRegression()
fresh.predict(X_scaled[:5])
Output
sklearn.exceptions.NotFittedError: This LogisticRegression instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

Every estimator has two methods for its hyperparameters. get_params() returns them as a dict. set_params(**params) changes them and returns the estimator. Both read the names of the __init__ arguments, exactly as the BaseEstimator of module 19 did with inspect.signature.

params = model.get_params()
print(len(params), params["C"], params["max_iter"])
same = model.set_params(C=2.0)
print(same is model, model)
Output
14 0.5 500
True LogisticRegression(C=2.0, max_iter=500)

Cloning: a fresh copy with the same settings

Section titled “Cloning: a fresh copy with the same settings”

sklearn.base.clone(estimator) builds a new, unfitted estimator with the same hyperparameters. In essence it calls type(est)(**est.get_params()), the same one-liner you wrote in module 19. Cross-validation and hyperparameter search clone your estimator before each fit, so no fold reuses what another fold learned.

from sklearn.base import clone
copy = clone(model)
print(copy, copy is model)
print(hasattr(model, "coef_"), hasattr(copy, "coef_"))
Output
LogisticRegression(C=2.0, max_iter=500) False
True False

Cloning works only when __init__ stores each argument unchanged. This rule matters when you write your own estimators (see Custom estimators).

Train/test split: score on data the model has not seen

Section titled “Train/test split: score on data the model has not seen”

A model is useful when it predicts well on new customers, not on the ones it learned from. This ability is called generalization. To estimate it, you hide part of the data before training. train_test_split shuffles the rows and cuts them into a training set and a test set (also called the hold-out set):

Argument Meaning Typical value
test_size share of rows for the test set 0.2 or 0.25
stratify keep the share of each class equal in both parts stratify=y for classification
random_state seed of the shuffle; the same number gives the same split 42
shuffle shuffle before cutting (default True) False only for time-ordered data

Pass X and y together. The function returns four objects in a fixed order: X_train, X_test, y_train, y_test. Only 19% of the customers churned, so a random cut can put noticeably more or fewer churners in the test set. stratify=y prevents this (see Example 1).

Always compare a model with a baseline: the score of a rule that needs no learning. For churn, “nobody churns” is already about 81% accurate. A model is only worth its complexity when it beats that number clearly. sklearn.dummy.DummyClassifier and DummyRegressor give baselines with the estimator API.

Pipeline: chain the steps into one estimator

Section titled “Pipeline: chain the steps into one estimator”

A real model needs several steps: fill the missing values, scale, encode, then predict. Done by hand, every step needs fit_transform() on the training rows and transform() on every other set of rows, in the right order. One slip, such as fitting the scaler on all rows, lets the test rows leak into training (module 33 measured how much a leak inflates a score).

A Pipeline chains the steps into one estimator. Each step is a (name, estimator) pair. Every step except the last must be a transformer. The last step can be any estimator.

flowchart TD
    subgraph FIT ["pipe.fit(X_train, y_train)"]
        A["X_train"] --> B["imputer.fit_transform"]
        B --> C["scaler.fit_transform"]
        C --> D["model.fit(Xt, y_train)"]
    end
    subgraph PREDICT ["pipe.predict(X_new)"]
        E["X_new"] --> F["imputer.transform"]
        F --> G["scaler.transform"]
        G --> H["model.predict"]
    end
    B -.->|"statistics_"| F
    C -.->|"mean_, scale_"| G
    D -.->|"coef_"| H
  • pipe.fit(X, y) calls fit_transform() on each transformer in order, passing the output to the next step, and then fit() on the last step.
  • pipe.predict(X), predict_proba(X) and score(X, y) call transform() on each transformer with what it learned, and then the method of the last step.
  • The pipeline is itself an estimator. It has get_params(), it can be cloned, and you can pass it to cross_val_score. Cross-validation then refits every step on each training fold, so preprocessing can no longer leak.

Two ways to build one:

Pipeline([...]) make_pipeline(...)
Step names you choose them: ("scale", StandardScaler()) automatic, the class name in lowercase: "standardscaler"
Use when you refer to steps by name often a quick pipeline

A pipeline routes parameters to its steps with a double underscore: <step>__<parameter>. pipe.set_params(model__C=0.1) sets C of the step named model. Names nest, so prep__num__strategy reaches inside a step inside a step. You read steps like a list or a dict: pipe[0], pipe[-1], pipe["scale"], pipe.named_steps["scale"], and pipe[:-1] is a new pipeline of every step but the last.

ColumnTransformer: different steps for different columns

Section titled “ColumnTransformer: different steps for different columns”

The customers table mixes numbers (tenure_months) and text categories (contract). Numbers need imputing and scaling. Categories need one-hot encoding. A ColumnTransformer applies a different transformer to each group of columns and puts the results side by side:

ColumnTransformer(
[
("num", numeric_steps, ["age", "tenure_months"]), # (name, transformer, columns)
("cat", OneHotEncoder(), ["plan", "contract"]),
],
remainder="drop", # columns in no list: "drop" (default) or "passthrough"
)
Tool Does
make_column_selector(dtype_include="number") picks columns by dtype when the transformer is fitted
make_column_selector(dtype_include="str") picks the text columns (pandas 3 str dtype)
make_column_selector(pattern="charges$") picks columns whose name matches a regular expression
get_feature_names_out() the names of the output columns, such as cat__contract_one-year
verbose_feature_names_out=False drops the num__ and cat__ prefixes from those names
make_column_transformer(...) the same with automatic names, like make_pipeline

get_feature_names_out() works on every built-in transformer and on pipelines. It answers the question “which coefficient belongs to which column?” after one-hot encoding has turned 4 text columns into 14 new ones.

By default, transformers return NumPy arrays and the column names are lost. est.set_output(transform="pandas") makes transform() and fit_transform() return a DataFrame with the names from get_feature_names_out() and the row index of the input. On a pipeline or a column transformer, it applies to every step inside. Call it before fit(): a step fitted on arrays complains when it later receives a DataFrame.

Some steps learn nothing. Taking the logarithm of a skewed column is the same calculation on every row and every fold. A transformer that learns nothing is stateless. A transformer that learns values in fit(), such as the median of a column, is stateful. FunctionTransformer(func) wraps a plain function as a stateless transformer, so it can sit in a pipeline:

from sklearn.preprocessing import FunctionTransformer
log_step = FunctionTransformer(np.log1p, feature_names_out="one-to-one")
charges = customers[["monthly_charges"]].head(3)
print(log_step.fit_transform(charges).round(3))
print(log_step.get_feature_names_out())
Output
monthly_charges
0 4.451
1 4.031
2 4.692
['monthly_charges']

np.log1p(x) computes log(1 + x), which is defined at 0. feature_names_out="one-to-one" says “each output column keeps the name of its input column”, so get_feature_names_out() works. Use a named function, not a lambda, in a pipeline that you plan to save: pickle cannot save a lambda.

When no built-in transformer does what you need, write one. scikit-learn gives you the same building blocks you wrote in module 19:

Base class (sklearn.base) Gives you Your minilearn version
BaseEstimator get_params, set_params, __repr__, cloning support BaseEstimator with inspect.signature
TransformerMixin fit_transform (calls fit(X, y).transform(X)), and set_output when the class also has get_feature_names_out TransformerMixin.fit_transform
ClassifierMixin score (accuracy), and marks the estimator as a classifier ClassifierMixin.score
RegressorMixin score (R²), and marks the estimator as a regressor RegressorMixin.score
OneToOneFeatureMixin get_feature_names_out when each output column matches one input column none

The rules are the ones you already know:

  1. List the mixins first and BaseEstimator last: class Clipper(TransformerMixin, BaseEstimator). The MRO then finds the mixin methods first.
  2. __init__ takes hyperparameters as keyword arguments with defaults and stores each one unchanged under the same name. No validation and no computation in __init__. Otherwise get_params() and clone() break.
  3. fit(X, y=None) validates the hyperparameters and the data, computes the learned attributes (names ending in _) and returns self. A transformer accepts y=None even when it ignores y, because a pipeline passes y to every step.
  4. transform() and predict() first check that the estimator is fitted with check_is_fitted(self), and never change the learned attributes.

Your final minilearn (module 22) made some different design choices. This table maps each one to scikit-learn:

Final minilearn (module 22) scikit-learn
own BaseEstimator: get_params, set_params, __repr__ from inspect.signature sklearn.base.BaseEstimator: the same idea
fit() is a template method: it validates, then calls the _fit() hook no template method: each estimator writes fit() itself and calls helper functions
check_X() and _check_input() sklearn.utils.validation.validate_data(self, X, reset=...)
NotFittedError, check_is_fitted() sklearn.exceptions.NotFittedError, sklearn.utils.validation.check_is_fitted()
KNNClassifier(distance=...): a name or a function, resolved in fit() into distance_ KNeighborsClassifier(metric=...): a name or a function
@register("knn") and make_model("knn", n_neighbors=15) no registry: keep a dict of template estimators and call clone(template).set_params(...); sklearn.utils.all_estimators() lists the classes
the module 20 Pipeline: __len__, __getitem__ by index, name and slice sklearn.pipeline.Pipeline (also a BaseEstimator): len(pipe), pipe[0], pipe["scale"], pipe[:-1]; for step in pipe gives the estimators, pipe.steps the (name, estimator) pairs

Why no template method? scikit-learn estimators have very different fit() signatures: some take sample_weight, some take groups, some take no y. One fixed template would suit few of them. So scikit-learn gives small helpers (validate_data, check_is_fitted, check_classification_targets) and enforces the contract with tests instead: sklearn.utils.estimator_checks runs about 50 checks on any estimator (Example 6 runs them).

The helper sklearn.utils.validation.validate_data(self, X) does the input work: it converts X to a NumPy array, rejects missing values unless you allow them, and records n_features_in_ (and feature_names_in_ for a DataFrame). With reset=False, it instead checks that new data has the same columns as the data seen in fit(). Example 6 and Example 7 apply these rules.

Cross-validation: a score with an error bar

Section titled “Cross-validation: a score with an error bar”

One train/test split gives one number, and that number depends on which rows landed in the test set. k-fold cross-validation (CV) repeats the evaluation kk times. It cuts the training data into kk equal parts called folds. Each round trains on k−1k - 1 folds and scores on the remaining one, so every row is used for scoring exactly once:

Round Fold 1 Fold 2 Fold 3 Fold 4 Fold 5
1 score train train train train
2 train score train train train
3 train train score train train
4 train train train score train
5 train train train train score

Report the mean of the kk scores s1,…,sks_1, \dots, s_k and their standard deviation:

sˉ=1k∑i=1ksistd=1k∑i=1k(si−sˉ)2\bar{s} = \frac{1}{k}\sum_{i=1}^{k} s_i \qquad \text{std} = \sqrt{\frac{1}{k}\sum_{i=1}^{k} (s_i - \bar{s})^2}

The standard deviation says how much the score moves when the data changes a little. Two models whose means differ by less than about one standard deviation are not clearly different.

Tool Does
KFold(n_splits=5, shuffle=True, random_state=42) 5 folds of random rows
StratifiedKFold(n_splits=5, shuffle=True, random_state=42) 5 folds, each with the same class shares as y; use it for classification
cross_val_score(est, X, y, cv=..., scoring=...) an array of kk scores for one metric
cross_validate(est, X, y, cv=..., scoring=[...], return_train_score=True) a dict of arrays: several metrics, fit and score times, training scores

scoring takes a name such as "accuracy", "roc_auc", "f1", "r2" or "neg_root_mean_squared_error". For errors, scikit-learn returns the negative value, so that “higher is better” holds for every scoring name. With cv=5, scikit-learn uses StratifiedKFold(5) for a classifier and KFold(5) for a regressor, both without shuffling. Pass a splitter object to control the shuffle.

Persistence: save a fitted pipeline with joblib

Section titled “Persistence: save a fitted pipeline with joblib”

Training can take minutes or hours. Model persistence means saving the fitted model to a file so that another program can load it and predict without training again. joblib.dump(obj, path) saves any Python object, and joblib.load(path) reads it back. joblib is a library that scikit-learn installs. It uses pickle and stores large NumPy arrays efficiently. Save the whole pipeline, not only the model: the preprocessing is part of the model.

Example 1 — Split the churn data and beat a baseline

Section titled “Example 1 — Split the churn data and beat a baseline”

Goal: Set up an honest evaluation for a churn model: separate the features from the target, split with stratify, and measure the baseline that every model must beat.

Step 1 — Separate the features from the target

Section titled “Step 1 — Separate the features from the target”
X = customers.drop(columns=["customer_id", "signup_date", "churned"])
y = customers["churned"]
print(X.shape, y.shape)
print(f"churn rate: {y.mean():.4f}")
Output
(5000, 12) (5000,)
churn rate: 0.1926

customer_id and signup_date are dropped because they identify a customer but carry no general rule. A model that learns ids memorizes rows. The 12 remaining columns are the features.

from sklearn.model_selection import train_test_split
for seed in [0, 1, 2, 3]:
_, _, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=seed)
print(f"random_state={seed}: train {y_tr.mean():.4f} test {y_te.mean():.4f}")
Output
random_state=0: train 0.1928 test 0.1920
random_state=1: train 0.1925 test 0.1928
random_state=2: train 0.1883 test 0.2056
random_state=3: train 0.1896 test 0.2016

Each seed gives a different shuffle, so the churn rate in the test set moves around the true 19.26%. The _ names the parts that this loop does not need.

X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=42
)
print(X_train.shape, X_test.shape)
print(f"train {y_train.mean():.4f} test {y_test.mean():.4f}")
print(X_test.index[:5].tolist())
Output
(3750, 12) (1250, 12)
train 0.1925 test 0.1928
[3185, 3646, 782, 2189, 1577]

With stratify=y, both parts have the same churn rate as the full data, up to one customer. The split keeps the original row index, so you can always trace a test row back to its customer. random_state=42 makes the split the same on every run, and on every machine with the same library versions.

from sklearn.dummy import DummyClassifier
baseline = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print(baseline.predict(X_test)[:8])
print(round(baseline.score(X_test, y_test), 3))
Output
[0 0 0 0 0 0 0 0]
0.807

DummyClassifier(strategy="most_frequent") ignores the features and always predicts the most common class, 0. It is right for every customer who stays, so its accuracy equals the share of non-churners. A churn model with an accuracy of 0.81 has learned nothing.

numeric_cols = ["age", "has_autopay", "tenure_months", "monthly_charges",
"support_tickets", "logins_last_30d", "avg_session_minutes"]
scaler = StandardScaler().fit(X_train[numeric_cols])
model = LogisticRegression().fit(scaler.transform(X_train[numeric_cols]), y_train)
accuracy = model.score(scaler.transform(X_test[numeric_cols]), y_test)
print(round(accuracy, 3))
Output
0.834

The scaler learns from the training rows only and then transforms both sets. The model beats the baseline, but only by a few points of accuracy. total_charges is left out here because it has 10 missing values, which LogisticRegression rejects. Example 3 adds an imputer for it.

Common mistakes:

  • Unpacking the four parts in the wrong order. The order is always X_train, X_test, y_train, y_test.
  • Splitting X and y in two separate calls. With the same random_state the two shuffles happen to match, but with a different or missing random_state they differ, and the rows no longer match their labels. stratify also needs y in the same call. Pass both to one call.
  • Reporting accuracy without the baseline. With imbalanced classes, a high accuracy can mean nothing.

Example 2 — Inspect, tune and clone an estimator

Section titled “Example 2 — Inspect, tune and clone an estimator”

Goal: Read the settings and the learned values of the churn model by name, change one setting and see its effect, and make a fresh copy for a new experiment.

model = LogisticRegression()
params = model.get_params()
print(len(params), sorted(params)[:7])
print(sorted(params)[7:])
print(params["C"], params["max_iter"], params["solver"])
Output
14 ['C', 'class_weight', 'dual', 'fit_intercept', 'intercept_scaling', 'l1_ratio', 'max_iter']
['n_jobs', 'penalty', 'random_state', 'solver', 'tol', 'verbose', 'warm_start']
1.0 100 lbfgs

These are the arguments of LogisticRegression.__init__, with their defaults. C controls how much the model may trust the data: a smaller C forces smaller coefficients, which gives a simpler model. Module 35 explains this idea, called regularization.

Step 2 — Fit on a DataFrame and read the learned attributes

Section titled “Step 2 — Fit on a DataFrame and read the learned attributes”
scaler = StandardScaler().set_output(transform="pandas")
Xs_train = scaler.fit_transform(X_train[numeric_cols])
Xs_test = scaler.transform(X_test[numeric_cols])
model.fit(Xs_train, y_train)
learned = [k for k in vars(model) if k.endswith("_") and not k.startswith("_")]
print(learned)
coefs = pd.Series(model.coef_[0], index=model.feature_names_in_)
print(coefs.sort_values().round(3))
Output
['feature_names_in_', 'n_features_in_', 'classes_', 'n_iter_', 'coef_', 'intercept_']
tenure_months -1.133
logins_last_30d -0.282
has_autopay -0.216
age -0.102
avg_session_minutes -0.068
monthly_charges 0.437
support_tickets 0.528
dtype: float64

Because the scaler returned a DataFrame, the model recorded the column names in feature_names_in_. vars(model) lists every attribute. The public ones that end in _ were created by fit(). On scaled features, the size of a coefficient compares the columns: one standard deviation more support tickets raises the churn score the most, and one standard deviation more tenure lowers it the most.

Step 3 — Change a hyperparameter and refit

Section titled “Step 3 — Change a hyperparameter and refit”
for c in [0.001, 0.01, 1.0, 100.0]:
model.set_params(C=c).fit(Xs_train, y_train)
acc = model.score(Xs_test, y_test)
size = np.abs(model.coef_).sum()
print(f"C={c:<6} test accuracy {acc:.3f} sum |coef| {size:.3f}")
Output
C=0.001 test accuracy 0.808 sum |coef| 0.780
C=0.01 test accuracy 0.831 sum |coef| 2.064
C=1.0 test accuracy 0.834 sum |coef| 2.766
C=100.0 test accuracy 0.834 sum |coef| 2.778

set_params() returns the model, so .fit() chains. A very small C shrinks the coefficients toward 0, and the model falls back toward “nobody churns”. Above C=1, the coefficients barely change. Choosing C this way on the test set is only a demonstration: real tuning uses cross-validation on the training set (module 37).

Step 4 — Clone the model for a new experiment

Section titled “Step 4 — Clone the model for a new experiment”
fresh = clone(model)
print(fresh)
print(fresh.get_params() == model.get_params(), hasattr(fresh, "coef_"))
fresh.set_params(C=0.05)
print(model.C, fresh.C)
Output
LogisticRegression(C=100.0)
True False
100.0 0.05

The clone copies the hyperparameters (C=100.0 from the last loop round) but none of the learned attributes. The two objects are independent: changing fresh leaves model alone.

Common mistakes:

  • Setting a learned attribute by hand, such as model.coef_ = .... Change hyperparameters and refit instead.
  • Expecting clone() to copy a fitted model. It returns an unfitted copy. Use copy.deepcopy() (or save and load the file) to copy a fitted one.
  • Misspelling a parameter: LogisticRegression(c=1) raises TypeError and set_params(c=1) raises ValueError. Names are case-sensitive.

Example 3 — Replace hand-written preprocessing with a Pipeline

Section titled “Example 3 — Replace hand-written preprocessing with a Pipeline”

Goal: The churn model now needs total_charges, which has missing values. Write the impute–scale–model chain by hand, then replace it with a Pipeline that gives identical predictions in one object.

from sklearn.impute import SimpleImputer
num_cols = numeric_cols + ["total_charges"]
imputer = SimpleImputer(strategy="median")
scaler = StandardScaler()
clf = LogisticRegression()
Xt_train = scaler.fit_transform(imputer.fit_transform(X_train[num_cols]))
clf.fit(Xt_train, y_train)
Xt_test = scaler.transform(imputer.transform(X_test[num_cols]))
manual_proba = clf.predict_proba(Xt_test)[:, 1]
print(manual_proba[:5].round(3))
Output
[0.152 0.205 0.141 0.241 0.062]

Three objects and six calls, and every call must be the right one: fit_transform on the training rows, transform on the test rows, in the same order. predict_proba() returns one column per class. Column 1 is the probability of churn.

Step 2 — Build the same chain as a Pipeline

Section titled “Step 2 — Build the same chain as a Pipeline”
from sklearn.pipeline import Pipeline
pipe = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
("model", LogisticRegression()),
])
pipe.fit(X_train[num_cols], y_train)
pipe_proba = pipe.predict_proba(X_test[num_cols])[:, 1]
print(pipe_proba[:5].round(3))
print(np.allclose(manual_proba, pipe_proba))
Output
[0.152 0.205 0.141 0.241 0.062]
True

One fit() and one predict_proba() do the six calls in the right order. The probabilities are identical, so the pipeline changes nothing about the math. It removes the chance of calling fit_transform on the test rows.

print(len(pipe), pipe[-1])
print(pipe.named_steps["impute"].statistics_)
print(pipe["scale"].mean_.round(1).tolist())
print(pipe[:-1].transform(X_test[num_cols]).shape)
Output
3 LogisticRegression()
[ 42. 1. 17. 58.72 1. 10. 12.8 977.61]
[42.1, 0.5, 23.3, 60.8, 1.2, 11.7, 14.3, 1399.8]
(1250, 8)

Each step keeps what it learned. The imputer stored one median per column (the last one, 977.61, fills the missing total_charges), and the scaler stored the means. pipe[:-1] is the preprocessing part alone, which shows exactly what the model receives.

Step 4 — Route parameters with the double underscore

Section titled “Step 4 — Route parameters with the double underscore”
from sklearn.pipeline import make_pipeline
auto = make_pipeline(
SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression()
)
print([name for name, _ in auto.steps])
auto.set_params(logisticregression__C=0.1, simpleimputer__strategy="mean")
print(auto.get_params()["logisticregression__C"], auto[0].strategy)
pipe.set_params(model__C=0.1)
print(pipe["model"])
Output
['simpleimputer', 'standardscaler', 'logisticregression']
0.1 mean
LogisticRegression(C=0.1)

make_pipeline names each step after its class in lowercase. <step>__<parameter> sends the value to the right step. The short names of a Pipeline you build yourself (model__C) are easier to read than logisticregression__C.

try:
auto.set_params(model__C=1.0)
except ValueError as err:
message = str(err)
print(type(err).__name__, "-", message.split(" for ")[0])
print(message[message.index("Valid"):])
Output
ValueError - Invalid parameter 'model'
Valid parameters are: ['memory', 'steps', 'transform_input', 'verbose'].

auto has no step called model, and scikit-learn refuses the unknown name instead of ignoring it. The full message also prints the whole pipeline and the pipeline’s own parameters. To see the step names, print list(auto.named_steps).

Common mistakes:

  • Putting a model in the middle of a pipeline. Every step except the last must have transform(). scikit-learn raises a TypeError at fit() time.
  • Using one underscore (model_C) instead of two. The name is then unknown.
  • Fitting the pipeline and then also fitting a step by hand. The pipeline already fitted it; a second fit on other rows overwrites what it learned.

Example 4 — Preprocess mixed columns with ColumnTransformer

Section titled “Example 4 — Preprocess mixed columns with ColumnTransformer”

Goal: Use all 12 features of customers.csv: impute and scale the 8 numeric columns, one-hot encode the 4 text columns, and fit one pipeline that you can read by column name.

from sklearn.compose import ColumnTransformer, make_column_selector
pick_numbers = make_column_selector(dtype_include="number")
pick_text = make_column_selector(dtype_include="str")
num_names = pick_numbers(X_train)
print(num_names[:4])
print(num_names[4:])
print(pick_text(X_train))
Output
['age', 'has_autopay', 'tenure_months', 'monthly_charges']
['total_charges', 'support_tickets', 'logins_last_30d', 'avg_session_minutes']
['region', 'plan', 'contract', 'payment_method']

A column selector is a small object that you call with a DataFrame. It returns the matching column names. The ColumnTransformer calls it at fit() time, so a new numeric column joins the numeric branch without code changes. In pandas 3, text columns have the str dtype, so select them with dtype_include="str".

from sklearn.preprocessing import OneHotEncoder
numeric_steps = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())
preprocess = ColumnTransformer([
("num", numeric_steps, pick_numbers),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), pick_text),
])
Xt = preprocess.fit_transform(X_train)
print(type(Xt).__name__, Xt.shape)
names = preprocess.get_feature_names_out()
print(names[:3])
print(names[-3:])
Output
ndarray (3750, 22)
['num__age' 'num__has_autopay' 'num__tenure_months']
['cat__payment_method_credit_card' 'cat__payment_method_electronic_check'
'cat__payment_method_paypal']

The numeric branch is itself a pipeline: a column transformer accepts any transformer, including a pipeline. The 4 text columns become 14 one-hot columns, so 8 + 14 = 22 features come out. sparse_output=False asks for a normal (dense) array. handle_unknown="ignore" turns a category never seen in training into all zeros instead of an error. Each name starts with its branch name: num__ or cat__.

preprocess.set_output(transform="pandas")
Xt = preprocess.fit_transform(X_train)
print(Xt.iloc[:3, [0, 2, 8, 12]])
Output
num__age num__tenure_months cat__region_East cat__plan_basic
53 -1.265 2.450 0.0 1.0
4249 0.145 -0.972 1.0 0.0
956 0.224 0.840 0.0 1.0

With pandas output, every column has its name and every row keeps its customer index, which makes debugging much easier. set_output() is called before the refit, as the rule says.

Step 4 — Fit the full pipeline and compare

Section titled “Step 4 — Fit the full pipeline and compare”
churn_model = Pipeline([
("prep", preprocess),
("model", LogisticRegression(max_iter=1000)),
])
churn_model.fit(X_train, y_train)
print(f"baseline {baseline.score(X_test, y_test):.3f}")
print(f"numeric only {accuracy:.3f}")
print(f"all features {churn_model.score(X_test, y_test):.3f}")
Output
baseline 0.807
numeric only 0.834
all features 0.836

The pipeline takes the raw DataFrame with text and missing values. Adding the contract, plan, payment method and region columns barely moves the accuracy (0.834 → 0.836). Accuracy is a coarse measure on imbalanced data; Example 5 measures the ranking quality with ROC-AUC instead. Comparing variants on the test set, as here, is only a first look: Example 5 compares them properly with cross-validation on the training rows. max_iter=1000 is a safety margin; the default of 100 iterations is already enough here (n_iter_ is 35).

Step 5 — Read the coefficients by feature name

Section titled “Step 5 — Read the coefficients by feature name”
feature_names = churn_model[:-1].get_feature_names_out()
coefs = pd.Series(churn_model[-1].coef_[0], index=feature_names)
coefs = coefs.sort_values()
print(pd.concat([coefs.head(3), coefs.tail(3)]).round(3))
Output
num__tenure_months -0.911
cat__contract_two-year -0.815
num__logins_last_30d -0.278
num__monthly_charges 0.449
num__support_tickets 0.544
cat__contract_month-to-month 0.949
dtype: float64

churn_model[:-1].get_feature_names_out() gives the 22 names in the order the model sees them. The strongest signals match the data dictionary: a month-to-month contract, more support tickets and higher charges push churn up; long tenure and a two-year contract push it down. Module 43 explains how to read coefficients with care.

Step 6 — Predict for a customer with a new category

Section titled “Step 6 — Predict for a customer with a new category”
new_customer = X_test.head(1).copy()
new_customer["region"] = "Central" # a region the model has never seen
print(new_customer[["region", "contract", "tenure_months"]])
print(churn_model.predict_proba(new_customer).round(3))
Output
region contract tenure_months
3185 Central month-to-month 11
[[0.859 0.141]]

The region columns of this customer are all 0, and the model still predicts. Without handle_unknown="ignore", transform() raises a ValueError, which in production means a failed request for one new value.

Common mistakes:

  • Selecting text columns with dtype_include=object. In pandas 3 this still works but warns that the behavior is deprecated. Use "str".
  • Listing a column in two branches. It then appears twice in the output. A column in no branch is dropped (the default remainder="drop").
  • Calling set_output(transform="pandas") after fit(). Inner steps fitted on arrays then warn about feature names. Set it first, then fit.

Example 5 — Cross-validate the churn pipeline

Section titled “Example 5 — Cross-validate the churn pipeline”

Goal: Replace the single test score with a 5-fold cross-validated score, report it as mean ± standard deviation for several metrics, and check the baseline on the same folds.

Step 1 — Compare KFold and StratifiedKFold

Section titled “Step 1 — Compare KFold and StratifiedKFold”
from sklearn.model_selection import KFold, StratifiedKFold
kf = KFold(n_splits=5, shuffle=True, random_state=42)
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
for name, cv in [("KFold", kf), ("StratifiedKFold", skf)]:
rates = [y_train.iloc[test].mean() for _, test in cv.split(X_train, y_train)]
print(f"{name:<16}", np.round(rates, 3))
Output
KFold [0.181 0.181 0.203 0.216 0.181]
StratifiedKFold [0.192 0.192 0.192 0.193 0.193]

cv.split() yields one pair of row positions per round: the training positions and the scoring positions. KFold cuts at random, so the churn rate per fold moves around. StratifiedKFold keeps it at 19.3% in every fold, so each fold score is measured on the same kind of population.

from sklearn.model_selection import cross_val_score
scores = cross_val_score(churn_model, X_train, y_train, cv=skf, scoring="roc_auc")
print(scores.round(3))
print(f"ROC-AUC: {scores.mean():.3f} ± {scores.std():.3f}")
Output
[0.806 0.811 0.826 0.825 0.796]
ROC-AUC: 0.813 ± 0.011

ROC-AUC is the probability that the model gives a random churner a higher churn probability than a random non-churner. 0.5 is a coin flip, 1.0 is a perfect ranking. Unlike accuracy, it is not fooled by the class imbalance. Module 36 covers it in depth. cross_val_score cloned the pipeline 5 times, so churn_model itself is unchanged.

Step 3 — Score several metrics with cross_validate

Section titled “Step 3 — Score several metrics with cross_validate”
from sklearn.model_selection import cross_validate
results = cross_validate(
churn_model, X_train, y_train, cv=skf,
scoring=["accuracy", "roc_auc", "f1"], return_train_score=True,
)
print(sorted(results)[:4])
print(sorted(results)[4:])
table = pd.DataFrame(results).drop(columns=["fit_time", "score_time"])
print(table.agg(["mean", "std"]).round(3))
Output
['fit_time', 'score_time', 'test_accuracy', 'test_f1']
['test_roc_auc', 'train_accuracy', 'train_f1', 'train_roc_auc']
test_accuracy train_accuracy test_roc_auc train_roc_auc test_f1 train_f1
mean 0.836 0.836 0.813 0.819 0.402 0.406
std 0.011 0.002 0.013 0.003 0.052 0.015

cross_validate returns a dict of arrays, one entry per metric for the test folds (test_...) and, with return_train_score=True, for the training folds (train_...). Training and test scores are close, so the model does not overfit: it does not memorize the training rows. F1 is low because the model finds only a part of the churners at the default threshold of 0.5; module 36 shows how to move that threshold.

Step 4 — Score the baseline on the same folds

Section titled “Step 4 — Score the baseline on the same folds”
dummy = DummyClassifier(strategy="most_frequent")
base = cross_validate(dummy, X_train, y_train, cv=skf, scoring=["accuracy", "roc_auc"])
print(f"baseline accuracy {base['test_accuracy'].mean():.3f}")
print(f"baseline ROC-AUC {base['test_roc_auc'].mean():.3f}")
Output
baseline accuracy 0.807
baseline ROC-AUC 0.500

The baseline reaches 0.807 accuracy but only 0.5 ROC-AUC. The model’s accuracy gain looks small (0.807 → about 0.84), but its ROC-AUC gain is large (0.5 → about 0.81). The same skf object gives the same folds to both, so the comparison is fair.

Step 5 — Score the chosen model on the test set once

Section titled “Step 5 — Score the chosen model on the test set once”
from sklearn.metrics import roc_auc_score
churn_model.fit(X_train, y_train)
test_auc = roc_auc_score(y_test, churn_model.predict_proba(X_test)[:, 1])
print(f"test ROC-AUC: {test_auc:.3f}")
Output
test ROC-AUC: 0.813

The test score falls inside the CV range (mean ± std), which is what you expect when the test set is a fair sample. This is the number to report.

Common mistakes:

  • Passing cv=5 and expecting shuffled folds. For a classifier, cv=5 means StratifiedKFold(5) without shuffling, which handles rows sorted by class. But when independent rows are sorted by another column, such as signup date, unshuffled folds each cover one period. Pass StratifiedKFold(5, shuffle=True, random_state=42). Truly time-ordered data is the opposite case: never shuffle it; use TimeSeriesSplit (module 40).
  • Comparing two models on different folds. Create the splitter once and pass the same object to every call.
  • Reading neg_ scores as bad. neg_log_loss of −0.37 is better than −0.45. Flip the sign to report the error.

Example 6 — Rebuild minilearn on scikit-learn’s base classes

Section titled “Example 6 — Rebuild minilearn on scikit-learn’s base classes”

Goal: Rewrite the StandardScaler and the KNNClassifier of the final minilearn (module 22), including its distance strategy, with NumPy on scikit-learn’s BaseEstimator, TransformerMixin and ClassifierMixin. Prove that they match scikit-learn’s own classes, pass scikit-learn’s estimator checks, and run in a real Pipeline with cross_val_score.

The classes go in a module file, minilearn_np.py, not in the script. Other scripts and the test file of Step 4 import them from there, and a saved model can find them later (see Persistence).

minilearn_np.py
"""minilearn rebuilt with NumPy on scikit-learn's base classes.
Module 22's minilearn wrote its own BaseEstimator, mixins, fit() template and
distance strategies. Here scikit-learn provides the base classes, and each
estimator writes fit() itself and calls validate_data().
"""
from collections.abc import Callable
import numpy as np
from sklearn.base import (
BaseEstimator,
ClassifierMixin,
OneToOneFeatureMixin,
TransformerMixin,
)
from sklearn.utils.multiclass import check_classification_targets
from sklearn.utils.validation import check_is_fitted, validate_data
type DistanceFunc = Callable[[np.ndarray, np.ndarray], np.ndarray]
def euclidean(rows: np.ndarray, point: np.ndarray) -> np.ndarray:
"""Distance from point to every row: the square root of the summed squares."""
return np.sqrt(((rows - point) ** 2).sum(axis=1))
def manhattan(rows: np.ndarray, point: np.ndarray) -> np.ndarray:
"""Distance from point to every row: the sum of absolute differences."""
return np.abs(rows - point).sum(axis=1)
DISTANCES: dict[str, DistanceFunc] = {"euclidean": euclidean, "manhattan": manhattan}
class MiniStandardScaler(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Standardize each column: z = (x - mean_) / scale_."""
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None:
self.with_mean = with_mean
self.with_std = with_std
def fit(self, X, y=None):
X = validate_data(self, X, dtype=np.float64) # sets n_features_in_
n_cols = X.shape[1]
self.mean_ = X.mean(axis=0) if self.with_mean else np.zeros(n_cols)
std = X.std(axis=0) # population std, as in minilearn
self.scale_ = np.where(std > 0, std, 1.0) if self.with_std else np.ones(n_cols)
return self
def transform(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=np.float64, reset=False)
return (X - self.mean_) / self.scale_
def inverse_transform(self, Z):
check_is_fitted(self)
return np.asarray(Z, dtype=np.float64) * self.scale_ + self.mean_
class MiniKNNClassifier(ClassifierMixin, BaseEstimator):
"""Predict the majority class of the k nearest training rows."""
def __init__(
self, n_neighbors: int = 5, distance: str | DistanceFunc = "euclidean"
) -> None:
self.n_neighbors = n_neighbors
self.distance = distance # stored unchanged; resolved in fit()
def fit(self, X, y):
X, y = validate_data(self, X, y, dtype=np.float64)
check_classification_targets(y) # rejects a continuous y
n_samples = X.shape[0]
if not 1 <= self.n_neighbors <= n_samples:
raise ValueError(
f"need 1 <= n_neighbors <= n_samples, got n_neighbors="
f"{self.n_neighbors}, n_samples={n_samples}"
)
if callable(self.distance):
self.distance_ = self.distance # the strategy, as in module 22
elif self.distance in DISTANCES:
self.distance_ = DISTANCES[self.distance]
else:
raise ValueError(
f"unknown distance {self.distance!r}; "
f"use {sorted(DISTANCES)} or a function"
)
self.classes_, self.y_codes_ = np.unique(y, return_inverse=True)
self.X_train_ = X
return self
def predict_proba(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=np.float64, reset=False)
proba = np.empty((X.shape[0], len(self.classes_)))
for i, row in enumerate(X):
dist = self.distance_(self.X_train_, row) # one distance per training row
order = np.argsort(dist, kind="stable") # equal distance: lower index
votes = np.bincount(
self.y_codes_[order[: self.n_neighbors]], minlength=len(self.classes_)
)
proba[i] = votes / self.n_neighbors
return proba
def predict(self, X):
proba = self.predict_proba(X) # checks fitted before classes_ is used
return self.classes_[proba.argmax(axis=1)] # vote ties: the smaller class

Compare it with module 22, line by line:

  • The scaler is the same idea. NumPy does each column at once with axis=0, and broadcasting applies the 1-D mean_ and scale_ to every row.
  • distance is still a strategy: a name ("euclidean", "manhattan") or any function. As in module 22, __init__ stores it unchanged and fit() resolves it into the learned attribute distance_. Each NumPy distance function takes all training rows at once and returns one distance per row, so the inner loop over training rows is gone.
  • fit() is written in each class, with no _fit() hook. The classes are named MiniStandardScaler and MiniKNNClassifier so that they do not hide scikit-learn’s classes on this page.
  • check_classification_targets(y) rejects a continuous target, and fit() refuses more neighbors than training rows, as scikit-learn’s KNeighborsClassifier does.

Step 2 — Compare the scaler with scikit-learn

Section titled “Step 2 — Compare the scaler with scikit-learn”
from minilearn_np import MiniKNNClassifier, MiniStandardScaler
knn_cols = ["tenure_months", "logins_last_30d",
"monthly_charges", "avg_session_minutes"]
ours = MiniStandardScaler().fit(X_train[knn_cols])
theirs = StandardScaler().fit(X_train[knn_cols])
print(ours.mean_.round(3), ours.scale_.round(3))
print(np.allclose(ours.mean_, theirs.mean_), np.allclose(ours.scale_, theirs.scale_))
print(np.allclose(ours.transform(X_test[knn_cols]), theirs.transform(X_test[knn_cols])))
print(ours.get_feature_names_out(), ours.n_features_in_)
Output
[23.315 11.742 60.781 14.314] [19.87 8.04 22.985 7.904]
True True
True
['tenure_months' 'logins_last_30d' 'monthly_charges' 'avg_session_minutes'] 4

np.allclose(a, b) is True when every pair of numbers agrees up to a tiny rounding tolerance. Both classes use the population standard deviation (divide by n), so the learned values and the transformed test rows match. validate_data recorded the column names, so get_feature_names_out() (from OneToOneFeatureMixin) works too.

Step 3 — Compare the classifier with scikit-learn, for both distances

Section titled “Step 3 — Compare the classifier with scikit-learn, for both distances”
from sklearn.neighbors import KNeighborsClassifier
Z_train = ours.transform(X_train[knn_cols])
Z_test = ours.transform(X_test[knn_cols])
for distance in ["euclidean", "manhattan"]:
mini = MiniKNNClassifier(n_neighbors=15, distance=distance).fit(Z_train, y_train)
real = KNeighborsClassifier(n_neighbors=15, metric=distance).fit(Z_train, y_train)
same_labels = np.array_equal(mini.predict(Z_test), real.predict(Z_test))
same_proba = np.allclose(mini.predict_proba(Z_test), real.predict_proba(Z_test))
print(f"{distance:<9} labels {same_labels} proba {same_proba} "
f"accuracy {mini.score(Z_test, y_test):.3f}")
print(mini, mini.distance_.__name__)
Output
euclidean labels True proba True accuracy 0.814
manhattan labels True proba True accuracy 0.821
MiniKNNClassifier(distance='manhattan', n_neighbors=15) manhattan

All 1,250 predictions and probabilities agree for both distances. scikit-learn calls the strategy metric; minilearn calls it distance. The comparison is fair because these four columns have almost no exact distance ties; with many ties, two correct implementations can pick different neighbors. score() came from ClassifierMixin, the same accuracy you wrote in module 19. This step reads the test set only to check that two implementations agree, not to choose a model.

Step 4 — Run scikit-learn’s estimator checks

Section titled “Step 4 — Run scikit-learn’s estimator checks”

scikit-learn ships the test suite that its own estimators must pass. parametrize_with_checks turns it into pytest tests, one per check and estimator: unfitted calls must raise NotFittedError, fit() must not change the hyperparameters, clone() must work, predictions must not depend on the row order, and so on.

test_minilearn_np.py
"""Run scikit-learn's estimator checks on the rebuilt minilearn classes."""
from sklearn.utils.estimator_checks import parametrize_with_checks
from minilearn_np import MiniKNNClassifier, MiniStandardScaler
@parametrize_with_checks([MiniStandardScaler(), MiniKNNClassifier()])
def test_sklearn_compatible(estimator, check):
check(estimator)
Terminal
pytest -q test_minilearn_np.py
Output
..........................s..............................................s.................. [ 90%]
.......... [100%]
100 passed, 2 skipped in 1.22s

Both classes pass every check that runs. The skipped checks need optional setups (such as the array API) that do not apply here. The first version of MiniKNNClassifier failed two checks: predict() read classes_ before checking that the model was fitted, and the error for too few samples did not say n_samples=1. The checks found both bugs in about a second. Module 14 explains pytest itself.

Step 5 — Run the rebuilt classes in a real Pipeline

Section titled “Step 5 — Run the rebuilt classes in a real Pipeline”
from sklearn.base import is_classifier
from sklearn.model_selection import check_cv
mini_pipe = make_pipeline(MiniStandardScaler(), MiniKNNClassifier(n_neighbors=15))
real_pipe = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15))
print(mini_pipe)
default_cv = check_cv(5, y_train, classifier=is_classifier(mini_pipe))
print(is_classifier(mini_pipe), default_cv)
mini_scores = cross_val_score(mini_pipe, X_train[knn_cols], y_train, cv=skf)
real_scores = cross_val_score(real_pipe, X_train[knn_cols], y_train, cv=skf)
print(mini_scores.round(3), np.allclose(mini_scores, real_scores))
mini_pipe.set_params(miniknnclassifier__distance="manhattan")
print(clone(mini_pipe)[-1], mini_pipe["ministandardscaler"].with_std)
Output
Pipeline(steps=[('ministandardscaler', MiniStandardScaler()),
('miniknnclassifier', MiniKNNClassifier(n_neighbors=15))])
True StratifiedKFold(n_splits=5, random_state=None, shuffle=False)
[0.807 0.808 0.817 0.801 0.795] True
MiniKNNClassifier(distance='manhattan', n_neighbors=15) True

check_cv is the function that cross_val_score uses to turn cv=5 into a splitter. Because ClassifierMixin marks the pipeline’s last step as a classifier, cv=5 would give StratifiedKFold, without shuffling; this page passes the shuffled skf instead. The pipeline repr, cloning inside cross_val_score, __ routing and indexing by name all work with your classes, and the fold scores equal scikit-learn’s. You wrote none of that code. You followed the rules, and the base classes did the rest.

Common mistakes:

  • Validating n_neighbors or distance in __init__. set_params() skips __init__, so a bad value set later is never checked. Validate in fit().
  • Forgetting return self in fit(). fit(...).transform(...) and pipelines then fail with AttributeError: 'NoneType' object has no attribute ....
  • Writing class MiniKNNClassifier(BaseEstimator, ClassifierMixin). With BaseEstimator first, its default tags win in the MRO: sklearn.base.is_classifier() returns False, and cross_val_score(cv=5) silently uses unstratified KFold folds. Mixins go on the left.
  • Defining the classes in the script that saves a model. Put them in a module, as here, so that tests, other scripts and joblib.load can import them.

Example 7 — Add a custom step, then save and reload the pipeline

Section titled “Example 7 — Add a custom step, then save and reload the pipeline”

Goal: Clip extreme values with a custom stateful transformer, log-transform the skewed charges with a FunctionTransformer, cross-validate the final pipeline, save it with joblib and check that the loaded copy predicts the same.

Step 1 — Write a stateful custom transformer

Section titled “Step 1 — Write a stateful custom transformer”
from sklearn.base import BaseEstimator, OneToOneFeatureMixin, TransformerMixin
from sklearn.utils.validation import check_is_fitted, validate_data
class QuantileClipper(OneToOneFeatureMixin, TransformerMixin, BaseEstimator):
"""Clip each column to quantiles learned on the training rows."""
def __init__(self, lower: float = 0.01, upper: float = 0.99) -> None:
self.lower = lower
self.upper = upper
def fit(self, X, y=None):
if not 0 <= self.lower < self.upper <= 1:
raise ValueError("need 0 <= lower < upper <= 1")
X = validate_data(self, X, dtype=np.float64)
self.lower_, self.upper_ = np.quantile(X, [self.lower, self.upper], axis=0)
return self
def transform(self, X):
check_is_fitted(self)
X = validate_data(self, X, dtype=np.float64, reset=False)
return np.clip(X, self.lower_, self.upper_)
clipper = QuantileClipper(upper=0.95).set_output(transform="pandas")
clipped = clipper.fit_transform(X_train[["support_tickets", "logins_last_30d"]])
print(clipper.upper_, clipped.max().to_dict())
Output
[ 3. 27.] {'support_tickets': 3.0, 'logins_last_30d': 27.0}

This is capping (also called winsorizing) with limits learned in fit(). Because the limits come from the training rows, the step must sit inside the pipeline: on each CV fold, the limits are learned from that fold’s training rows only. set_output works on your class too. TransformerMixin adds it only because OneToOneFeatureMixin gives the class get_feature_names_out(); a transformer without that method has no set_output.

log_cols = ["monthly_charges", "total_charges"]
count_cols = ["age", "has_autopay", "tenure_months", "support_tickets",
"logins_last_30d", "avg_session_minutes"]
log_steps = make_pipeline(
SimpleImputer(strategy="median"),
FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
StandardScaler(),
)
final_prep = ColumnTransformer(
[
("log", log_steps, log_cols),
("num", make_pipeline(QuantileClipper(), StandardScaler()), count_cols),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), pick_text),
],
verbose_feature_names_out=False,
)
final_model = Pipeline(
[("prep", final_prep), ("model", LogisticRegression(max_iter=1000))]
)
final_model.set_output(transform="pandas")
final_model.fit(X_train, y_train)
print(final_model[:-1].get_feature_names_out()[:9])
Output
['monthly_charges' 'total_charges' 'age' 'has_autopay' 'tenure_months'
'support_tickets' 'logins_last_30d' 'avg_session_minutes' 'region_East']

The pipeline now has three branches and a custom step. verbose_feature_names_out=False drops the branch prefixes, which is safe because no two branches produce the same name. The custom class sits next to the built-in ones and behaves the same way.

Step 3 — Cross-validate it against the earlier pipeline

Section titled “Step 3 — Cross-validate it against the earlier pipeline”
auc_4 = cross_val_score(churn_model, X_train, y_train, cv=skf, scoring="roc_auc")
auc_7 = cross_val_score(final_model, X_train, y_train, cv=skf, scoring="roc_auc")
print(f"Example 4: ROC-AUC {auc_4.mean():.3f} ± {auc_4.std():.3f}")
print(f"Example 7: ROC-AUC {auc_7.mean():.3f} ± {auc_7.std():.3f}")
print("gain per fold:", (auc_7 - auc_4).round(3))
Output
Example 4: ROC-AUC 0.813 ± 0.011
Example 7: ROC-AUC 0.824 ± 0.008
gain per fold: [0.009 0.011 0.01 0.006 0.023]

The mean gain (0.011) is about one standard deviation, which alone would not be convincing. But both pipelines were scored on the same folds, so you can compare them fold by fold. This is a paired comparison, and here the new pipeline wins on all 5 folds.

def log_variant(log_cols: list[str]) -> Pipeline:
"""The Example 4 pipeline, with log1p on log_cols and no clipping."""
plain = [c for c in num_cols if c not in log_cols]
impute = SimpleImputer(strategy="median")
branches = [
("num", make_pipeline(impute, StandardScaler()), plain),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), pick_text),
]
if log_cols:
logged = make_pipeline(
SimpleImputer(strategy="median"),
FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
StandardScaler(),
)
branches.append(("log", logged, log_cols))
return make_pipeline(ColumnTransformer(branches), LogisticRegression(max_iter=1000))
variants = [[], ["monthly_charges"], ["tenure_months"], ["total_charges"],
["monthly_charges", "total_charges"]]
for cols in variants:
model = log_variant(cols)
auc = cross_val_score(model, X_train, y_train, cv=skf, scoring="roc_auc")
print(f"log of {', '.join(cols) or 'nothing':<31} ROC-AUC {auc.mean():.4f}")
bands = pd.cut(customers["tenure_months"], [-1, 6, 12, 24, 48, 72])
print(customers.groupby(bands, observed=True)["churned"].mean().round(3))
Output
log of nothing ROC-AUC 0.8126
log of monthly_charges ROC-AUC 0.8122
log of tenure_months ROC-AUC 0.8218
log of total_charges ROC-AUC 0.8241
log of monthly_charges, total_charges ROC-AUC 0.8237
tenure_months
(-1, 6] 0.440
(6, 12] 0.196
(12, 24] 0.142
(24, 48] 0.094
(48, 72] 0.041
Name: churned, dtype: float64

Removing one part at a time and measuring the change is an ablation study (exercise M34-C13 does it for both steps). Logging monthly_charges alone gains nothing. Logging total_charges alone gives almost all the gain, and logging tenure_months alone gives most of it. The last variant has the log but no clipping, and it scores almost the same as Example 7, so the clipping adds very little.

The reason is not skewness: logistic regression does not need symmetric features. It needs the log-odds of churn to change roughly linearly with each feature. The table shows that churn falls steeply over the first months of tenure and then slowly. total_charges grows with tenure, so its log follows that steep early drop.

Step 5 — Save the pipeline and its metadata

Section titled “Step 5 — Save the pipeline and its metadata”
import json
from pathlib import Path
import platform
import joblib
import sklearn
Path("output").mkdir(exist_ok=True)
saved = joblib.dump(final_model, "output/churn_pipeline.joblib")
metadata = {
"sklearn_version": sklearn.__version__,
"numpy_version": np.__version__,
"joblib_version": joblib.__version__,
"python_version": platform.python_version(),
"features": list(X_train.columns),
"cv_roc_auc": round(float(auc_7.mean()), 3),
}
Path("output/churn_pipeline.json").write_text(json.dumps(metadata, indent=2))
print(saved)
print(sorted(metadata))
print(metadata["sklearn_version"], len(metadata["features"]))
Output
['output/churn_pipeline.joblib']
['cv_roc_auc', 'features', 'joblib_version', 'numpy_version', 'python_version', 'sklearn_version']
1.9.1 12

joblib.dump returns the list of files it wrote. The JSON file records what the model needs: the library versions, the input columns and the score you measured. A service that loads the model can check them before it unpickles anything.

Step 6 — Load the pipeline and check its predictions

Section titled “Step 6 — Load the pipeline and check its predictions”
check = json.loads(Path("output/churn_pipeline.json").read_text())
if check["sklearn_version"] != sklearn.__version__: # check before unpickling
raise RuntimeError("model saved with another scikit-learn: retrain or pin it")
loaded = joblib.load("output/churn_pipeline.joblib") # only files you trust
print(type(loaded).__name__, loaded is final_model)
print(np.array_equal(loaded.predict_proba(X_test), final_model.predict_proba(X_test)))
print(loaded.predict_proba(X_test[check["features"]].head(3)).round(3))
Output
Pipeline False
True
[[0.882 0.118]
[0.73 0.27 ]
[0.914 0.086]]

The loaded object is a new pipeline, not the same object, but it predicts exactly the same probabilities. It contains every learned value: the medians, the clip limits, the scaler means, the one-hot categories and the coefficients. The script checks the version before joblib.load, because by the time load returns, the unpickling has already run. In a real project the test set, already used in Example 5, would stay locked until the last model is chosen; here it only checks that the loaded copy predicts the same. Loading works in this script because QuantileClipper is defined here. In a separate prediction script, you would import it from a module, such as churn_features.py (the mini-project does exactly this).

Common mistakes:

  • Saving only the model step (final_model[-1]). The loaded model then receives raw text columns and fails. Save the whole pipeline.
  • Loading a file from an email or a website. A pickle file can run code on your machine. Load only files you trust.
  • Upgrading scikit-learn on the server and keeping the old file. Retrain, or pin the same version in both places.
Mistake Symptom Fix
Fitting a scaler or encoder before the split The test score is too optimistic Split first; put every learned step in a Pipeline
scaler.fit_transform(X_test) The test rows are scaled with their own mean; scores shift Use transform() on test data
Splitting X and y in two calls without the same random_state Rows and labels no longer match; the score is near chance One call: train_test_split(X, y, ...)
No stratify=y on imbalanced classes The test churn rate differs from the real one; scores move between seeds train_test_split(..., stratify=y), StratifiedKFold
Accuracy without a baseline 0.81 accuracy looks good but equals “nobody churns” Compare with DummyClassifier; also report ROC-AUC
set_params(model_C=1) (one underscore) ValueError: Invalid parameter 'model_C' Two underscores: model__C
make_column_selector(dtype_include=object) A deprecation warning in pandas 3 dtype_include="str" (or dtype_exclude="number")
set_output(transform="pandas") after fit() UserWarning: X has feature names, but ... was fitted without feature names Call set_output() before fit()
OneHotEncoder() without handle_unknown="ignore" ValueError: Found unknown categories for a new value in production OneHotEncoder(handle_unknown="ignore")
Validation or computation in a custom __init__ get_params(), clone() or set_params() fail or ignore changes Store arguments unchanged; validate in fit()
fit() that does not return self AttributeError: 'NoneType' object has no attribute 'transform' End fit() with return self
cv=5 (no shuffle) on independent rows sorted by another column, or results you must reproduce and compare Each fold covers one slice of the data; folds differ from the other comparisons Pass one StratifiedKFold(5, shuffle=True, random_state=42) to every call; use TimeSeriesSplit for time-ordered data
Reporting the mean CV score only Two models look different when they are not Report mean ± std on the same folds
FunctionTransformer(lambda x: ...) in a saved pipeline PicklingError at joblib.dump Use a named function defined in a module
Loading a model whose class lived in __main__ AttributeError: Can't get attribute 'X' on <module '__main__'> Define custom classes in an importable module
Loading with another scikit-learn version InconsistentVersionWarning; wrong or failing predictions Pin the version; save it in the metadata; retrain on upgrade
  • Web services: a FastAPI or Flask app loads a joblib pipeline once at start-up and calls predict_proba() for each request. The pipeline accepts the raw request fields, so the web code does no preprocessing. Module 44 builds such a service.
  • Plugin APIs: the estimator API is a design pattern you can copy. Any system with many interchangeable parts (payment providers, file exporters, storage backends) gains from one small shared interface, a get_params()-style config and a factory that clones from config.
  • Automation and CI: a nightly job retrains the pipeline, cross-validates it, compares the score with the last saved metadata and replaces the model file only when the score holds. The same “save the artifact plus its version and metrics” rule applies to any build artifact.
  • Text and log processing: Pipeline and ColumnTransformer also chain text vectorizers and parsers, for example to classify support tickets or log lines in an operations tool (module 41).
  • Every scikit-learn object follows one estimator API: fit() learns and returns self; transformers add transform(); predictors add predict() and score().
  • Hyperparameters go into __init__ and stay unchanged; learned attributes end with _ and exist only after fit(). get_params(), set_params() and clone() work on every estimator.
  • Split once with train_test_split(..., stratify=y, random_state=42) and compare every model with a DummyClassifier or DummyRegressor baseline.
  • A Pipeline chains transformers and a model into one estimator, so fitting happens on training rows only. Route parameters with step__param.
  • A ColumnTransformer sends each column group to its own steps. make_column_selector, get_feature_names_out() and set_output(transform="pandas") keep the columns readable.
  • FunctionTransformer wraps a stateless function. A custom transformer subclasses the mixins and BaseEstimator, stores arguments unchanged, validates in fit() and uses validate_data and check_is_fitted. Test it with parametrize_with_checks (or check_estimator) before you trust it.
  • Cross-validation with StratifiedKFold and cross_validate gives a score with an error bar. Use it on the training set to choose, and use the test set once.
  • joblib.dump and joblib.load save and restore a whole fitted pipeline. Load only trusted files, with the same library version, and keep custom classes in an importable module.

Q1. What do fit(), transform(), predict() and score() return for a transformer and a classifier?

Answer

fit() returns the estimator itself for both. A transformer’s transform() returns the new feature matrix. A classifier’s predict() returns one label per row, and its score(X, y) returns the accuracy. A transformer has no predict(), and a classifier has no transform().

Q2. LogisticRegression(C=0.5) has an attribute C and, after fitting, an attribute coef_. What is the difference between them?

Answer

C is a hyperparameter: you choose it, the constructor stores it unchanged, and get_params() reports it. coef_ is a learned attribute: fit() computes it from the data. The trailing underscore marks it, and it does not exist before fit().

Q3. Why does train_test_split have a stratify argument, and when should you use it?

Answer

A random split can give the test set a different share of each class than the full data, especially with rare classes such as the 19% churners. stratify=y keeps the class shares equal in both parts. Use it for every classification split. Do not use a shuffled split for time-ordered data.

Q4. A pipeline is make_pipeline(SimpleImputer(), StandardScaler(), LogisticRegression()). How do you set the imputer strategy to "median" and C to 0.1 in one call?

Answer

pipe.set_params(simpleimputer__strategy="median", logisticregression__C=0.1). make_pipeline names each step after its class in lowercase, and the double underscore routes each value to its step.

Q5. What does pipe.predict(X_test) do inside a fitted pipeline of an imputer, a scaler and a model?

Answer

It calls imputer.transform(X_test) with the medians learned in fit(), then scaler.transform() on the result with the learned means and standard deviations, then model.predict() on that. No step is refitted, so nothing is learned from the test rows.

Q6. Why is it wrong to scale the whole dataset before cross_val_score, and how does a pipeline fix it?

Answer

The scaler’s mean and standard deviation then include the rows of every validation fold, so each fold is scored on data that influenced the preprocessing. That is leakage, and the score is too optimistic. When you pass a pipeline to cross_val_score, it clones and fits the whole pipeline on each training fold, so the scaler learns from that fold only.

Q7. In a ColumnTransformer, what happens to a column that is in no transformer’s list? How do you keep it?

Answer

It is dropped, because the default is remainder="drop". Pass remainder="passthrough" to keep the unlisted columns unchanged, or give remainder a transformer to apply to them.

Q8. Name the four rules a custom transformer must follow to work with Pipeline, clone() and cross_val_score.

Answer
  1. Inherit from the mixins first and BaseEstimator last.
  2. __init__ stores each keyword argument unchanged under the same name, with no validation or computation.
  3. fit(X, y=None) validates, computes learned attributes ending in _, and returns self.
  4. transform() checks that the estimator is fitted and does not change the learned attributes.

Q9. Five CV folds give ROC-AUC scores 0.84, 0.82, 0.82, 0.79 and 0.81. Another model gets a mean of 0.818 ± 0.015 on the same folds. Is the second model better?

Answer

The first model’s mean is 0.816 and its standard deviation is about 0.016. The difference of 0.002 is far smaller than one standard deviation, so the two models are not clearly different. Prefer the simpler or faster one, or collect more evidence (more folds, repeated CV).

Q10. What is the difference between cross_val_score and cross_validate?

Answer

cross_val_score returns one array of scores for one metric. cross_validate accepts several metrics (a list or a dict in scoring) and returns a dict with test_<metric> arrays, fit_time and score_time, and with return_train_score=True also train_<metric> arrays.

Q11. A colleague sends you model.joblib by email. What three risks should you check before you load and use it?

Answer
  1. Security: loading a joblib or pickle file can run arbitrary code, so load it only if you trust the source (or ask for a skops file).
  2. Version: it must be loaded with the same scikit-learn version that saved it; otherwise you get an InconsistentVersionWarning and possibly wrong predictions.
  3. Imports: any custom class in it must be importable on your machine from the same module path.

Q12. Why did the rebuilt MiniKNNClassifier get score(), get_params() and stratified folds in cross_val_score without any extra code?

Answer

ClassifierMixin provides score() (accuracy) and marks the class as a classifier, so cross_val_score(cv=5) chooses StratifiedKFold. BaseEstimator provides get_params(), set_params() and the repr by reading the __init__ signature. The class followed the conventions, so the base classes could do the rest.

Your progress

0 / 4 done

  • Exercises: 28 exercises on the estimator API, splits, pipelines, column transformers, custom estimators, cross-validation and persistence, with hints and full solutions.
  • Mini-project: build, cross-validate and ship a house price pipeline with a custom transformer, a training script and a prediction script.
  • Cheat sheet: the estimator API, pipeline syntax, column selection, custom estimator template, CV and scoring names on one page.
  • Next module: 35. Regression uses these pipelines to fit and compare linear models, trees and gradient boosting for house prices.