Skip to content
Back to blog

Unit Test Sklearn Preprocessing Pipelines: Impute, Encode, Vectorize

Prasandeep

Published 9 min readAI
Unit Test Sklearn Preprocessing Pipelines: Impute, Encode, Vectorize

A model card says F1 is fine. Production still breaks: a new category lands in country, SimpleImputer was fit on a different column order, or TF-IDF vocabulary silently shrinks after a "cleanup" PR. The classifier looks innocent. The bug lived in the preprocessing pipeline.

This post shows how to unit-test pipeline-level preprocessing: imputation, categorical encoders, and text vectorization, both as isolated steps and as one fitted ColumnTransformer / Pipeline. You will leave with pytest patterns, fixture shapes, and failure modes that only show up after fit.

This is not an end-to-end model accuracy guide, and it is not a substitute for data-contract checks on the warehouse. Pair it with Metamorphic Testing for ML Models When Ground Truth Is Missing when labels are weak, and with Flaky Test Detection with Machine Learning when CI noise hides real preprocess regressions.

What "pipeline-level" unit testing means

You treat the sklearn (or equivalent) preprocess graph as production code:

LayerWhat you assertSpeed
Step unitOne transformer on a tiny DataFrameMilliseconds
Fitted pipelinefit on train fixture, transform on holdout / adversarial rowsSeconds
Schema contractColumn names, dtypes, output width, sparse vs denseMilliseconds
Golden matrixExact or near-exact numeric output for a frozen fixtureMilliseconds

You are not asserting AUC here. You are asserting: same inputs in, same feature matrix shape and semantics out, including the nasty edges (all-null column, unseen category, empty string, Unicode).

Before you start

  1. Python 3.10+ with scikit-learn>=1.3, pandas, pytest, and preferably scipy for sparse checks.
  2. A single module that builds the preprocess pipeline (factory function), not a notebook cell.
  3. Tiny CSV or in-memory fixtures checked into tests/fixtures/preprocess/ (tens of rows is enough).
  4. Agreement that preprocess changes that alter feature width or mapping are breaking and must update tests deliberately.
clike

src/features/preprocess.py # build_preprocess_pipeline() tests/features/test_impute.py tests/features/test_encode.py tests/features/test_vectorize.py tests/features/test_pipeline.py tests/fixtures/preprocess/train.csv tests/fixtures/preprocess/serve_edge.csv

The running scenario

Fraud / support ticket triage with mixed columns:

  • amount (float, missing allowed)
  • country (categorical string)
  • subject (free text)
python

# src/features/preprocess.py from sklearn.compose import ColumnTransformer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.impute import SimpleImputer from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder def build_preprocess_pipeline() -> ColumnTransformer: numeric = Pipeline( steps=[ ("impute", SimpleImputer(strategy="median")), ] ) categorical = Pipeline( steps=[ ("impute", SimpleImputer(strategy="most_frequent")), ( "onehot", OneHotEncoder( handle_unknown="ignore", sparse_output=True, ), ), ] ) text = TfidfVectorizer( lowercase=True, min_df=1, ngram_range=(1, 2), max_features=5000, ) return ColumnTransformer( transformers=[ ("num", numeric, ["amount"]), ("cat", categorical, ["country"]), ("txt", text, "subject"), ], remainder="drop", verbose_feature_names_out=True, )

Pin handle_unknown, strategy, and max_features in code under test. Tests that only check "it runs" will miss a silent swap to handle_unknown="error".

Test imputation in isolation

Imputers hide nulls. Assert the contract, not the library's math for every strategy.

python

# tests/features/test_impute.py import numpy as np import pandas as pd import pytest from sklearn.impute import SimpleImputer @pytest.fixture def amount_frame() -> pd.DataFrame: return pd.DataFrame({"amount": [10.0, np.nan, 30.0, np.nan]}) def test_median_imputer_fills_nan(amount_frame: pd.DataFrame) -> None: imputer = SimpleImputer(strategy="median") out = imputer.fit_transform(amount_frame[["amount"]]) assert not np.isnan(out).any() # median of [10, 30] == 20 assert out[1, 0] == pytest.approx(20.0) assert out[3, 0] == pytest.approx(20.0) def test_imputer_rejects_all_nan_fit_for_median() -> None: imputer = SimpleImputer(strategy="median") frame = pd.DataFrame({"amount": [np.nan, np.nan]}) with pytest.raises(ValueError): imputer.fit(frame)

How you know it worked: failures name the strategy and the row index. If product later switches to constant fill, this test fails on purpose and you update the expected value in the same PR as the pipeline change.

