Sub topic 5
Checking that the loaded model matches
This chapter assumes you can fit a scikit-learn estimator, call predict, and save a model with joblib as shown in the earlier chapters. Here you check that a saved model, once loaded, behaves like the original.
Why a round trip needs a check
A save and load is a round trip. The fitted model goes to disk, then comes back as a new Python object. Saving can fail without raising an error. A file may be cut short, loaded in a different environment, or written from the wrong variable. You may also load an old file that sits next to a newer one with a similar name.
A quick comparison catches these problems before the model reaches users. The test is simple: the loaded model must give the same output as the original on the same input.
What to compare
A fitted model keeps its learned state in attributes such as coef_ and classes_. If the round trip worked, that state is the same, so every output built from it is the same too. You can compare outputs instead of attributes, which works for any estimator.
- Compare
predictoutput for class labels or regression values. - Compare
predict_probawhen the model supports it. Probabilities expose small differences that labels can hide. - Use a sample that includes edge cases, not only the first few rows.
The two comparisons need different tools. Labels are integers or strings, so they must match exactly. Probabilities are floating-point numbers, so they should match within a small tolerance.
| Output | Comparison | Why |
|---|---|---|
| `predict` labels | `np.array_equal` | Labels are discrete, so any difference is a real difference. |
| `predict_proba` | `np.allclose` | Floating-point values can differ in the last digits. |
| Regression values | `np.allclose` | Same reason as probabilities. |
A complete round-trip check
The script below trains a pipeline, saves it, loads it, and compares the two. It is self-contained, so you can run it as shown.
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)
dump(model, "iris_model.joblib")
loaded = load("iris_model.joblib")
assert np.array_equal(loaded.predict(X), model.predict(X))
assert np.allclose(loaded.predict_proba(X), model.predict_proba(X))
print("Round trip OK")If both assertions pass, the script prints Round trip OK. If one fails, Python raises an AssertionError and stops. That is the behavior you want in a test or a deployment script.
Where the check runs
The check above runs in the same process that trained the model. That is useful but weak, because the original object is still in memory. The stronger test runs in a fresh process, ideally in the environment where the model will be used.
To test in a fresh process, save reference predictions at training time. Later, load the model elsewhere and compare against them.
import numpy as np
from joblib import load
from sklearn.datasets import load_iris
X, _ = load_iris(return_X_y=True)
reference = np.load("iris_reference.npy")
loaded = load("iris_model.joblib")
assert np.allclose(loaded.predict_proba(X), reference)
print("Matches the saved reference")This script needs iris_reference.npy, which you create at training time with np.save("iris_reference.npy", model.predict_proba(X)).
Common mistakes
- Comparing probabilities with
==. Tiny floating-point differences make the test fail even when the model is fine. Usenp.allclose. - Checking only
predict. Two models can predict the same labels while their probabilities differ. Check both when both exist. - Testing only on training data. The check is about fidelity, not accuracy, so training data is fine. But include rows that exercise different branches, such as extreme values.
- Skipping the fresh-process test. A same-process check cannot reveal a version mismatch, because both objects come from the same libraries.
Exercises
Exercise
A loaded model passes np.array_equal(loaded.predict(X), model.predict(X)) but fails np.array_equal(loaded.predict_proba(X), model.predict_proba(X)) by a difference of about 1e-16. Is the model broken, and what should you change in the test?
Show answer
The model is probably fine. Differences of about 1e-16 are floating-point rounding. Replace np.array_equal with np.allclose for the probabilities, and keep exact comparison for the labels.
Exercise
Why is a round-trip check in the same process that trained the model a weak test? What would you add?
Show answer
The original model is still in memory, and both objects come from the same library versions, so the check cannot reveal a version mismatch or a bad file in the target environment. Save reference predictions at training time, then load the file in a fresh process in the target environment and compare against the reference with np.allclose.