Persist a scikit-learn model with its preprocessing pipeline
A saved classifier is incomplete when its inputs depend on fitted preprocessing that was left behind. Save the scaler and classifier as one pipeline, preserve their feature contract, and reload them in a matching runtime. This keeps serving predictions on the same transformation path used during training.
Prepare a small trusted artifact
Use Python 3.14 with scikit-learn 1.9.1 and its NumPy and joblib dependencies. Create an isolated environment for the example and install scikit-learn==1.9.1. The demonstration trains on the bundled Iris dataset, so it does not download data.
Joblib uses Python's pickle-based persistence. Loading an untrusted artifact can execute code. Only load files from a source you trust, and verify the expected artifact identity before loading. A checksum supplied by the same untrusted sender does not establish trust. Joblib load documentation .
Save the full fitted pipeline
Run this complete script. It creates a temporary directory, writes the artifact and a small manifest, reloads the artifact, and removes only that temporary directory when finished.
import hashlib
import importlib.metadata
import json
import platform
import tempfile
from pathlib import Path
import joblib
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
data = load_iris()
x_train, x_test, y_train, y_test = train_test_split(
data.data, data.target, stratify=data.target, random_state=17
)
pipeline = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
pipeline.fit(x_train, y_train)
expected = pipeline.predict_proba(x_test)
with tempfile.TemporaryDirectory() as folder:
artifact = Path(folder) / "iris.joblib"
joblib.dump(pipeline, artifact)
manifest = {
"python": platform.python_version(),
"packages": {
name: importlib.metadata.version(name)
for name in ("scikit-learn", "numpy", "scipy", "joblib")
},
"features": data.feature_names,
"sha256": hashlib.sha256(artifact.read_bytes()).hexdigest(),
}
(Path(folder) / "manifest.json").write_text(
json.dumps(manifest, indent=2), encoding="utf-8"
)
# This artifact was just created by this process.
restored = joblib.load(artifact)
np.testing.assert_allclose(restored.predict_proba(x_test), expected)
print("Reloaded predictions match")
The expected output is Reloaded predictions match. The pipeline fits the scaler on the training split and applies that fitted transformation before both original and restored predictions. The held-out split remains outside fitting.
Pipeline reference
.
Define the serving input contract
The feature list in the manifest records the required order. A row must contain the same measurements, units and meanings used during training. Four numbers with reordered columns can pass basic shape checks while producing incorrect predictions. Validate incoming fields and map them to the recorded order before calling predict.
Keep a small known-input regression fixture beside a real release. Compare both predicted classes and probability vectors after deploying the artifact. A successful deserialization only proves that objects loaded. It does not prove that a data adapter still supplies the right features. Avoid calling fit or fit_transform during ordinary prediction requests.
Preprocessing pitfalls
.
Reproduce the environment
The manifest is an audit aid, not a complete environment lock. Retain the training code, dependency lock, dataset version and validation results with the artifact. Scikit-learn does not support loading a model across arbitrary library versions. Rebuild or retrain under a new environment and rerun evaluation rather than treating a version warning as harmless. Persistence guidance .
For a long-lived service, promote a versioned artifact only after its checks pass and let the process load an immutable version. Avoid replacing a file while another process is reading it. Other formats such as ONNX or skops may suit different deployment and trust requirements, but require their own compatibility review.
The complete temporary-file round trip was executed locally with scikit-learn 1.9.1. It demonstrates preservation of predictions, not a production accuracy target.
Question provenance
This article addresses Save classifier to disk in scikit-learn , asked by garak on Stack Overflow. The source question is licensed under CC BY-SA 3.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.
Author: Herman Schoenfeld