Package and test a scikit-learn model pipeline
Version the full preprocessing and model pipeline, pin dependencies, load artifacts safely and prove inference parity with pytest.
By Invicly Tech, , in AI and Machine Learning with Python. About 10 minutes to read.
In short
Packaging turns a trained model into something another machine can load and trust. In scikit-learn that means saving the whole Pipeline, preprocessing included, pinning the library versions, and loading files only from sources you control. A pytest test then proves the packaged model gives the same predictions as the one you evaluated.
Think of it like this: Shipping only the model without its preprocessing is like sending a cake recipe that skips the step where you weigh the flour.
Explained simply
A model in a notebook only works inside that notebook. Packaging is the work that lets the same model run on a server, in a scheduled job or on a colleague's laptop and give the same answers. It has four parts: save everything the model needs, pin the software versions, load files safely and test that nothing changed.
In scikit-learn, the safest unit to save is a Pipeline. A Pipeline chains steps such as filling missing values, turning categories into numbers, scaling and the model itself. When you save the fitted Pipeline, the learned averages, category lists and model weights all travel together.
Saved scikit-learn models are usually pickle or joblib files. These formats are convenient but can run code when they are loaded, so treat them like programs: only load files you built yourself or got from a trusted, checked source. The skops library offers a format you can inspect before loading.
Finally, write a test. Keep a small set of sample inputs and the predictions your evaluated model gave for them. A pytest test reloads the packaged model and checks that it still gives those same predictions. If a library upgrade changes the output, the test fails before your users notice.
Press Play on a diagram to walk through it one step at a time.
- 1Build Pipeline
Imputer, encoder, scaler and model in one object
- 2Fit and evaluate
Record metrics and save sample predictions
- 3Save artifact
skops or joblib file plus pinned requirements
- 4Parity test
pytest reloads it and compares predictions
- 5Docker image
Same Python and libraries everywhere
- Built in or one small package
- Fast and supports almost any object
- Can run code when loaded
- Only for files from trusted sources
- Designed for scikit-learn objects
- Lists unknown types before loading
- You approve types explicitly
- Still needs matching library versions
- Converts the model to a portable graph
- Runs without Python scikit-learn
- Not every transformer converts
- Needs its own parity test after conversion
In depth
Why the whole pipeline must travel together
Training-serving skew happens when the model sees different preprocessing in production than it saw in training. A common cause is fitting a StandardScaler or OneHotEncoder in a separate notebook cell and shipping only the estimator. The production code then rebuilds the preprocessing by hand, slightly differently, and accuracy drops with no error message.
A Pipeline, often with a ColumnTransformer for mixed numeric and categorical columns, solves this. You call fit once on the training data and predict once on raw rows. Set handle_unknown="ignore" on OneHotEncoder so unseen categories in production do not crash the service. Save the fitted Pipeline as one artifact, and record its input column names and types next to it.
- 1Raw input row
Columns exactly as the contract names them
- 2ColumnTransformer
Imputers and encoders fitted on training data
- 3Scaler
Means and standard deviations learned in training
- 4Estimator
The trained model weights
- 5Prediction
Class, probability or number
Pinning dependencies
scikit-learn documents that a model saved with one version may not load, or may behave differently, in another. So pin exact versions of Python, scikit-learn, NumPy, SciPy and pandas. A simple way is a requirements.txt with == versions, generated with pip freeze from a clean virtual environment, or a lock file from a tool such as uv or pip-tools.
Store the Python version too, because wheels differ between versions. MLflow helps: mlflow.sklearn.log_model records a requirements file and a conda or virtualenv spec alongside the model. A Docker image goes one step further and freezes the operating system libraries. Use a slim official Python base image and install from the pinned file.
- Pin with ==, not >=
- Record the Python version
- Rebuild the environment from the lock file in CI
- Upgrade on purpose and rerun the parity test
Loading artifacts safely
Python's pickle module, and joblib which builds on it, can execute arbitrary code during loading. The Python documentation warns never to unpickle data from an untrusted source. In practice, that means model files must come from your own build process or a registry with access control, and you should verify a checksum before loading.
The skops library stores scikit-learn objects in a format that is not plain pickle. Before loading, skops.io.get_untrusted_types lists any types it does not trust by default, and skops.io.load only loads them if you pass them as trusted. This makes a malicious file much harder to slip through. Whatever format you use, never load a model file uploaded by a user or downloaded from an unknown site.
- Treat pickle and joblib files as code
- Check a SHA-256 checksum before loading
- Review untrusted types with skops before loading
- Restrict who can write to the model store
Testing inference parity with pytest
Parity means the packaged model returns the same output as the model you evaluated. When you finish evaluation, save 50 to 200 representative input rows, including edge cases such as missing values and rare categories, plus the predictions. Commit both to the repository.
The test reloads the artifact, predicts on those rows and compares with numpy.testing.assert_allclose. For classes, compare exactly. For probabilities, use a very small tolerance. Add tests for the contract too: a missing required column should raise a clear error, and an unknown category should still produce a prediction. Run these tests in CI and inside the Docker image, so you test what you ship.
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Save the whole pipeline, not just the model~40m
- 2Pin dependencies~40m
- 3Load artifacts only from trusted sources~40m
- 4Test inference parity with pytest~40m
- 5Build a Docker image~40m
Key points
- Save the full Pipeline so the same preprocessing runs at training and prediction time.
- Pin exact versions of Python, scikit-learn, NumPy and pandas; pickled models often break across versions.
- Pickle and joblib files can run arbitrary code when loaded, so load them only from trusted, checked sources.
- An inference parity test compares predictions of the reloaded artifact with saved reference predictions.
- A Docker image freezes the operating system and Python version as well as the libraries.
Key terms
Tap a card to flip it. 0/5 known
Examples
# test_parity.py
import joblib
import numpy as np
import pandas as pd
def test_reloaded_pipeline_matches_reference():
pipe = joblib.load("artifacts/pipeline.joblib") # trusted file we built
X = pd.read_csv("tests/sample_inputs.csv")
expected = np.load("tests/expected_proba.npy")
got = pipe.predict_proba(X)[:, 1]
np.testing.assert_allclose(got, expected, rtol=0, atol=1e-9)Run with: pytest -q
Building and saving a mixed-type pipeline
Your churn data has numeric columns (tenure, monthly_spend) and categorical ones (plan, region). Step 1: build a ColumnTransformer with an imputer and scaler for numbers and a OneHotEncoder for categories. Step 2: chain it with the model in a Pipeline. Step 3: fit on training rows only. Step 4: save the fitted Pipeline with skops and write a SHA-256 checksum next to it.
import hashlib
import skops.io as sio
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
pre = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["tenure", "monthly_spend"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan", "region"]),
])
pipe = Pipeline([("pre", pre), ("clf", LogisticRegression(max_iter=1000))]).fit(X_train, y_train)
sio.dump(pipe, "artifacts/pipeline.skops")
print(hashlib.sha256(open("artifacts/pipeline.skops", "rb").read()).hexdigest())A pinned Docker image that runs the tests
Step 1: generate requirements.txt with exact versions from your clean environment. Step 2: write a Dockerfile on a slim Python base that copies the requirements first, so the install layer is cached. Step 3: copy the code, artifact and tests. Step 4: build and run pytest inside the container. Evidence: the tests pass inside the image, not only on your laptop. Cleanup: docker image rm churn-model:0.1.0.
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY src/ src/
COPY artifacts/ artifacts/
COPY tests/ tests/
RUN useradd --create-home appuser
USER appuser
CMD ["python", "-m", "pytest", "-q"]
# docker build -t churn-model:0.1.0 . && docker run --rm churn-model:0.1.0Quick reference
- Save the fitted Pipeline, not just the estimator
- OneHotEncoder(handle_unknown="ignore") keeps unseen categories from crashing inference
- Pin exact versions with ==, and record the Python version
- Never load pickle or joblib files from untrusted sources; they can run code
- skops.io.get_untrusted_types(file=path) lists types to review before skops.io.load
- Parity test: reload artifact, predict on saved inputs, assert_allclose against saved outputs
- Run the tests inside the Docker image you will deploy
Common mistakes
- Fitting the scaler in a notebook cell and shipping only the model, so production inputs are never scaled.
- Loading a pickle downloaded from the internet, which can run any code on your machine.
- Writing requirements without versions, so next month's install pulls a newer scikit-learn that cannot read the file.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Wrap a StandardScaler and LogisticRegression in a Pipeline, fit it on the iris dataset and save it with joblib.
- Exercise 2medium
Write a pytest test that reloads your pipeline, predicts on 20 saved rows and checks the classes match saved expected classes.
- Exercise 3hard
Switch to skops: save the pipeline, list untrusted types before loading, load only after review, and add a checksum check that fails the test if the file changed.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use pickle or joblib for scikit-learn models?
- Both work and both carry the same security risk. Joblib handles large NumPy arrays more efficiently. For files that cross team boundaries, consider skops, and in every case load only trusted files.
- Can I load a model saved with an older scikit-learn version?
- Sometimes, often with a warning, but it is not guaranteed and results may differ. The safe approach is to pin the version used for training or retrain with the new version and rerun your parity tests.
- Do I need Docker to package a model?
- Not strictly. A pinned virtual environment works for many cases. Docker helps when the model must run the same way on servers, in CI and on other machines, because it also fixes the operating system and Python version.