Sub topic 10
Saving and loading a fitted pipeline
This chapter assumes you can build a Pipeline, fit it, and call predict. It covers how to save a fitted pipeline to disk with joblib, load it later, and avoid the common mistakes that break a saved model.
Why save the whole pipeline
Training can take minutes or hours. A service that makes predictions should not retrain every time it starts. You fit once, save the result, and load it wherever you need predictions.
Save the whole pipeline, not only the final classifier. The fitted scaler holds the means and standard deviations learned from the training data. The fitted encoder holds the category list. If you save only the classifier, you must rebuild those steps by hand, and any mismatch silently changes the predictions. A saved pipeline carries every fitted step, so the same transformations run at prediction time.
Saving with joblib
joblib is the library scikit-learn recommends for saving estimators. It stores NumPy arrays efficiently, which suits fitted models. It is installed with scikit-learn.
import joblib
from sklearn.datasets import load_breast_cancer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X, y)
joblib.dump(pipe, "model.joblib")
# Only load files you created or trust, because loading can execute arbitrary code.
loaded = joblib.load("model.joblib")
print(loaded.predict(X[:5]))joblib.dump writes the fitted object to model.joblib. joblib.load reads it back as a pipeline that is already fitted. You do not call fit again. The loaded pipeline gives the same predictions as the original on the same input.
Security: only load trusted files
Loading a joblib file runs code. The format is built on Python's pickle, and unpickling can execute arbitrary instructions embedded in the file. A malicious file can take over your machine as soon as you load it.
What must match when you load
A saved pipeline is not a portable, stable format. It records the structure of the Python objects at save time. Loading works reliably only if the environment is compatible.
- scikit-learn version. Load with the same version that saved the file. Different versions can change internal attributes. scikit-learn warns when versions differ, and results may be wrong or loading may fail.
- Python and NumPy versions. Keep these close to the training environment too.
- Custom code. If the pipeline contains a class you wrote, such as the
Log1pTransformerfrom the previous chapter, Python must be able to import that class by name when loading. Put custom classes in a module that both the training and the serving code import. A class defined only in a notebook or in a script's__main__often cannot be found later. - Input columns. If you fitted on a DataFrame, pass a DataFrame with the same column names at prediction time. A
ColumnTransformerthat selects columns by name fails if a name is missing.
Checking the round trip
Before you rely on a saved model, confirm that loading did not change its behavior. Compare predictions from the original and the loaded pipeline.
import joblib
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X, y)
joblib.dump(pipe, "model.joblib")
loaded = joblib.load("model.joblib")
same = np.array_equal(pipe.predict(X), loaded.predict(X))
print("Predictions identical:", same)
print(loaded.named_steps["standardscaler"].mean_[:3])The last line shows that the fitted scaler's learned means came along with the file. The step name standardscaler is the lowercase class name that make_pipeline generates.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Warning about a version mismatch when loading | Saved and loaded with different scikit-learn versions | Install the training version, or retrain and save again |
| `AttributeError: Can't get attribute 'MyTransformer'` | The custom class is not importable where you load | Move the class to a shared module and import it in both places |
| `NotFittedError` after loading | You saved the pipeline before calling `fit` | Fit first, then call `joblib.dump` |
| `KeyError` for a column name | Prediction input lacks columns used during fitting | Pass data with the same column names |
Exercise
You fitted a pipeline that contains a custom transformer class defined in your training notebook, and saved it with joblib. A colleague loads the file in a separate script and gets an AttributeError about the class. Why does this happen, and how do you fix it?
Show answer
The file stores a reference to the class by name, not the class code. The separate script cannot import a class that only existed in the notebook. Move the class into a normal Python module, import it in the training code, retrain and save the pipeline, and import the same module in the script that loads the file.
Exercise
Why is it better to save the full pipeline than only the fitted classifier, and what is the main risk of loading a joblib file you downloaded from the internet?
Show answer
The full pipeline keeps the fitted scaler, imputer, and encoder, so prediction applies exactly the same transformations as training. Saving only the classifier forces you to recreate those steps by hand, which can silently change predictions. Loading a joblib file can execute arbitrary code, so a file from an untrusted source can compromise your machine.