Sub topic 8
Matching scikit-learn and Python versions
This chapter assumes you can save and load a model with joblib and that you wrote a small metadata file next to it, as in the earlier chapters. It explains why the library versions at load time must match the versions at save time, and how to enforce that.
What a saved file actually contains
A pickle or joblib file does not contain scikit-learn's code. It contains the import path of each class, such as sklearn.linear_model.LogisticRegression, and the instance attributes that fit created, such as coef_, intercept_ and classes_.
When you load the file, Python imports the class from whatever scikit-learn is installed and then fills in the stored attributes. If the installed class expects different attributes, or interprets the same attributes differently, the object can load without complaint and still behave wrongly.
What can differ between environments
| Component | What can go wrong |
|---|---|
| scikit-learn | Attributes are renamed, added or removed, and defaults or algorithms change. A load can fail with an `AttributeError` or `ModuleNotFoundError`, or it can succeed with different predictions. |
| NumPy | Stored arrays and random state objects may not unpickle across major versions. |
| Python | A file written with a newer pickle protocol cannot be read by an older Python. |
| joblib | Rarely a problem, but old files may need a compatible reader. |
scikit-learn only promises that a model loads correctly in the same version that saved it. Across versions, the project gives no guarantee, even between neighboring releases.
The warning you should not ignore
Since scikit-learn 1.3, loading an estimator that was saved with a different version emits an InconsistentVersionWarning. It is a warning, not an error, so a script keeps running and a log line is easy to miss. In a deployment you usually want the mismatch to stop the program.
You can turn the warning into an exception for the duration of the load:
import warnings
from joblib import load
from sklearn.exceptions import InconsistentVersionWarning
with warnings.catch_warnings():
warnings.simplefilter("error", InconsistentVersionWarning)
model = load("iris_model.joblib")
print(type(model).__name__)If the versions differ, load now raises InconsistentVersionWarning as an exception and you never get a half-trusted model object.
Check before you load
The warning appears only after the file has been read. Comparing versions first is cheaper and works for any file format. This code reads the metadata file from the earlier chapter and compares it with the running environment:
import json
import sys
import joblib
import sklearn
with open("iris_model.meta.json") as f:
meta = json.load(f)
current = {
"scikit_learn": sklearn.__version__,
"joblib": joblib.__version__,
"python": sys.version.split()[0],
}
if meta["scikit_learn"] != current["scikit_learn"]:
raise RuntimeError(
f"Model was saved with scikit-learn {meta['scikit_learn']}, "
f"but {current['scikit_learn']} is installed."
)
if meta["python"].split(".")[:2] != current["python"].split(".")[:2]:
print("Warning: Python minor version differs from the one used for saving.")The check is strict for scikit-learn, where any difference matters. It is looser for Python, where only the major and minor numbers decide pickle compatibility in practice.
Fixing a mismatch
You have three options, in order of preference:
- Recreate the environment that saved the model. Install the exact versions from the metadata file, for example
pip install scikit-learn==1.5.2, and load the model there. - Retrain the model in the new environment from the original data and code, then save it again with fresh metadata. This is the dependable fix when the old environment cannot be rebuilt.
- Use an alternative format that does not depend on scikit-learn internals, such as ONNX. The later chapter on alternatives covers this.
Do not try to patch attributes on a loaded object to make a mismatched model work. You cannot tell which attributes changed meaning.
Preventing mismatches
- Pin exact versions in
requirements.txtor a lock file for both the training and serving environments, and install them from the same file. - Save the metadata file with every model, and have the loading code compare it as shown above.
- Upgrade scikit-learn deliberately. After an upgrade, retrain and save new model files instead of reusing old ones.
- Run the round-trip check from the earlier chapter in the serving environment, not only where you trained.
Exercise
A teammate loads your model.joblib in their environment. The load finishes and predict returns values, but they see an InconsistentVersionWarning in the log. Is the model safe to use, and what should they do?
Show answer
No. The warning means scikit-learn's version differs from the one that saved the file, so the stored attributes may not match what the installed classes expect. Predictions can be silently wrong. They should read the version from the metadata file and install it, or retrain and save a new file in their environment. For deployments, they should turn the warning into an error so a mismatch stops the load.
Exercise
Why does the version check in this chapter compare only the major and minor parts of the Python version, but the whole scikit-learn version string?
Show answer
Pickle compatibility depends on the Python minor version (for example 3.11 versus 3.12), and patch releases do not change it. scikit-learn gives no compatibility guarantee between any two releases, including patch releases, so only an exact match is safe.