Sub topic 3
Saving and loading with joblib
This chapter assumes you can fit and predict with a scikit-learn estimator, and that you have seen pickle.dump and pickle.load. Here you will save a fitted model with joblib, load it back, and learn the errors that most often appear.
What joblib is
joblib is a Python library that scikit-learn already depends on, so it is installed with scikit-learn. Its dump and load functions are built on pickle, but they handle large NumPy arrays more efficiently. A fitted model is mostly arrays: coefficients, tree thresholds, cluster centers. For that reason the scikit-learn documentation recommends joblib over plain pickle for models.
Saving a fitted model
The first argument to dump is the object. The second is the file path.
from joblib import dump
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
X, y = load_iris(return_X_y=True)
model = RandomForestClassifier(n_estimators=50, random_state=0)
model.fit(X, y)
dump(model, "forest.joblib")The file name is yours to choose. .joblib is a convention that tells readers which tool wrote the file. Using it also keeps you from confusing joblib files with plain pickle files, which matters later.
dump accepts a str or a pathlib.Path. It overwrites an existing file without asking, so put a version or date in the name if you want to keep older models.
Loading it back
Run the following in a new Python process, with no training code, to confirm that nothing is carried over from the session that saved the model.
from joblib import load
model = load("forest.joblib")
print(model.predict([[5.1, 3.5, 1.4, 0.2], [6.7, 3.0, 5.2, 2.3]]))The restored object is a RandomForestClassifier that is already fitted. You do not call fit again. The file holds the hyperparameters you set and the state learned during training, such as the trees themselves. It does not hold the training data, unless the estimator keeps a copy. Some do. For example, KNeighborsClassifier stores the training points, so its file is large.
What goes wrong
Most problems in practice fall into a few groups.
| Symptom | Likely cause | Fix |
|---|---|---|
| `FileNotFoundError` on load | Relative path, and the process started in a different working directory | Build an absolute path, for example from `Path(__file__).parent` |
| `ModuleNotFoundError` or `AttributeError` on load | The model uses a custom class or function that cannot be imported where you load it | Put that code in an importable module and install it in both places |
| Warning about a different scikit-learn version, or odd results | Saved and loaded with different versions | Match the versions (see the chapter on version compatibility) |
| `UnpicklingError` or a garbled load | The file was written by one tool and read by another | Load with the same library that saved it |
| Unexpected code runs, or a crash, on load | The file is untrusted or damaged | Only load files you trust (see the chapter on security) |
The ModuleNotFoundError case catches many people. Pickle-based formats store a reference to a class or function by name, not its source code. If you define a custom transformer in a notebook and save a model that uses it, the file records something like __main__.MyTransformer. A different script has no such name. Define the class in a module such as mytransformers.py and import it in both the training and the loading code.
Useful options
The dump function returns the list of files it wrote. For a single file this is a list with one name, and you can ignore it.
For a big model, load can memory-map the arrays instead of reading them all into RAM:
from joblib import load
model = load("forest.joblib", mmap_mode="r")With mmap_mode="r", NumPy arrays are read from disk as needed, and several processes can share them. This works only for files saved without compression. Compression is covered in its own chapter.
A repeatable pattern
A small helper keeps paths in one place and makes failures easier to read:
from pathlib import Path
from joblib import dump, load
MODEL_PATH = Path("models") / "forest.joblib"
def save_model(model, path=MODEL_PATH):
path.parent.mkdir(parents=True, exist_ok=True)
dump(model, path)
def load_model(path=MODEL_PATH):
if not path.exists():
raise FileNotFoundError(f"No model file at {path.resolve()}")
return load(path)mkdir(parents=True, exist_ok=True) creates the models folder on the first run and does nothing on later runs. The error message shows the full path, so you can see at once which directory the process was looking in.
Exercise
You save a model with dump(model, "m.joblib") in a notebook that defines a custom transformer class in a cell. A colleague runs load("m.joblib") in a separate script and gets an error that the class cannot be found. Why does this happen, and how do you fix it?
Show answer
Pickle-based files store a reference to the class by name (here under __main__), not the class code. The script does not have that name. Move the transformer into a regular module (for example mytransformers.py), import it in the training code, re-save the model, and make sure the same module is importable where you call load.
Exercise
What does dump store for a fitted LogisticRegression, and what does it not store?
Show answer
It stores the estimator's hyperparameters and the learned state, such as the coefficients and intercept. It does not store the training data, because this estimator does not keep a copy of it.