Sub topic 2
Saving with pickle
This chapter covers the standard-library tool for writing a fitted scikit-learn estimator to disk and reading it back. It assumes you can train and call predict on a scikit-learn estimator, and that you know how to open files and import modules in Python. It also assumes you know what a pipeline is. The later chapters on joblib, security, and version compatibility build on what you learn here.
What pickle does
Pickle is Python's built-in serialization module. Serialization means turning an in-memory object into a sequence of bytes, so you can store it or send it elsewhere. Reading those bytes back and rebuilding the object is called deserialization, or unpickling.
A fitted scikit-learn estimator is an ordinary Python object. Its learned state lives in attributes, and scikit-learn names these with a trailing underscore. Pickle can write those attributes out and rebuild the object later, so you can call predict without calling fit again.
You can see this state on a fitted model:
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)
print(model.coef_.shape)
print(model.classes_)
print(model.n_iter_)The output shows a coefficient matrix of shape (3, 4), the class labels [0 1 2], and the iteration count. These three attributes, plus the constructor parameters such as max_iter, are what pickle has to preserve.
Writing and reading a file
Four functions cover almost every use. Two work on files and two work on bytes in memory.
| Function | Direction | Works with |
|---|---|---|
| `pickle.dump(obj, file)` | object to bytes | an open binary file |
| `pickle.load(file)` | bytes to object | an open binary file |
| `pickle.dumps(obj)` | object to bytes | returns a `bytes` value |
| `pickle.loads(data)` | bytes to object | a `bytes` value |
The following example saves a fitted model and loads 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 file modes matter. Pickle output is binary, so you must open the file with "wb" to write and "rb" to read. Opening with a text mode such as "w" raises a TypeError, because a text-mode file expects str and pickle writes bytes.
The .pkl extension is only a convention. Pickle does not check the file name. Many teams also use .pickle.
Pickling to memory
The dumps and loads functions are useful when the bytes do not belong on disk. Examples are a database column, a message queue, or a cache. They also give you a quick copy test:
import pickle
import numpy as np
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)
payload = pickle.dumps(model, protocol=pickle.HIGHEST_PROTOCOL)
clone = pickle.loads(payload)
print(type(payload), len(payload))
print(np.array_equal(clone.predict(X), model.predict(X)))The second print should show True. The clone is a separate object with the same learned values, so changing one does not change the other.
How the process works
Pickling an object is a walk over its attributes. For each value, pickle either writes the value itself or writes a reference to where the value can be found. This split explains the most common failures, so it is worth understanding.
Pickle stores two kinds of content:
- Data by value. Numbers, strings, lists, dictionaries, and NumPy arrays are written into the file. For a fitted model this is the learned state, such as
coef_,classes_, andintercept_. - Classes and functions by name. Pickle does not store the source code of
LogisticRegression. It stores the module pathsklearn.linear_model._logisticand the class name. When you load the file, Python imports that module and looks the class up.
The second point has three consequences:
- The environment that loads the file must have scikit-learn installed. Without it you get a
ModuleNotFoundError. - The installed class must be compatible with the stored attributes. A different scikit-learn version can break this. A later chapter covers it in detail.
- Pickle never stores your code. If you define your own class or function, the loading side must be able to import it under the same module path and name.
What is and is not in the file
A pickled estimator contains its constructor parameters and fitted attributes. It does not contain the training set unless the estimator keeps it. Some estimators do keep it. KNeighborsClassifier stores the training data in its index, and a SVC stores its support vectors. File sizes therefore vary a lot between model types.
You can check how large a pickle is:
import os
import pickle
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
X, y = load_iris(return_X_y=True)
models = {
"logistic": LogisticRegression(max_iter=200),
"knn": KNeighborsClassifier(),
"forest": RandomForestClassifier(n_estimators=200, random_state=0),
}
for name, est in models.items():
est.fit(X, y)
path = f"{name}.pkl"
with open(path, "wb") as f:
pickle.dump(est, f)
print(name, os.path.getsize(path), "bytes")The random forest file is much larger than the logistic regression file, because it stores 200 trees. If file size matters for your deployment, measure it as shown here rather than guessing.
Protocols
Pickle has numbered protocol versions. Higher protocols are more compact and faster, and they handle large objects such as NumPy arrays better. A file written with a high protocol cannot be read by an older Python that does not support it.
pickle.DEFAULT_PROTOCOLis whatdumpuses when you pass nothing. It depends on your Python version.pickle.HIGHEST_PROTOCOLis the newest protocol your interpreter supports.
For most work the default is fine. If the file will be read by an older Python version, pass an explicit lower number such as protocol=4. Python 3.8 and later can read protocol 4.
Common errors
Most pickle problems fall into a few patterns.
Lambdas and locally defined functions
Pickle stores functions by name, so it can only pickle a function it can find again by importing. A lambda has no importable name, and neither does a function defined inside another function.
import pickle
import numpy as np
from sklearn.preprocessing import FunctionTransformer
bad = FunctionTransformer(lambda X: np.log1p(X))
try:
pickle.dumps(bad)
except (pickle.PicklingError, AttributeError) as exc:
print("failed:", type(exc).__name__)
good = FunctionTransformer(np.log1p)
print(len(pickle.dumps(good)), "bytes for the named version")The lambda version fails. The version that passes np.log1p works, because NumPy functions can be found by import. When you need custom logic, define the function at the top level of a module and import it, rather than writing it inline.
Classes defined in the main script
Suppose you define a custom transformer in train.py, run that script, and pickle a pipeline that uses it. Pickle records the class as __main__.MyTransformer. When a different script, such as serve.py, loads the file, its __main__ has no MyTransformer, and you get an AttributeError. The fix is to put the class in its own module, for example my_transformers.py, and import it in both the training and the serving code. The module must be importable under the same name in both places.
Loading in a different environment
Common symptoms include a ModuleNotFoundError for a scikit-learn submodule, an AttributeError about a missing attribute, or a warning from scikit-learn that the file came from another version. All of these point to a version mismatch. Treat the warning as a real problem and not as noise. Sometimes the model still loads and gives wrong results without any error.
Saving an unfitted estimator
Pickle will happily save an estimator you forgot to fit. The file loads fine, but predict then raises NotFittedError. Check for this by confirming the fitted attributes exist before you save, or by running predict once on a few rows.
Security note
Unpickling is not a passive read. Pickle files can contain instructions that Python runs while loading. A file crafted by an attacker can run arbitrary code on your machine at the moment you call pickle.load.
Pickling your own models and loading them in your own environment is a normal practice. The rule is about where the bytes came from.
Practical habits
A few habits prevent most problems:
- Open files in binary mode and use a
withblock, so the file always closes. - Save the model after the final
fit, not before. - Keep the file next to a note of the scikit-learn and Python versions you used. A later chapter shows how to record this in a small JSON file.
- Test the loaded model against the original before you rely on it. Compare
predictoutput on the same rows, as the chapter on checking round trips explains. - Put any custom classes and functions in an importable module, never in the script you run directly.
When pickle is enough
Pickle is the right tool when the same team controls both sides: you train and save in one environment, and you load in an identical one. Examples are a notebook experiment you want to resume, a cached model in a test suite, and a batch job in a pinned container image.
It is a weaker choice when files cross trust boundaries or environments that you do not control. Later chapters present joblib, which handles large NumPy arrays more efficiently and is the usual choice for scikit-learn, and the skops and ONNX formats, which address the security and portability limits described above.
Exercise
You train a pipeline in train.py. It contains FunctionTransformer(lambda X: X * 2). You pickle it with pickle.dump. What happens, and how would you fix it so the pipeline can be pickled and loaded by another script?
Show answer
The dump call fails, because pickle stores functions by importable name and a lambda has none. The fix is to define a named function, such as def double(X): return X * 2, at the top level of a separate module like my_funcs.py, and import it with from my_funcs import double. Pass FunctionTransformer(double). The loading script must be able to import my_funcs under the same name. If the function were defined in train.py and run as a script, it would be recorded as __main__.double, and the loading script would fail to find it.
Exercise
A colleague sends you a file called model.pkl by email and asks you to run pickle.load on it to check the predictions. What is the risk, and what should you do first?
Show answer
Unpickling can run arbitrary code during the load, so a malicious file could execute commands on your machine with your permissions. Do not load it until you have confirmed where it came from and that you trust the source. If you cannot confirm that, ask for the training code and data and retrain the model yourself, or ask for a format that does not execute code on load, such as skops.