Skip to content

scikit-learn Pipelines and Feature Preprocessing

A fitted model needs the same feature definitions at prediction time that it used during training. A Pipeline keeps the fitted preprocessing steps beside the estimator, so a prediction uses the stored medians, scales, and category vocabulary.

The Algorithms Overview explains the models. The End-to-End Pipeline compares models on numeric inputs. This guide concentrates on mixed inputs, missing measurements, and categories that arrive after training. It includes a regression task and a classification task on simulated assay batches. These examples demonstrate software behavior, not biological performance.

ColumnTransformer sends named columns through different transformations and joins their outputs. Pipeline applies those transformations before it fits the final estimator. During prediction, it calls the fitted transformations without fitting them again. During cross validation, scikit-learn fits a separate copy of the entire pipeline for each training fold. The composition guide describes these interfaces.

Model Numeric inputs in this guide Categorical inputs in this guide
Linear regression Median imputation and scaling One-hot encoding with a reference category
Logistic regression Mean or median imputation and scaling One-hot encoding with all categories
XGBoost Native missing values, or imputation in the one-hot comparison Native categories and a separate one-hot comparison
LightGBM Native missing values Native categories
CatBoost Native missing values Strings with an explicit missing label

Scaling helps put the penalty in logistic regression on comparable numeric units. Unpenalized ordinary least squares does not require standardized inputs for equivalent predictions, but scaling changes coefficient units and can improve numerical conditioning. Tree splits do not require standardized inputs. A single transformation for all five models would discard useful differences between their input interfaces.

Run the Python blocks in page order in one script or notebook. The setup defines the data, imports, and shared helpers used by every model. Each model section then creates its own pipeline and fits it through validation. The companion runner executes all blocks in that order and captures each printed output.

The companion repository stores the environment in containers/python-base/pyproject.toml and uv.lock. From its root, build and run the same image with these commands. The run uses CPU execution and needs no external dataset or credentials.

Terminal window
podman build -t python-base:pipelines-2026-10-26 containers/python-base
bash guides/machine-learning/scikit-learn-pipelines/run.sh

For a separate local experiment, create a uv project and add the required packages. Use the versions printed below if you need the captured results. The companion lock fixes the full dependency set.

Terminal window
uv init pipeline_example
cd pipeline_example
uv add numpy pandas scikit-learn xgboost lightgbm catboost
# Save the Python blocks below as pipeline_example.py, in page order.
uv run python pipeline_example.py

The simulation creates continuous assay yield and a binary pass outcome from complete measurements. It then removes some measurements, which prevents missing inputs from creating missing targets. Instrument and reagent are nominal categories with no numerical order. The random seeds fix both the generated data and the row split.

