Sub topic 5
Checking that the loaded model matches
You have saved a fitted model. Before you rely on the file, confirm that the model you load behaves like the one you saved. This chapter shows how to run that check, what to compare, and where the check can mislead you.
This chapter assumes you can fit and use a scikit-learn estimator, call joblib.dump and joblib.load, and read a short NumPy snippet. Familiarity with Pipeline helps, because the examples save a pipeline.
Why a round trip needs a check
Saving and loading rarely fails loudly. The common problems are quieter:
- You saved the classifier but not the scaler, so the loaded model receives unscaled input and returns plausible but wrong labels.
- You loaded the file in an environment with a different library version, and the numbers shifted slightly or not so slightly.
- You saved the model before the final call to
fit, so the file holds an older state. - You overwrote a good file with a bad one and nobody noticed.
None of these raise an exception. A comparison between the original and the loaded model catches most of them in a few lines of code.
A round-trip check has three parts:
- Record what the original model produces for a fixed set of inputs.
- Save the model, then load it back.
- Run the same inputs through the loaded model and compare the outputs.
The basic check
The example below trains a pipeline on part of the iris data, saves it, loads it, and compares predictions on data the model did not train on. It runs as written.
import numpy as np
from joblib import dump, load
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X_train, y_train)
dump(model, "iris_model.joblib")
loaded = load("iris_model.joblib")
assert np.array_equal(loaded.predict(X_test), model.predict(X_test))
assert np.allclose(loaded.predict_proba(X_test), model.predict_proba(X_test))
print("round trip ok")The two assertions use different comparisons on purpose.
predictreturns class labels, which are integers here. Labels are discrete, so they must match exactly. Usenp.array_equal.predict_probareturns floating-point numbers. Usenp.allclose, which accepts differences within a small tolerance.
Exact or approximate comparison
On one machine, with the same library versions, a loaded model usually gives bit-for-bit identical floats. The file stores the fitted arrays exactly, and the same code runs on them. So why not always demand exact equality?
Because the comparison often runs on a different machine than the one that saved the file. Different CPUs, different BLAS libraries (the linear algebra code behind NumPy), and different thread counts can change the order of floating-point additions. The results then differ in the last few digits. Those differences are harmless, but an exact comparison would flag them as failures.
np.allclose(a, b) passes when abs(a - b) <= atol + rtol * abs(b) for every element. The defaults are rtol=1e-05 and atol=1e-08. These suit probabilities well. Tighten them if your outputs are very small or you want a stricter test.
| Output | Typical comparison | Reason |
|---|---|---|
| `predict` for a classifier | `np.array_equal` | Labels are discrete and should not change |
| `predict` for a regressor | `np.allclose` | Floats can differ in the last digits |
| `predict_proba` | `np.allclose` | Floats |
| `decision_function` | `np.allclose` | Floats, and can be large in magnitude |
| `transform` | `np.allclose` | Floats |
Even labels can differ legitimately when two classes have nearly tied scores and the last-digit noise flips the winner. This is rare. If it happens, compare probabilities with a tolerance and look at how close the tie is.
Compare the fitted state directly
Predictions test the behavior, but you can also compare the fitted state, the learned attributes that end in an underscore. This tells you which part differs when a check fails.
scaler_a = model.named_steps["standardscaler"]
scaler_b = loaded.named_steps["standardscaler"]
clf_a = model.named_steps["logisticregression"]
clf_b = loaded.named_steps["logisticregression"]
np.testing.assert_array_equal(scaler_a.mean_, scaler_b.mean_)
np.testing.assert_array_equal(scaler_a.scale_, scaler_b.scale_)
np.testing.assert_array_equal(clf_a.coef_, clf_b.coef_)
np.testing.assert_array_equal(clf_a.intercept_, clf_b.intercept_)
np.testing.assert_array_equal(clf_a.classes_, clf_b.classes_)
assert scaler_a.n_features_in_ == scaler_b.n_features_in_
print("fitted state matches")The np.testing functions are better than a bare assert for this job. When arrays differ, np.testing.assert_array_equal and np.testing.assert_allclose print which elements differ and by how much. They also treat NaN values in the same position as equal, while np.allclose does not unless you pass equal_nan=True.
Do not write assert a == b for arrays. It either raises a "truth value of an array is ambiguous" error or, with a one-element array, passes without comparing what you meant.
The attribute names depend on the estimator. Check its documentation under "Attributes" to find the ones worth comparing. For a tree-based model, comparing every node array is tedious, so compare predictions and perhaps feature_importances_.
Compare the parameters too
Hyperparameters are what you passed before fitting. They should survive the round trip unchanged:
assert loaded.get_params().keys() == model.get_params().keys()
assert clf_b.get_params() == clf_a.get_params()This matters less than predictions, but it is cheap, and it catches the case where you loaded a file saved from a different configuration than you expected.
Check in a fresh Python process
The checks above load the file inside the same process that created the model. That can hide a real problem. Python already knows every class and function the original model used, so loading succeeds even if the file could not be loaded elsewhere.
The classic case is a pipeline containing a function you defined in your script, such as the one passed to FunctionTransformer. Pickle stores a reference to the function by name, not its code. A fresh process that does not define that function fails with an AttributeError or ModuleNotFoundError.
A more honest test loads the file in a separate interpreter and sends the results back through a file. The next example continues from the earlier script, so model and X_test already exist.
import subprocess
import sys
np.save("x_test.npy", X_test)
fresh_code = (
"import numpy as np\n"
"from joblib import load\n"
"m = load('iris_model.joblib')\n"
"x = np.load('x_test.npy')\n"
"np.save('fresh_proba.npy', m.predict_proba(x))\n"
)
subprocess.run([sys.executable, "-c", fresh_code], check=True)
fresh = np.load("fresh_proba.npy")
np.testing.assert_allclose(
fresh, model.predict_proba(X_test), rtol=1e-7, atol=1e-12
)
print("fresh process matches")If your pipeline uses your own functions or classes, put them in a module that both the training script and the serving code import. Then the saved file refers to my_package.features.clip_outliers instead of __main__.clip_outliers, and the fresh process can find it.
Choose the test inputs carefully
A check is only as good as the inputs you feed it.
- Use data the model did not train on. Training rows work, but held-out rows are closer to what production will send.
- Use more than a few rows. Three rows can match by luck. A few hundred rows, or the whole test set, make a mismatch very likely to show.
- Include the awkward cases. If your pipeline imputes missing values or encodes categories, include rows with NaN and rows with rare or unseen categories. Preprocessing steps are where state can go missing.
- Match the input type. If production sends a pandas DataFrame, test with a DataFrame. A model fitted on a DataFrame stores
feature_names_in_, and passing a plain array can trigger warnings or errors.
For the last point, compare the stored feature names when you use DataFrames:
import pandas as pd
df = pd.DataFrame(X_train, columns=["sl", "sw", "pl", "pw"])
named_model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
named_model.fit(df, y_train)
dump(named_model, "named_model.joblib")
named_loaded = load("named_model.joblib")
assert list(named_loaded.feature_names_in_) == list(named_model.feature_names_in_)
np.testing.assert_allclose(
named_loaded.predict_proba(df), named_model.predict_proba(df)
)
print("names and predictions match")Keep reference outputs for later
Everything so far compares a loaded model with the original in memory. That original disappears when your script ends. If you want to check the file again next month, or after a library upgrade, store the reference outputs next to the model:
np.save("iris_reference_x.npy", X_test)
np.save("iris_reference_proba.npy", model.predict_proba(X_test))Later, load the model and the two arrays, run predict_proba on the stored inputs, and compare with np.testing.assert_allclose. This works as a regression test. If it fails after you upgrade scikit-learn, you have learned about the change before your users did. The next chapters cover why versions matter and how to record them.
What a passing check does not prove
A match tells you the loaded model reproduces the saved model. It does not tell you that the model is good, that the file is safe to load, or that it will load in a future environment.
- It does not measure accuracy. Score the loaded model on held-out data separately.
- It does not replace the security caution for untrusted files. Loading is where the risk occurs, and you cannot run a comparison before you load.
- It only covers the inputs you tried. A model can match on your test set and differ on an input you never imagined.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `AttributeError: Can't get attribute ... on <module '__main__'>` | A custom function or class was defined in the script that saved the model | Move it into an importable module and import it in both places |
| Labels match, probabilities differ by about `1e-16` | Exact comparison on floats | Use `np.allclose` or `np.testing.assert_allclose` |
| Loaded model gives different labels on raw data | Scaler or encoder was not saved | Save the whole `Pipeline` |
| `ValueError: The truth value of an array ...` | Used `==` on arrays inside `assert` | Use `np.array_equal` or `np.testing` functions |
| Warning about feature names | Model was fitted on a DataFrame and called with an array, or the reverse | Use the same input type for fit and predict |
| Check passes but results differ in production | Check ran in the same process or on different data | Test in a fresh process with realistic inputs |
Summary
Record the original model's outputs, save, load, and compare. Use exact comparison for labels and np.allclose for floats. Compare fitted attributes when you need to find where a mismatch starts. Run at least one check in a fresh process, test on held-out and awkward inputs, and store reference outputs so you can repeat the check later.
Exercise
A teammate's round-trip check loads the file in the same script that trained the model. It passes, but the service that loads the file fails with "Can't get attribute 'clipoutliers' on <module 'main_'>". Why did the check not catch this, and what two changes fix it?
Show answer
The training script defines clipoutliers in main, so the same process can resolve the name when loading. The saved file only stores a reference to the function by name. The service is a different program with no such function in its main. First, move clipoutliers into an importable module and import it in both the training script and the service. Second, re-save the model so the file refers to the module path, and add a fresh-process check (for example with subprocess) that loads the file and compares predictions.
Exercise
You compare predictproba from a saved model and its reloaded copy on another machine, and np.arrayequal fails although the maximum absolute difference is 3e-16. Which comparison should you use, and what should you still compare exactly?
Show answer
Use np.allclose or np.testing.assertallclose, which accept differences within a tolerance and so tolerate last-digit floating-point noise from different hardware or BLAS libraries. Keep exact comparison (np.arrayequal) for discrete outputs such as classifier labels from predict, and for stored arrays like classes_.