Sub topic 10
Saving and Loading a Fitted Pipeline
Prerequisites
This chapter assumes you can build and fit a Pipeline or make_pipeline object, and that you know what fit, predict, and transform do. You should also be comfortable running Python scripts from a terminal. Earlier chapters covered ColumnTransformer and custom transformers. Here they matter because they change what you must save and how you load it back.
Why save the whole pipeline
Training usually happens once, and prediction happens many times, often in a different process or on a different machine. Something has to carry the fitted state from the training process to the prediction process.
A fitted pipeline holds more than model coefficients. The scaler has learned a mean and standard deviation per column. The imputer has learned fill values. The one-hot encoder has learned the category list. The classifier has learned its weights. Predictions are only correct if new data passes through the same fitted steps before reaching the model.
If you save only the final classifier, you must rebuild the preprocessing by hand at prediction time. That invites two bugs:
- You refit the scaler on the new data, so the statistics differ from the ones the model was trained with.
- You apply steps in a different order, or forget one.
Saving the pipeline as a single object avoids both. The pipeline is one estimator, so one file holds every fitted step.
Saving and loading with joblib
scikit-learn estimators are ordinary Python objects, so you can persist them with Python's pickle format. The joblib library wraps pickle and handles large NumPy arrays more efficiently, which is why the scikit-learn documentation uses it.
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(obj, path) writes the object to disk. joblib.load(path) reads it back and returns an object of the same class with the same fitted attributes. The loaded pipeline needs no further fit call. You can call predict, predict_proba, or score on it directly.
The file extension is a convention. .joblib is common, and .pkl also works. Neither changes how the data is written.
Verify the round trip
Whenever you add persistence to a project, test that the loaded object behaves like the original. A short check catches most mistakes:
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")
assert np.array_equal(pipe.predict(X), loaded.predict(X))
assert np.allclose(pipe.predict_proba(X), loaded.predict_proba(X))
print("Round trip OK")Both assertions should pass. The loaded object is a reconstruction of the same fitted state, so even floating-point probabilities match.
What is actually stored
Pickling a pipeline stores the pipeline's Python state. That includes:
- The list of steps and their names.
- The constructor parameters of each step, such as
max_iter=1000. - The fitted attributes, which end with an underscore by scikit-learn convention, such as
mean_,scale_,coef_, andcategories_.
It does not store the source code of the classes. The file records the module path and class name, for example sklearn.preprocessing._data.StandardScaler. At load time, Python imports that class from the installed library and fills in the saved state. This design explains most persistence problems you will meet in practice.
Some estimators store training data as part of their fitted state. KNeighborsClassifier keeps the training samples, and a RandomForestClassifier stores every tree. Their files can be large, and they can contain data you did not intend to share.
Safety: loading is code execution
Pickle files can run arbitrary code when loaded. A crafted file can delete files or open a network connection the moment you call joblib.load. The danger is built into the format, and no scikit-learn setting removes it.
Practical rules for teams:
- Load only files produced by your own training jobs.
- Store artifacts in locations with controlled write access, so nobody can swap a file.
- Record a checksum, such as SHA-256, when you save a file, and verify it before loading.
- If you must accept models from others, use a format that does not execute code during loading (see the alternatives section below).
Version compatibility
Pickle is not a long-term archive format. The saved state depends on the internal structure of each class, and that structure can change between scikit-learn releases. The documentation says plainly that loading a model under a different version is not guaranteed to work and can give wrong results.
Newer versions of scikit-learn warn about this. If the version that wrote the file differs from the version that reads it, loading raises InconsistentVersionWarning. Do not silence that warning. It means one of these may happen:
- Loading fails with an
AttributeErroror a similar error. - Loading succeeds but predictions differ from those at training time.
The reliable approach is to pin the same scikit-learn version in the training and serving environments, and to retrain when you upgrade. It also helps to keep the version next to the model. The following example saves a dictionary that holds the pipeline plus the metadata a loader needs.
import warnings
import joblib
import sklearn
from sklearn.datasets import load_breast_cancer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
data = load_breast_cancer()
X, y = data.data, data.target
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)).fit(X, y)
artifact = {
"pipeline": pipe,
"sklearn_version": sklearn.__version__,
"feature_names": list(data.feature_names),
"target_names": list(data.target_names),
}
joblib.dump(artifact, "model_with_meta.joblib")
loaded = joblib.load("model_with_meta.joblib")
if loaded["sklearn_version"] != sklearn.__version__:
warnings.warn(
f"Model trained with scikit-learn {loaded['sklearn_version']}, "
f"running {sklearn.__version__}"
)
model = loaded["pipeline"]
print(loaded["target_names"][model.predict(X[:3])])Storing the expected feature_names gives you a way to validate incoming data at prediction time, which the next section covers.
Input format at prediction time
A pipeline remembers what it saw during fit, but the strictness of its checks depends on the input type.
- If you fit with a pandas DataFrame, the pipeline records
feature_names_in_. At prediction time, scikit-learn compares the column names of the new data to that list and raises an error for missing or reordered names. - If you fit with a NumPy array, there are no names, so scikit-learn can only check the number of columns. Columns in the wrong order give wrong predictions without any error.
- A
ColumnTransformerthat selects columns by name requires those names to exist in the DataFrame at prediction time. Extra columns are dropped by default, and missing ones raise an error.
Because of this, fitting on DataFrames is the safer choice for anything you intend to save. The pipeline then enforces the schema for you. You can inspect the expected columns through loaded.feature_names_in_ on the pipeline or on the first step.
Custom transformers and importable classes
Recall the custom transformer from the previous chapter. When you pickle a pipeline that contains your own class, the file stores only a reference such as transformers.Log1pTransformer. The prediction process must be able to import exactly that path.
This breaks in a common situation. If you define the class inside the training script and run that script directly, the class lives in the module __main__. The file then records __main__.Log1pTransformer. A different script that loads the file has a different __main__, so the import fails with AttributeError: Can't get attribute 'Log1pTransformer' on <module '__main__'>.
The fix is to put custom classes in a regular module that both scripts import. Here is a minimal layout with three files in one directory.
transformers.py:
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
class Log1pTransformer(TransformerMixin, BaseEstimator):
def fit(self, X, y=None):
return self
def transform(self, X):
return np.log1p(X)train.py:
import joblib
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
from transformers import Log1pTransformer
rng = np.random.default_rng(0)
X = rng.uniform(0, 100, size=(200, 3))
y = (X[:, 0] > 50).astype(int)
pipe = make_pipeline(Log1pTransformer(), LogisticRegression(max_iter=1000)).fit(X, y)
joblib.dump(pipe, "log_model.joblib")predict.py:
import joblib
import numpy as np
# transformers.py must be importable here, or loading fails.
model = joblib.load("log_model.joblib")
print(model.predict(np.array([[10.0, 20.0, 30.0], [90.0, 20.0, 30.0]])))Run python train.py and then python predict.py. The second script does not import Log1pTransformer itself, but unpickling imports transformers on its behalf, so the file must be on the Python path.
The same rule applies to functions. A FunctionTransformer built from a lambda cannot be pickled by the standard library, and a named function defined in __main__ has the same import problem as the class above. Use a named function in an importable module.
Also keep in mind that the saved file contains the fitted state, not the code. If you edit Log1pTransformer.transform after saving, the old file will run the new code on load. Treat changes to transformer logic as a reason to retrain.
Compression and file size
By default, joblib writes uncompressed data. For models with large arrays, such as forests, compression can shrink the file at the cost of slower saves and loads.
import os
import joblib
from sklearn.datasets import load_breast_cancer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(
StandardScaler(),
RandomForestClassifier(n_estimators=200, random_state=0),
).fit(X, y)
joblib.dump(pipe, "forest.joblib")
joblib.dump(pipe, "forest_compressed.joblib", compress=3)
for path in ["forest.joblib", "forest_compressed.joblib"]:
print(path, os.path.getsize(path) // 1024, "KiB")The compress argument takes an integer from 0 to 9, and higher values compress more slowly. A value around 3 is a common compromise. Joblib also infers the method from the extension, so a name ending in .gz or .xz selects that algorithm. Compare sizes and load times on your own model before choosing, because the gain depends on how compressible the arrays are.
Uncompressed files have one advantage: joblib.load(path, mmap_mode="r") can memory-map the large arrays instead of reading them into RAM. Several worker processes can then share one copy. Memory-mapping does not work with compressed files.
Alternatives to pickle
| Option | Strength | Limitation |
|---|---|---|
| joblib or pickle | Works for any scikit-learn object, including custom classes | Executes code on load, and is tied to library versions |
| skops.io | Loading checks types and refuses unknown ones unless you approve them | Extra dependency, and not every object type is supported |
| ONNX (via skl2onnx) | Runs without Python or scikit-learn, in many languages | Conversion covers a subset of estimators, and custom transformers need extra work |
skops is a good fit when you share models between teams and want a safer load step. ONNX suits deployments where the serving side is not Python. For models you train and serve yourself, in matching environments, joblib is the simplest choice. Whatever you pick, the version-pinning discipline still applies.
Checklist before shipping a saved pipeline
- Fit on a DataFrame so column names are recorded.
- Put custom classes and functions in an importable module.
- Save the scikit-learn version and the expected feature names next to the model.
- Reload the file in a fresh process and compare predictions with the original.
- Pin the same library versions in the serving environment.
- Restrict who can write to the model location, and verify a checksum before loading.
Exercise
You train a pipeline in a script that defines a custom transformer class at the top of the same file, save it with joblib.dump, and then load it from a second script. The load fails with "Can't get attribute ... on <module '_main_'>". Why does this happen, and what is the fix?
Show answer
Running the training script directly places the class in the module _main, so the pickle records the reference main.ClassName and stores no source code. The second script has its own main_ that does not contain that class, so the import fails. Move the class into a regular module (for example transformers.py), import it in the training script, and make sure that module is importable when loading. Then the pickle records transformers.ClassName, and loading works.
Exercise
A teammate sends you a file named best_model.joblib and suggests you run joblib.load on it to check its accuracy. What is the risk, and name two ways to reduce it?
Show answer
Loading a pickle-based file can execute arbitrary code, so a malicious file could harm your machine as soon as it is loaded. To reduce the risk, only load files from a trusted, access-controlled source and verify a checksum recorded when the file was created. You can also ask for the model in a format that checks types on load, such as skops.io, or open the file in an isolated environment such as a container with no credentials or network access.
Exercise
You saved a pipeline with scikit-learn 1.4 and the serving environment has a newer version. Loading prints InconsistentVersionWarning, but predictions seem fine. Should you ignore the warning?
Show answer
No. The warning means the saved internal state may not match what the newer class expects, so results can be silently wrong even when nothing crashes. Either install the version used for training in the serving environment, or retrain and save the pipeline with the version you will serve with. Storing the training version next to the model makes this mismatch easy to detect.