Sub topic 3
Saving and loading with joblib
This chapter assumes you can fit a scikit-learn estimator and call predict. It also assumes you have seen pickle.dump and pickle.load. You do not need to know how pipelines work yet. The next chapter covers them.
What joblib is and how it relates to pickle
joblib is a Python library that scikit-learn already depends on, so it is installed with scikit-learn. It provides dump and load functions that write a Python object to disk and read it back.
joblib is not a separate file format built from scratch. Internally it uses the pickle protocol, the same mechanism you saw in the previous chapter. Its pickler adds special handling for NumPy arrays. A fitted scikit-learn model is mostly NumPy arrays: coefficients, tree node tables, cluster centers, and so on. joblib writes those arrays as raw data instead of pushing them through the generic pickle path. For models that carry large arrays, this usually makes saving and loading faster and the file layout simpler. The scikit-learn documentation recommends joblib for this reason.
Because joblib builds on pickle, it also inherits pickle's problems. A joblib file can run arbitrary code when you load it, and it depends on the library versions that wrote it. Later chapters cover both issues. For now, only load files you created yourself.
| Aspect | `pickle` | `joblib` |
|---|---|---|
| Source | Standard library | Separate package, installed with scikit-learn |
| Large NumPy arrays | Handled generically | Handled efficiently |
| Memory-mapped loading | No | Yes, for uncompressed files |
| Built-in compression | No | Yes, through `compress=` |
| Safe on untrusted files | No | No |
Saving a fitted model
The basic call is dump(value, filename). The first argument is the object to save. The second is the path to write.
from pathlib import 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)
Path("models").mkdir(exist_ok=True)
paths = dump(model, Path("models") / "iris_forest.joblib")
print(paths)Four details are worth knowing here.
dumpaccepts a string or apathlib.Path.- It does not create missing directories, so the example calls
mkdirfirst. Without it you get aFileNotFoundError. - It returns a list of the file names it wrote. With the default settings this list holds one name, so you can usually ignore it.
- It overwrites an existing file without asking. If you want to keep older models, put a date, a version number, or a run identifier in the file name.
The .joblib extension is a convention. joblib does not check it. Using it makes the file's purpose clear to other people and to tools that inspect your directory. The .pkl extension is also common, but it can mislead readers into thinking the file was written by plain pickle.
Loading a model
load(filename) reads the file and returns the object. It reconstructs the estimator with its fitted state, so you can call predict immediately.
from joblib import load
from sklearn.datasets import load_iris
X, y = load_iris(return_X_y=True)
model = load("models/iris_forest.joblib")
print(type(model).__name__)
print(model.predict(X[:5]))
print(model.score(X, y))The loaded object is a new RandomForestClassifier that has the same fitted attributes as the one you saved. Attributes whose names end in an underscore, such as classes_, n_features_in_, and estimators_, were set by fit and are restored. You do not need to call fit again, and calling it would discard the loaded state.
A later chapter shows how to compare a loaded model with the original in a systematic way. The exercise at the end of this chapter gives you a quick version of that check.
What is stored and what is not
It helps to know what a joblib file contains, because it explains most of the surprises people hit.
The file contains:
- The estimator's class, stored as a reference to its module and name, for example
sklearn.ensemble._forest.RandomForestClassifier. - The estimator's hyperparameters, such as
n_estimators=50. - Everything
fitlearned, such as trees, class labels, and feature counts.
The file does not contain:
- The source code of scikit-learn or of any class you wrote.
- The training data. Some estimators keep a copy of it as part of their fitted state, as
KNeighborsClassifierdoes. Most do not. - The Python or library versions that created the file.
The first point matters most. A pickle-based file stores a reference to a class, not the class itself. When you call load, Python imports that module and looks up the class by name. The environment that loads the file must therefore be able to import every class the file refers to.
The diagram above is replaced by the next block, which uses the required format.
Custom code and the `__main__` problem
The most common loading failure after a version mismatch involves classes or functions you defined yourself. Suppose a notebook defines a helper and uses it in a model:
import numpy as np
from joblib import dump
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import FunctionTransformer
from sklearn.pipeline import make_pipeline
def log_features(X):
return np.log1p(X)
model = make_pipeline(
FunctionTransformer(log_features),
LogisticRegression(max_iter=200),
)
X = np.array([[1.0, 2.0], [2.0, 1.0], [8.0, 9.0], [9.0, 8.0]])
y = np.array([0, 0, 1, 1])
model.fit(X, y)
dump(model, "log_model.joblib")This saves without error. The file stores a reference to __main__.log_features, because the function was defined in the script that ran. If you later load the file from a different script, or from a web service, Python looks for log_features in that program's __main__ module. It is not there, and loading fails with an AttributeError.
There are two ways to avoid this:
- Move the helper into a module that you can import, such as
features.py, and import it in both the training and loading programs. The file then storesfeatures.log_features, which resolves anywhere that module is installed. - Use a built-in transformer when one exists. Here,
FunctionTransformer(np.log1p)stores a reference to a NumPy function that is always available.
A lambda cannot be saved at all. Pickling it raises a PicklingError, so use a named function in an importable module instead.
Passing file objects
dump and load also accept open file objects. This is useful when the destination is not a plain path, for example when you write to a temporary file, or to an in-memory buffer that you later upload.
import io
from joblib import dump, load
from sklearn.datasets import load_iris
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True)
model = KNeighborsClassifier(n_neighbors=3).fit(X, y)
buffer = io.BytesIO()
dump(model, buffer)
print(f"{buffer.tell()} bytes written")
buffer.seek(0)
restored = load(buffer)
print(restored.predict(X[:3]))When you pass a file object, open it in binary mode ("wb" or "rb") if it is a real file. For io.BytesIO, rewind with seek(0) before reading, as shown. If you forget, load starts at the end of the buffer and raises an EOFError.
Memory-mapped loading
For large arrays, joblib supports memory mapping. With mmap_mode="r", load does not read the array data into RAM. Instead, the operating system maps the file into memory and pages in data only when the code touches it. Several processes that map the same file share one copy of the data.
You can see the effect with a plain dictionary of arrays:
import numpy as np
from joblib import dump, load
weights = {"w": np.arange(1_000_000, dtype=np.float64)}
dump(weights, "weights.joblib")
mapped = load("weights.joblib", mmap_mode="r")
print(type(mapped["w"]).__name__)
print(mapped["w"][:3])The array comes back as a numpy.memmap object, which is read-only because of the "r" mode. Two limits apply:
- Memory mapping only works for files written without compression. The
compressargument is covered in a later chapter. - Whether it helps a scikit-learn model depends on how that estimator stores its state. Arrays stored directly on the object can be mapped. Data held inside compiled structures, such as the trees of a forest, may still be read into memory. Measure memory use before you rely on it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `FileNotFoundError` on `dump` | The target directory does not exist | Create it with `Path.mkdir` first |
| `FileNotFoundError` on `load` | Relative path resolved against a different working directory | Use an absolute path, or build the path from `__file__` |
| `AttributeError: Can't get attribute ...` on `load` | The file references a class or function that is not importable, often from `__main__` | Move the code into an importable module |
| `PicklingError` on `dump` | The model holds a lambda, a local function, or an open resource | Replace it with a module-level function |
| `EOFError` on `load` from a buffer | The buffer position was not reset | Call `seek(0)` before loading |
| `ModuleNotFoundError` on `load` | A library used by the model is not installed in this environment | Install it, using the version recorded at save time |
| Warnings or odd results after `load` | The file was written by a different scikit-learn version | See the version compatibility chapter |
Practical habits
- Save only after the model is finished. Do not save a model in the middle of a hyperparameter search and forget which parameters it used.
- Write the file, then load it in a separate process and run a prediction. This catches
__main__references and missing modules before deployment. - Keep the training script in version control and name the model file after the run or commit that produced it. A model file is a build artifact, and you should be able to recreate it.
- Treat the file as code, not data. Store it where only trusted people and systems can write to it.
Exercise
You train a model in a notebook that defines a helper function clean(X) and uses it in a FunctionTransformer. You save the model with joblib.dump and the call succeeds. A colleague runs joblib.load in a separate script and gets AttributeError: Can't get attribute 'clean' on <module '__main__'>. Why does this happen, and how do you fix it? Then name one quick check you can run after saving to confirm that a loaded model matches the original.
Show answer
The file stores a reference to the function as __main__.clean, not its source code. In the colleague's script, __main__ has no clean, so the lookup fails. Fix it by moving clean into an importable module such as features.py, importing it in the training script, and making sure the loading environment can import that same module. For the check, load the file and compare loaded.predict(X) with model.predict(X) on the same data, for example with numpy.array_equal. Do it in a fresh Python process so it also catches missing imports.