Sub topic 8
Matching scikit-learn and Python versions
This chapter assumes you can save and load a fitted estimator or Pipeline with pickle and joblib. It also assumes you have used virtual environments and pip. Here you will learn what a saved model file does and does not record about its environment. You will also learn how version mismatches fail, and how to catch them early.
Why a model file is tied to an environment
A file created by joblib.dump or pickle.dump does not hold the model's code. It holds three kinds of information:
- The import path of each class, such as
sklearn.linear_model._logistic.LogisticRegression. - The instance attributes of each object: hyperparameters, learned arrays like
coef_, and any private fields. - The data layout needed to rebuild those objects, such as NumPy array headers and buffers.
On load, Python imports each class by its saved path and then restores the saved attributes onto a new instance. The class definition comes from whatever scikit-learn is installed at load time. If that class differs from the one used at save time, the restored object is a mixture of old data and new code.
The scikit-learn documentation states that a model saved with one version is not guaranteed to load in another. Only the environment that saved the file is certain to read it correctly.
What can differ
Several layers must agree, and any one of them can break a load.
| Layer | What changes between versions | Typical symptom |
|---|---|---|
| scikit-learn | Private module paths, attribute names, internal data structures, default behavior | `ModuleNotFoundError`, `AttributeError` at predict time, a warning, or different predictions |
| NumPy | Internal module names and array pickle format. NumPy 2 moved `numpy.core` to `numpy._core`. | `ModuleNotFoundError: No module named 'numpy._core'` when an older NumPy loads a file saved with NumPy 2 |
| SciPy | Sparse matrix classes and internals | Errors or warnings when a model stores sparse data |
| joblib | Container format for arrays | Rare. Newer joblib reads older files, but the reverse can fail. |
| Python | Pickle protocol and standard-library internals | `ValueError: unsupported pickle protocol` when an older Python reads a newer protocol |
The scikit-learn row matters most, and it is the one you can least inspect by eye. The same estimator class is regularly reorganized. In version 0.22, for example, public-looking modules such as sklearn.linear_model.logistic were made private (sklearn.linear_model._logistic). Pickles saved before that change could no longer be resolved by path.
Failure modes, from loud to silent
Version mismatches fail in three ways. The last is the most dangerous.
- The load fails. An import error or unsupported-protocol error is clear and immediate. You see it the first time you try, so it is the easy case.
- The load succeeds with a warning. Since scikit-learn 1.3, loading an estimator saved by a different scikit-learn version emits
InconsistentVersionWarning. The message names both versions and says the code may break or give invalid results. - The load succeeds with no signal, and predictions are wrong. A missing attribute may surface only for certain inputs or methods. A changed default or internal algorithm can shift results slightly. The warning only covers estimators that carry the saved version, and it can be filtered out or lost in log noise. A service that never checks the output may run for weeks on a subtly broken model.
How does scikit-learn know the saving version? Every estimator that inherits from BaseEstimator adds a _sklearn_version field to its pickled state. The check below shows the field.
import sklearn
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)
state = model.__getstate__()
print(state["_sklearn_version"])
print(sklearn.__version__)The two printed values are equal here because the model was created in this process. For a model loaded from a file, _sklearn_version is the saving version and sklearn.__version__ is the loading version.
Make the warning an error
By default, InconsistentVersionWarning is printed once and execution continues. In a loader that feeds production predictions, you usually want a mismatch to stop the program. Python's warnings module can turn any warning into an exception.
import warnings
from joblib import load
from sklearn.exceptions import InconsistentVersionWarning
def load_strict(path):
"""Load a model, but fail if scikit-learn versions differ."""
with warnings.catch_warnings():
warnings.simplefilter("error", InconsistentVersionWarning)
return load(path)
try:
model = load_strict("iris_model.joblib")
except InconsistentVersionWarning as w:
print(f"Saved with scikit-learn {w.original_sklearn_version}")
print(f"Running scikit-learn {w.current_sklearn_version}")
raise
else:
print("Versions match, model loaded.")This example reuses iris_model.joblib from the earlier chapter on saving a Pipeline. The exception object carries original_sklearn_version and current_sklearn_version, so the error message can tell an operator exactly which version to install.
A Pipeline contains several estimators, and each carries its own version field. The warning can therefore be raised once per step.
Treating a version mismatch
When the warning or error appears, there are three sound responses. Pick one deliberately.
- Recreate the saving environment. Install the exact scikit-learn, NumPy, SciPy, joblib, and Python versions that created the file, load the model there, and use it there. This is the safest choice.
- Retrain in the new environment. If you still have the training code and data, retrain and save a fresh file. This is usually the best long-term fix. It is also what scikit-learn recommends for models you intend to keep.
- Export to a format that does not depend on scikit-learn internals. ONNX, covered in a later chapter, stores the computation rather than Python objects. This is useful when the serving environment cannot match the training one.
Loading in the new version and just checking that predictions look plausible is not a valid fix. Plausible output is exactly what failure mode 3 produces.
Pin versions where you train
Version pinning means writing exact version numbers into a dependency file. Create a pinned list in the training environment and ship it with the model.
python --version
python -m pip freeze | grep -i -E "^(scikit-learn|numpy|scipy|joblib|threadpoolctl)=="Typical output is a short list such as:
joblib==1.4.2
numpy==2.0.2
scikit-learn==1.5.2
scipy==1.13.1
threadpoolctl==3.5.0Copy the lines into a requirements.txt that sits next to the model file. The serving environment then installs exactly those versions with python -m pip install -r requirements.txt. The next chapter shows how to store the same facts as a small JSON file written from Python, so the loading code can read and check them automatically.
Pin the whole stack, not only scikit-learn. A model stored with numpy==2.0.2 can fail to load in an environment with numpy==1.26, even when scikit-learn matches. Pin Python to at least the minor version (for example 3.11). Pickle protocol, standard-library behavior, and available wheels all follow it.
Python version and the pickle protocol
Pickle has numbered protocols. Higher protocols add features such as out-of-band buffers (protocol 5) and are not readable by Python versions that predate them. joblib.dump uses the default protocol of the running Python, and newer Python releases may raise that default. A file written by a newer Python can therefore fail on an older one with unsupported pickle protocol.
You can check the highest protocol your interpreter supports and its default:
import pickle
import sys
print(sys.version.split()[0])
print("highest protocol:", pickle.HIGHEST_PROTOCOL)
print("default protocol:", pickle.DEFAULT_PROTOCOL)If you must serve on an older Python than you train on, one workaround is to pass a lower protocol when you save. With pickle, pass protocol=4 to pickle.dump. This helps only with the Python layer. It does not make the scikit-learn or NumPy layers compatible, so it should be a last resort rather than a compatibility strategy.
A file created on Python 2 cannot be loaded straightforwardly on Python 3, and scikit-learn dropped Python 2 long ago. Treat this as a historical issue and retrain.
Platform and architecture
Version is not the only part of the environment. Operating system and CPU architecture matter less than versions, but they are not irrelevant.
- Model arrays are saved with their dtype, so a 64-bit float array stays 64-bit across platforms. Byte order is recorded in the NumPy array header, so a plain trained estimator usually moves between Windows, Linux, and macOS without trouble.
- Predictions may differ in the last few bits between machines, because linear algebra libraries such as OpenBLAS or MKL use different instruction sets and summation orders. Compare probabilities with
np.allclose, not exact equality, when the machines differ. - Objects that wrap compiled or external resources, such as a model that holds a file handle or a GPU tensor, do not move with the file at all.
The verification chapter's pattern applies here: compare labels exactly and probabilities with a tolerance.
A practical verification pattern
Because failure mode 3 is silent, pair each model file with a small set of reference inputs and the outputs recorded at training time. After loading in a new environment, run the reference inputs and compare.
import numpy as np
from joblib import dump, load
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X, y)
# At training time: save the model and a reference sample.
reference_X = X[::15]
np.savez(
"iris_reference.npz",
X=reference_X,
labels=model.predict(reference_X),
proba=model.predict_proba(reference_X),
)
dump(model, "iris_model.joblib")
# At load time, possibly in another environment:
loaded = load("iris_model.joblib")
ref = np.load("iris_reference.npz")
assert np.array_equal(loaded.predict(ref["X"]), ref["labels"])
assert np.allclose(loaded.predict_proba(ref["X"]), ref["proba"], atol=1e-8)
print("Reference check passed.")The reference file is tiny. It catches a changed prediction, a changed probability, and a missing attribute that only shows up when predict_proba is called. Run it at service start-up, so a bad deployment fails before it takes traffic. It does not replace pinning. It confirms that pinning worked.
Common mistakes
- Upgrading scikit-learn in place and keeping old model files. Package upgrades happen for unrelated reasons, such as a security fix. Keep a pinned lock file, and treat an upgrade as a reason to retrain or re-verify every stored model.
- Ignoring warnings in logs. If a service logs
InconsistentVersionWarningand keeps running, the check is working and nobody is acting on it. Convert it to an error as shown above. - Pinning only scikit-learn. NumPy, SciPy, and joblib are part of the file's meaning too.
- Assuming a minor or patch version is safe. Compatibility is not guaranteed between any two releases, including patch releases. Many pairs do work, but the library makes no promise. Verify instead of assuming.
- Sharing a pickle with a colleague and saying "it works for me". Send the lock file with it, or better, a portable format.
Summary of the working rules
- A model file stores state, not code. The code comes from the environment that loads it.
- Match scikit-learn, NumPy, SciPy, joblib, and the Python minor version between saving and loading.
- Turn
InconsistentVersionWarninginto an exception in the loading code. - Save a requirements list and a small reference-prediction file next to every model.
- When the environments cannot match, retrain or use a portable format, and do not rely on luck.
Exercise
A teammate saved a Pipeline with scikit-learn 1.4 and sends you model.joblib. Your environment has scikit-learn 1.5. You load it and get no error, and predict returns labels that look reasonable. Name two ways to check whether it is safe to use, and say what you should do if the versions differ and you cannot recreate their environment.
Show answer
First, make InconsistentVersionWarning an error with warnings.simplefilter("error", InconsistentVersionWarning) around the load, or read the saved version from the estimator's _sklearn_version state and compare it with sklearn.__version__. Second, compare predictions and predict_proba on reference inputs with outputs recorded in the original environment, using exact equality for labels and np.allclose for probabilities. Seeing plausible labels is not evidence, because a mismatch can fail silently. If the versions differ and you cannot recreate their environment, retrain the Pipeline in your environment if you have the code and data, or ask your teammate for an ONNX export. Do not deploy the unverified file.
Exercise
Your training machine runs Python 3.12 with NumPy 2.0 and your server runs Python 3.9 with NumPy 1.26, with the same scikit-learn version. List two separate ways loading the file could fail, and name the file you should have shipped with the model to find this before deployment.
Show answer
The older Python may not support the pickle protocol that the newer Python used, which gives an unsupported pickle protocol error. NumPy 1.26 cannot import numpy._core, which files saved under NumPy 2 refer to, which gives ModuleNotFoundError: No module named 'numpy._core'. A requirements.txt (or equivalent lock file with the Python version noted) shipped with the model would have shown that the environments differ before deployment.