import os
from importlib.metadata import version
os.environ["OMP_NUM_THREADS"] = "1"
os.environ["OPENBLAS_NUM_THREADS"] = "1"
import numpy as np
import pandas as pd
from catboost import CatBoostClassifier
from lightgbm import LGBMClassifier
from sklearn.base import BaseEstimator, TransformerMixin, clone
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.metrics import log_loss, roc_auc_score, root_mean_squared_error
from sklearn.model_selection import (
GridSearchCV,
KFold,
StratifiedKFold,
cross_validate,
train_test_split,
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.utils.validation import check_is_fitted
from xgboost import XGBClassifier
numeric_columns = ["temperature", "concentration"]
categorical_columns = ["instrument", "reagent"]
rng = np.random.default_rng(26)
row_count = 720
features = pd.DataFrame({
"temperature": rng.normal(37, 2, row_count),
"concentration": rng.lognormal(1, 0.45, row_count),
"instrument": rng.choice(["A", "B", "C"], row_count),
"reagent": rng.choice(["standard", "enriched"], row_count),
})
instrument_effect = features["instrument"].map({"A": 0, "B": 2, "C": -2})
reagent_effect = (features["reagent"] == "enriched").astype(float)
signal = (
1.8 * (features["temperature"] - 37)
+ 2.5 * (features["concentration"] - 3)
+ instrument_effect + 3 * reagent_effect
)
yield_target = 50 + signal + rng.normal(0, 2, row_count)
log_odds = (
0.35 * signal - 0.8
+ 0.8 * (features["temperature"] > 38) * reagent_effect
)
pass_target = pd.Series(
rng.binomial(1, 1 / (1 + np.exp(-log_odds))), name="passed"
)
for column in features.columns:
missing_rows = rng.choice(row_count, size=36, replace=False)
features.loc[missing_rows, column] = np.nan
train_rows, test_rows = train_test_split(
np.arange(row_count), test_size=0.25, random_state=26,
stratify=pass_target,
)
x_train = features.iloc[train_rows].copy()
x_test = features.iloc[test_rows].copy()
y_train = pass_target.iloc[train_rows]
y_test = pass_target.iloc[test_rows]
yield_train = yield_target.iloc[train_rows]
yield_test = yield_target.iloc[test_rows]
classification_folds = list(StratifiedKFold(
n_splits=4, shuffle=True, random_state=26
).split(x_train, y_train))
new_batches = pd.DataFrame({
"temperature": [37.0, 39.0, np.nan],
"concentration": [3.0, 4.5, 2.0],
"instrument": ["A", "D", np.nan],
"reagent": ["standard", "enriched", "standard"],
})
print(f"Development rows: {len(x_train)}; test rows: {len(x_test)}")
print("Missing inputs:", features.isna().sum().to_dict())
print(f"Development positive fraction: {y_train.mean():.3f}")
for package in (
"numpy", "pandas", "scikit-learn", "xgboost", "lightgbm", "catboost"
):
print(f"{package} {version(package)}")
Development rows: 540; test rows: 180
Missing inputs: {'temperature': 36, 'concentration': 36, 'instrument': 36, 'reagent': 36}
Development positive fraction: 0.485
numpy 2.5.4
pandas 2.3.3
scikit-learn 1.9.1
xgboost 3.4.1
lightgbm 4.7.0
catboost 1.2.10

The two tasks share row indices for convenience, but they have different targets and metrics. The classification search never uses assay yield as an input or as a selection score. The new batches have no target values; they test the prediction interface. Instrument D appears only in those new batches.

A pipeline does not choose a valid split for you. Use patient groups when one patient contributes multiple rows, and preserve time order when future samples must remain unseen. Keep target-derived features out of the raw inputs. The scikit-learn leakage guide explains why preprocessing must learn from training rows only.

Linear regression with separate column transforms

Section titled “Linear regression with separate column transforms”

The numeric branch learns training medians and then scales the imputed values. The categorical branch replaces missing values with a reserved string and learns category indicators. Reserve a label that cannot also be a valid instrument or reagent name.

For ordinary least squares, dropping one indicator per feature avoids exact dependence between the full indicator set and the intercept. For penalized logistic regression, retaining every indicator keeps the penalty treatment symmetric across category indicators. The OneHotEncoder documentation explains the effects of dropping categories.

def make_one_hot_preprocessor(scale_numeric=True, drop=None):
"""Create independent numeric and categorical transformations.
Args:
scale_numeric: Whether to standardize imputed numeric values.
drop: Category dropping policy passed to OneHotEncoder.
Returns:
An unfitted ColumnTransformer for the four input columns.
"""
numeric_steps = [("impute", SimpleImputer(strategy="median"))]
if scale_numeric:
numeric_steps.append(("scale", StandardScaler()))
categorical_steps = [
("impute", SimpleImputer(
strategy="constant", fill_value="__missing__"
)),
("encode", OneHotEncoder(
handle_unknown="ignore", sparse_output=False, drop=drop
)),
]
return ColumnTransformer([
("numeric", Pipeline(numeric_steps), numeric_columns),
("categorical", Pipeline(categorical_steps), categorical_columns),
])
linear_pipeline = Pipeline([
("prepare", make_one_hot_preprocessor(drop="first")),
("model", LinearRegression()),
])
regression_folds = list(KFold(
n_splits=4, shuffle=True, random_state=26
).split(x_train))
linear_cv = cross_validate(
linear_pipeline, x_train, yield_train, cv=regression_folds,
scoring="neg_root_mean_squared_error", return_estimator=True,
error_score="raise",
)
# Verify that each fold learned its own training medians.
for (fit_rows, _), fitted in zip(
regression_folds, linear_cv["estimator"], strict=True
):
imputer = fitted["prepare"].named_transformers_["numeric"]["impute"]
expected = x_train.iloc[fit_rows][numeric_columns].median().to_numpy()
np.testing.assert_allclose(imputer.statistics_, expected)
linear_pipeline.fit(x_train, yield_train)
yield_predictions = linear_pipeline.predict(x_test)
print(f"Mean fold RMSE: {-linear_cv['test_score'].mean():.3f}")
test_rmse = root_mean_squared_error(yield_test, yield_predictions)
known_yield = linear_pipeline.predict(new_batches.iloc[[0]])
print(f"Test RMSE: {test_rmse:.3f}")
print("Known-batch yield:", known_yield.round(3))
print("Fold median checks passed.")
print("Output columns:", linear_pipeline["prepare"].get_feature_names_out())
Mean fold RMSE: 2.160
Test RMSE: 2.355
Known-batch yield: [50.064]
Fold median checks passed.
Output columns: ['numeric__temperature' 'numeric__concentration'
'categorical__instrument_B' 'categorical__instrument_C'
'categorical__instrument___missing__' 'categorical__reagent_enriched'
'categorical__reagent_standard']

The negative score is a scikit-learn convention; reversing its sign gives RMSE in yield units. The mean fold RMSE averages four separate errors rather than pooling all validation residuals. The test score describes the fixed regression pipeline after its final fit on development rows. It does not select the classifier in later sections.

Dense one-hot output keeps this small example easy to inspect. Large category vocabularies can require substantial memory, so consider sparse output with a compatible estimator. With handle_unknown="ignore", an unseen category produces an all-zero indicator block. When drop="first" is also set, that block matches the reference category and scikit-learn can warn about the unknown input. The linear prediction above uses a known category; the classification examples below exercise the unseen category explicitly.

The search compares imputation strategies and regularization strengths inside each fold. The name prepare__numeric__impute__strategy follows the pipeline, transformer, and step names down to the parameter. model__C controls inverse regularization strength; smaller values apply a stronger penalty.

The helper passes raw development rows into GridSearchCV. With refit=True, the search fits the selected pipeline again on all development rows after it finishes validation. This behavior is documented in GridSearchCV. Every classifier below uses the same folds and ROC AUC selection metric.

def search_classifier(name, pipeline, parameters):
"""Select and refit a classifier using development rows only.
Args:
name: Label printed beside the validation result.
pipeline: Unfitted pipeline containing the model and its input steps.
parameters: Parameter grid using pipeline parameter names.
Returns:
A fitted GridSearchCV with its selected pipeline refitted.
"""
search = GridSearchCV(
pipeline, parameters, cv=classification_folds, scoring="roc_auc",
refit=True, n_jobs=1, error_score="raise",
)
search.fit(x_train, y_train)
print(f"{name} mean validation AUC: {search.best_score_:.4f}")
print("Selected parameters:", search.best_params_)
return search
searches = {}
logistic_pipeline = Pipeline([
("prepare", make_one_hot_preprocessor()),
("model", LogisticRegression(max_iter=2000, random_state=26)),
])
searches["logistic"] = search_classifier(
"Logistic regression", logistic_pipeline,
{
"prepare__numeric__impute__strategy": ["mean", "median"],
"model__C": [0.1, 1.0, 10.0],
},
)
Logistic regression mean validation AUC: 0.8475
Selected parameters: {'model__C': 10.0, 'prepare__numeric__impute__strategy': 'median'}

Do not transform the complete development dataset before the search. That would let validation rows influence each fold’s medians and scales, even if the final test rows stayed separate. The stored best validation score also has selection optimism because the search chose its largest value. The reserved test set supplies the final evaluation after model selection. Nested cross validation is another option when the goal is to estimate the performance of the entire selection procedure.

Native categories for XGBoost and LightGBM

Section titled “Native categories for XGBoost and LightGBM”

Both libraries accept pandas categorical columns, but a category code has meaning only with its vocabulary. The transformer below learns that vocabulary during fit and preserves it during transform. An unseen label becomes a missing categorical value, so the estimator follows its missing-value behavior. This is an explicit policy for these examples, not evidence that the model understands a new category.

The transformer leaves numeric missing values intact. Its fitted category state belongs inside the pipeline, so each validation fold learns categories only from that fold’s training rows. It also preserves column names and input order for the estimator.

class FoldCategories(TransformerMixin, BaseEstimator):
"""Learn pandas category vocabularies from one training split.
Attributes:
categories_: Mapping from categorical columns to fitted vocabularies.
feature_names_in_: Input column names in their fitted order.
"""
def __init__(self, columns):
"""Store the categorical column names unchanged for sklearn cloning.
Args:
columns: Tuple of categorical column names.
"""
self.columns = columns
def fit(self, x, y=None):
"""Learn category labels without using target values.
Args:
x: Training DataFrame with numeric and categorical inputs.
y: Optional target, ignored.
Returns:
This fitted transformer.
"""
self.feature_names_in_ = np.asarray(x.columns, dtype=object)
self.categories_ = {
column: sorted(x[column].dropna().unique().tolist())
for column in self.columns
}
return self
def transform(self, x):
"""Apply the fitted vocabulary and map unseen labels to missing.
Args:
x: DataFrame to transform without changing its values in place.
Returns:
A copy with fitted column order and categorical dtypes.
Raises:
NotFittedError: If fit has not run.
KeyError: If a required input column is absent.
"""
check_is_fitted(self, "categories_")
result = x.loc[:, self.feature_names_in_].copy()
for column in self.columns:
result[column] = pd.Categorical(
result[column], categories=self.categories_[column]
)
return result
category_adapter = FoldCategories(tuple(categorical_columns))
probe = clone(category_adapter).fit(x_train)
probe_output = probe.transform(new_batches)
assert pd.isna(probe_output.loc[1, "instrument"])
assert pd.isna(probe_output.loc[2, "instrument"])
assert new_batches.loc[1, "instrument"] == "D"
print("Learned categories:", probe.categories_)
print("Unknown and absent instruments become missing without input mutation.")
Learned categories: {'instrument': ['A', 'B', 'C'], 'reagent': ['enriched', 'standard']}
Unknown and absent instruments become missing without input mutation.

enable_categorical=True enables categorical inputs, and tree_method="hist" supports categorical splits. XGBoost can choose category partitions or internal one-hot splits depending on its parameters. Its Python interface also supports category recoding in recent versions. The fitted adapter makes the unknown-category policy explicit before XGBoost receives the data. See the XGBoost categorical tutorial.

xgb_native_pipeline = Pipeline([
("prepare", clone(category_adapter)),
("model", XGBClassifier(
n_estimators=100, learning_rate=0.05, tree_method="hist",
enable_categorical=True, eval_metric="logloss",
random_state=26, n_jobs=1,
)),
])
searches["xgboost_native"] = search_classifier(
"XGBoost native", xgb_native_pipeline, {"model__max_depth": [2, 4]},
)
XGBoost native mean validation AUC: 0.7973
Selected parameters: {'model__max_depth': 2}

One-hot encoding remains a useful comparison for a small vocabulary or an existing numeric feature interface. This separate pipeline imputes numeric values and encodes categories without scaling. It uses dense output, so zero indicators are explicit zeros rather than absent sparse entries. XGBoost treats absent sparse entries as missing, which requires care when changing representations. The XGBoost FAQ describes that distinction.

xgb_one_hot_pipeline = Pipeline([
("prepare", make_one_hot_preprocessor(scale_numeric=False)),
("model", XGBClassifier(
n_estimators=100, learning_rate=0.05, tree_method="hist",
eval_metric="logloss", random_state=26, n_jobs=1,
)),
])
searches["xgboost_one_hot"] = search_classifier(
"XGBoost one-hot", xgb_one_hot_pipeline, {"model__max_depth": [2, 4]},
)
XGBoost one-hot mean validation AUC: 0.8054
Selected parameters: {'model__max_depth': 2}

The native and one-hot pipelines also differ in numeric imputation. Their scores compare complete input strategies; they do not isolate the causal effect of categorical encoding.

LightGBM recognizes unordered pandas categorical columns through categorical_feature="auto", its default here. It uses categorical splits and handles numeric missing values without an imputer. The same fitted adapter preserves category vocabularies across validation and prediction. The LightGBM categorical documentation describes category codes and missing values.

lightgbm_pipeline = Pipeline([
("prepare", clone(category_adapter)),
("model", LGBMClassifier(
n_estimators=100, learning_rate=0.05, max_depth=-1,
random_state=26, n_jobs=1, verbosity=-1,
deterministic=True, force_col_wise=True,
)),
])
searches["lightgbm_native"] = search_classifier(
"LightGBM native", lightgbm_pipeline, {"model__num_leaves": [7, 15]},
)
LightGBM native mean validation AUC: 0.7858
Selected parameters: {'model__num_leaves': 7}

CatBoost uses its own categorical transformations, including target statistics and internal one-hot treatment for some features. Its documentation advises against external one-hot preprocessing as a default. Pass the categorical column names through cat_features instead. See CatBoost categorical features.

Numeric missing values can remain missing, but categorical values need a consistent string or integer representation. The categorical imputer supplies a reserved string for absent values. The CatBoost FAQ explains why categorical NaN values are not accepted. The ColumnTransformer returns a DataFrame and retains names so cat_features still identifies the correct columns.

CatBoost 1.2.10 copies mutable parameters in get_params, which breaks scikit-learn cloning when cat_features is a list. This example supplies an immutable tuple of names and verifies it through the complete search. The upstream compatibility report records this version-specific problem.

catboost_preprocessor = ColumnTransformer(
[
("numeric", "passthrough", numeric_columns),
("categorical", SimpleImputer(
strategy="constant", fill_value="__missing__"
), categorical_columns),
],
verbose_feature_names_out=False,
).set_output(transform="pandas")
catboost_pipeline = Pipeline([
("prepare", catboost_preprocessor),
("model", CatBoostClassifier(
iterations=100, learning_rate=0.05, loss_function="Logloss",
cat_features=tuple(categorical_columns), random_seed=26,
thread_count=1, verbose=False, allow_writing_files=False,
)),
])
searches["catboost_native"] = search_classifier(
"CatBoost native", catboost_pipeline, {"model__depth": [3, 5]},
)
CatBoost native mean validation AUC: 0.7951
Selected parameters: {'model__depth': 5}

CatBoost receives an unseen string directly; the external preprocessing does not replace it with a known category. The resulting prediction uses CatBoost’s categorical machinery without an estimate learned specifically for that new label. Its internal categorical statistics do not remove the need for an external validation split.

Select once, then evaluate the held-out classifier

Section titled “Select once, then evaluate the held-out classifier”

All five classification pipelines now have fitted estimators selected on development folds. The comparison includes logistic regression, two XGBoost input strategies, LightGBM, and CatBoost. Choose the pipeline with the largest mean validation AUC before any classifier sees test labels. Only that selected classifier receives a held-out score.

The grids are small teaching examples, not equal-budget benchmarks or evidence that one library is generally best. They fix the number of boosting iterations and do not use early stopping. An early-stopping evaluation set also influences model selection, so it must come from development rows and receive the fitted transformations. Passing a raw eval_set through fit parameters does not automatically apply ordinary pipeline preprocessing to it. Never use the reserved test set for early stopping.

validation_scores = pd.Series({
name: search.best_score_ for name, search in searches.items()
}, name="mean_validation_auc").sort_values(ascending=False)
selected_name = validation_scores.index[0]
selected_pipeline = searches[selected_name].best_estimator_
probabilities = selected_pipeline.predict_proba(x_test)[:, 1]
print(validation_scores.round(4).to_string())
print("Selected classifier:", selected_name)
print(f"Test ROC AUC: {roc_auc_score(y_test, probabilities):.4f}")
print(f"Test log loss: {log_loss(y_test, probabilities):.4f}")
print("Test rows evaluated:", len(probabilities))
# Exercise every fitted model on known, unseen, and missing input values.
for name, search in searches.items():
predictions = search.predict_proba(new_batches)[:, 1]
assert np.isfinite(predictions).all()
assert ((predictions >= 0) & (predictions <= 1)).all()
print(name, "new-batch probabilities:", predictions.round(4))
encoded_new = searches["logistic"].best_estimator_["prepare"].transform(
new_batches
)
encoder = searches["logistic"].best_estimator_["prepare"]
encoder = encoder.named_transformers_["categorical"]["encode"]
instrument_width = len(encoder.categories_[0])
start = len(numeric_columns)
assert np.all(encoded_new[1, start:start + instrument_width] == 0)
print("The unseen instrument has an all-zero one-hot block.")
logistic 0.8475
xgboost_one_hot 0.8054
xgboost_native 0.7973
catboost_native 0.7951
lightgbm_native 0.7858
Selected classifier: logistic
Test ROC AUC: 0.8583
Test log loss: 0.4593
Test rows evaluated: 180
logistic new-batch probabilities: [0.3004 0.9689 0.3008]
xgboost_native new-batch probabilities: [0.3452 0.9172 0.3441]
xgboost_one_hot new-batch probabilities: [0.3492 0.8804 0.2402]
lightgbm_native new-batch probabilities: [0.2758 0.959 0.3444]
catboost_native new-batch probabilities: [0.3739 0.8999 0.1723]
The unseen instrument has an all-zero one-hot block.

ROC AUC measures ranking across thresholds; log loss evaluates the assigned probabilities. Neither metric establishes that a decision threshold meets the needs of an assay workflow. Choose thresholds and any probability calibration using development data before final evaluation. Do not change the model after inspecting the test score and then present the same test set as untouched.

The new-batch probabilities show that all five fitted pipelines accept the input contract. They do not measure accuracy for instrument D, because those rows have no observed outcomes. In a deployed system, record unknown categories and missing-value rates so a successful prediction call cannot conceal an input change. Preserve the entire fitted pipeline, its category policy, and its dependency versions when you move from validation to prediction.

Prokhorenkova and colleagues, 2018 describe CatBoost and its unbiased boosting with categorical features.

Ke and colleagues, 2017 describe LightGBM, a fast implementation of gradient boosting decision trees.

Chen and Guestrin, 2016 describe XGBoost, a scalable system for gradient tree boosting.

  • scikit-learn pipelines and composition

    The guide explains sequential transforms, named parameters, and column-specific branches. These interfaces keep learned imputation and category state inside each fitted pipeline.

  • XGBoost categorical data

    The tutorial explains native categories, supported tree methods, and category handling. It provides context for the explicit fitted vocabulary and missing-category policy here.

  • CatBoost categorical features

    The guide describes CatBoost categorical statistics and conditional one-hot treatment. Use it when comparing native categorical strings with the separate encoded pipeline.