Sub topic 2
Saving with pickle
This chapter assumes you can fit and predict with a scikit-learn estimator and write basic Python that opens files and imports modules. Here you save a fitted model with the standard library's pickle module and load it back.
What pickle does
Pickle is Python's built-in serializer. Serializing means turning an object in memory into a sequence of bytes. You can write those bytes to a file or send them over a network. Unpickling reverses the process and rebuilds the object.
A fitted scikit-learn estimator is an ordinary Python object. Calling fit stores what it learned in attributes whose names end in an underscore. For LogisticRegression these include coef_, intercept_, and classes_. Pickle saves the object's attributes, including these learned ones, so the loaded model can predict without retraining.
Saving and loading a model
The example trains a classifier on the iris data, writes it to model.pkl, and reads it back.
import pickle
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
model = LogisticRegression(max_iter=200).fit(X, y)
with open("model.pkl", "wb") as f:
pickle.dump(model, f)
with open("model.pkl", "rb") as f:
loaded = pickle.load(f)
print(loaded.predict(X[:3]))The script prints [0 0 0], the predicted class for the first three flowers.
Three details matter:
- Open the file in binary mode,
"wb"to write and"rb"to read. Pickle output is bytes, and text mode raises an error. pickle.dump(obj, file)writes to an open file.pickle.load(file)reads one object back.pickle.dumps(obj)andpickle.loads(data)do the same with abytesobject instead of a file. Use them when you store a model in a database or send it in a request.
What the file contains and what it leaves out
Pickle stores an object's data, not its code. The file records the class by name, for example sklearn.linear_model._logistic.LogisticRegression, plus the object's attributes. When you load the file, Python imports that class from the installed library and fills in the saved attributes.
Two consequences follow:
- The loading environment must have the same libraries installed and importable. If the file refers to a class that is missing, loading fails with an
ImportErrororModuleNotFoundError. - If you wrote your own class or function and it is part of the model, it must exist under the same module path when you load. A function defined in a script run as
__main__often cannot be found from a different script. Put custom code in an importable module.
Pickle also cannot serialize every object. Lambda functions and functions defined inside other functions fail with a PicklingError or AttributeError. If you pass a lambda to FunctionTransformer, replace it with a named function defined at module level.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: a bytes-like object is required, not 'str'` | The file was opened in text mode | Use `"wb"` and `"rb"` |
| `ModuleNotFoundError` on load | A library or your own module is not installed in this environment | Install it, or move custom code into an importable module |
| `PicklingError` on save | The model holds a lambda or a local function | Use a named function at module level |
| `EOFError` on load | The file is empty or the write did not finish | Save again and check the file size |
Two warnings before you rely on pickle
Pickle is convenient, but it has two weaknesses that later chapters cover in detail.
For now, load only files that you produced yourself, in an environment with the same library versions.
Exercise
You pickle a fitted model in one script and load it in another script on the same machine. The load fails with "TypeError: a bytes-like object is required, not 'str'" while saving, and later you see ModuleNotFoundError when loading. Name one fix for each error.
Show answer
The TypeError comes from opening the file in text mode, so open it with "wb" for writing and "rb" for reading. The ModuleNotFoundError means the loading environment cannot import a module the model refers to, so install the missing library or move your custom class or function into an importable module that both scripts can import.
Exercise
Why can you not rely on the pickle file alone to recreate your model on a computer that has only Python installed?
Show answer
Pickle stores the object's attributes and the names of its classes, not the code of those classes. The computer also needs scikit-learn, NumPy, and any custom modules installed, ideally in the versions used to save the model.