Sub topic 2
Save the Whole Pipeline, Not Just the Estimator
Assume you know basic Python, fit, and predict. A scikit-learn Pipeline is a sequence of data-processing steps followed by an estimator. Saving the whole pipeline preserves the transformations learned during training, such as the mean and standard deviation used by a scaler.
Save the Pipeline
If you save only the classifier, prediction code must recreate preprocessing exactly. That is easy to get wrong. Save the fitted pipeline instead.
import numpy as np
from joblib import dump, load
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
model = make_pipeline(
StandardScaler(),
LogisticRegression(max_iter=200),
)
model.fit(X, y)
dump(model, "iris_model.joblib")
dump(model, "iris_model_compressed.joblib", compress=3)
loaded = load("iris_model.joblib")
assert np.array_equal(model.predict(X), loaded.predict(X))
assert np.allclose(
model.predict_proba(X),
loaded.predict_proba(X),
)
print(loaded.predict(X[:3]))The fitted scaler and classifier are both stored in iris_model.joblib. Compression level 3 creates a smaller file, usually with slower saving and loading. Choose compression when storage or transfer size matters more than that extra time.
Check the Round Trip
A round trip means saving a fitted object, loading it, and checking its behavior. Compare predictions on a fixed test set. For probabilistic models, compare probabilities with a numerical tolerance because small floating-point differences can occur.
Keep the loaded model in memory for repeated predictions. Loading the file for every request adds unnecessary disk and deserialization work.
Only Load Files You Trust
joblib uses pickle-based serialization. Loading a malicious or modified pickle file can execute arbitrary Python code. Never load model files from an untrusted download, user upload, or unknown storage location.
For safer sharing, consider skops, which lets you inspect types before trusting them. ONNX can be appropriate when a model must run outside Python, but it supports fewer scikit-learn features.
Exercise
Why should a fitted scaler be saved with the classifier?
Show answer
The scaler contains training-specific values. Saving it in the pipeline ensures new data receives the same transformation before prediction.