Categorical impute before encode

Fit order matters. Most-frequent on country must run before OneHotEncoder, or nulls become their own surprise category.

python

def test_country_impute_then_onehot_has_no_nan_category() -> None: from sklearn.pipeline import Pipeline from sklearn.preprocessing import OneHotEncoder pipe = Pipeline( [ ("impute", SimpleImputer(strategy="most_frequent")), ("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False)), ] ) X = pd.DataFrame({"country": ["US", None, "US", "IN"]}) out = pipe.fit_transform(X) assert not np.isnan(out).any() # After impute, None -> US; categories should be IN, US (order depends on sklearn) names = list(pipe.named_steps["onehot"].categories_[0]) assert None not in names and "nan" not in [str(c).lower() for c in names]

Test categorical encoders for train/serve skew

The encoder bug that pages people: handle_unknown="error" in serve, or drop="first" changing width when a rare level appears only in train.

python

# tests/features/test_encode.py import pandas as pd from sklearn.preprocessing import OneHotEncoder def test_unknown_country_does_not_raise() -> None: enc = OneHotEncoder(handle_unknown="ignore", sparse_output=False) enc.fit(pd.DataFrame({"country": ["US", "IN", "DE"]})) serve = pd.DataFrame({"country": ["US", "BR"]}) # BR unseen out = enc.transform(serve) assert out.shape == (2, 3) # Unseen row should be all zeros across country columns assert out[1].sum() == 0 def test_feature_names_are_stable_after_refit_on_same_frame() -> None: enc = OneHotEncoder(handle_unknown="ignore", sparse_output=True) X = pd.DataFrame({"country": ["US", "IN", "DE", "US"]}) enc.fit(X) names_a = list(enc.get_feature_names_out(["country"])) enc.fit(X) names_b = list(enc.get_feature_names_out(["country"])) assert names_a == names_b

Decision table:

SettingUse whenTest focus
handle_unknown="ignore"Online serve sees new levelsUnseen row -> zero vector, no exception
handle_unknown="error"Batch jobs must fail closedUnseen row raises; alert is the feature
drop="first"Linear models, full-rankWidth = n_categories - 1; document it
min_frequency=...Long-tail categoriesRare levels collapse; assert mapping

If you use OrdinalEncoder, assert the integer mapping for a frozen category list. Do not rely on alphabetical order staying forever without pinning categories=.

Test text vectorization contracts

TF-IDF and CountVectorizer fail in quiet ways: empty documents, vocabulary capped by max_features, analyzer changes that invalidate a dumped vocabulary.

python

# tests/features/test_vectorize.py import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer def test_tfidf_empty_string_still_returns_row() -> None: vec = TfidfVectorizer(min_df=1) vec.fit(["refund please", "cancel order", "where is my package"]) X = vec.transform(["", "refund please"]) assert X.shape[0] == 2 assert X.shape[1] == len(vec.vocabulary_) # empty doc -> zero row assert X[0].nnz == 0 def test_max_features_caps_width() -> None: docs = [f"token{i} unique{i}" for i in range(200)] vec = TfidfVectorizer(max_features=50, min_df=1) X = vec.fit_transform(docs) assert X.shape[1] == 50 def test_analyzer_change_breaks_vocabulary_compatibility() -> None: docs = ["Order ID 12345 refund"] word = TfidfVectorizer(analyzer="word").fit(docs) char = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5)).fit(docs) assert set(word.vocabulary_) != set(char.vocabulary_)

Persist vocabulary in CI only when you ship a frozen vectorizer artifact. If the pipeline refits on every training job, assert shape caps and analyzer config instead of exact token ids.

Fit the full ColumnTransformer once, assert edges

This is the pipeline-level test that catches column mis-wiring (subject fed to OneHot, country to TF-IDF).

python

# tests/features/test_pipeline.py from pathlib import Path import pandas as pd import pytest from scipy import sparse from src.features.preprocess import build_preprocess_pipeline FIXTURES = Path(__file__).resolve().parents[1] / "fixtures" / "preprocess" @pytest.fixture(scope="module") def fitted(): train = pd.read_csv(FIXTURES / "train.csv") pipe = build_preprocess_pipeline() pipe.fit(train) return pipe, train def test_transform_width_matches_feature_names(fitted) -> None: pipe, train = fitted X = pipe.transform(train) names = pipe.get_feature_names_out() assert X.shape[0] == len(train) assert X.shape[1] == len(names) def test_output_is_sparse_by_default(fitted) -> None: pipe, train = fitted X = pipe.transform(train) assert sparse.issparse(X) def test_serve_edge_rows_do_not_raise(fitted) -> None: pipe, _ = fitted edge = pd.read_csv(FIXTURES / "serve_edge.csv") # includes null amount, unseen country, empty subject X = pipe.transform(edge) assert X.shape[0] == len(edge) def test_column_order_permutation_on_input_still_works(fitted) -> None: pipe, train = fitted shuffled = train[["subject", "amount", "country"]] a = pipe.transform(train) b = pipe.transform(shuffled) # ColumnTransformer selects by name; matrices must match assert (a != b).nnz == 0

Example serve_edge.csv:

csv

amount,country,subject ,BR, 15.0,US,refund please

How you know it worked: green means fit/transform on edges is stable. Red with ValueError: Found unknown categories means someone flipped handle_unknown. Red with shape mismatch means a transformer or column list changed.

Golden snapshots without lying to yourself

Exact float equality on TF-IDF is brittle across sklearn versions. Prefer:

  1. Shape + feature-name list committed as JSON for the train fixture.
  2. Hash of sorted feature names as a single assert.
  3. Dense exact equality only on the numeric+onehot block after slicing, or on a pipeline that excludes TF-IDF.
python

import json from pathlib import Path def test_feature_names_match_committed_snapshot(fitted) -> None: pipe, _ = fitted actual = list(pipe.get_feature_names_out()) snapshot = Path("tests/fixtures/preprocess/feature_names.json") expected = json.loads(snapshot.read_text(encoding="utf-8")) assert actual == expected

Update the JSON in the same PR that intentionally changes encode/vectorize config. Do not delete the assert.

Wire preprocess tests into CI

Keep them in the default unit job. They are fast enough to gate every PR that touches src/features/.

yaml

# .github/workflows/test.yml (excerpt) - name: Preprocess unit tests run: pytest tests/features -q --maxfail=10

Mark heavier refits with @pytest.mark.slow only if you fit large vocabularies. Most teams never need that for unit fixtures.

Pin scikit-learn in requirements.txt or lockfile. A minor sklearn bump that changes sparse_output defaults will otherwise fail on one machine and pass on another.

Failure modes that burn a day

1. Testing transform without fit on the same code path you ship.
Notebooks call fit_transform on full data. Serve calls transform only. Your tests must use the serve path.

2. Asserting on train only.
Unseen categories and null-heavy serve batches never appear. Keep serve_edge.csv.

3. Column position instead of names.
ColumnTransformer(..., [0, 1]) breaks when CSV column order changes. Prefer column names; assert permutation invariance as above.

4. remainder="passthrough" leaking raw strings into a numeric model.
Assert get_feature_names_out() contains only expected prefixes (num__, cat__, txt__).

5. Dense/sparse surprises.
OneHot sparse + TF-IDF sparse is fine until a custom step calls .toarray() on a wide matrix and OOMs in CI. Assert sparse.issparse where you expect it.

6. Fitting imputer on the whole frame including the label.
Leakage. Build the preprocess factory so label columns cannot be selected; add a test that target is absent from get_feature_names_out().

7. Locale / Unicode normalization.
Straße vs cafe with different analyzers. Freeze lowercase=True and document Unicode handling; add one accented fixture row.

Pipeline unit tests vs data contracts

ConcernPreprocess unit testsData contract (Great Expectations, Pandera, dbt tests)
Null handling inside sklearnYesUpstream null rates
Encoder unknown policyYesAllowed category sets in warehouse
TF-IDF shape capsYesText length distributions
Wrong join exploding rowsNoYes

Do both. Contracts protect inputs. Pipeline unit tests protect the code that maps inputs to model matrix.

Decision checklist

Add pipeline-level preprocess tests when:

  1. You ship a fitted preprocess artifact or refit in training jobs that serve must mirror.
  2. Categorical or text columns can gain levels in production.
  3. More than one engineer edits ColumnTransformer wiring.

Start with this minimal suite:

  1. Imputer fill + all-NaN fit behavior for each numeric strategy you use.
  2. OneHot (or Ordinal) unknown-level behavior matching serve policy.
  3. Vectorizer empty-doc row + max_features cap.
  4. Full build_preprocess_pipeline().fit(train).transform(serve_edge) with shape and feature-name snapshot.

If a change updates the snapshot, the PR description should say why the feature space changed. If it cannot, the change is accidental: fix the pipeline, not the test.

Summarize this post

Opens the chat with a prompt copied — paste to start.

Get the next guide in your inbox

Weekly AI testing insights, templates, and tool notes — unsubscribe anytime.