Sub topic 3
Matching scikit-learn and Python versions
Assume you know basic Python files, imports, and scikit-learn’s fit and predict methods. A saved model is not usually a universal data file. Pickle and joblib store Python objects whose structure depends on Python, scikit-learn, and related library versions.
Load the model in an environment close to the one that saved it. A different version may produce warnings, fail during loading, or produce different results. Keep the training environment definition, such as a requirements file or container image, when the model matters.
Recording versions next to the model
Record the versions used to create the model. Store this information in a separate JSON file beside the model:
import json
import sys
import joblib
import sklearn
metadata = {
"python": sys.version.split()[0],
"scikit_learn": sklearn.__version__,
"joblib": joblib.__version__,
}
with open("iris_model.meta.json", "w") as file:
json.dump(metadata, file, indent=2)
print(metadata)Also record the training data revision, feature order, target meaning, and model filename when those details affect predictions. Metadata helps you recreate an environment, but it does not make incompatible versions compatible.
Alternatives: skops and ONNX
skops is a scikit-learn-oriented format that avoids automatically trusting every Python object during loading. You inspect unknown types and explicitly choose which types to trust. This is safer for sharing models, but it still requires compatible supported objects.
ONNX is an interoperable format designed for running models with an ONNX runtime, sometimes without Python. It can suit production systems written in other languages. Conversion supports only particular estimators and operations, so test preprocessing, outputs, and numeric differences.
| Need | Suitable choice |
|---|---|
| Python-to-Python persistence | joblib |
| Safer scikit-learn sharing | skops |
| Cross-language serving | ONNX |
Loading once and reusing the model
Load a model during application startup, not inside every prediction request. Reusing one loaded object avoids repeated disk access and deserialization.
from joblib import load
model = load("iris_model.joblib")
def predict(features):
return model.predict(features)Exercise
Why should an application record library versions and load the model once?
Show answer
Versions help detect compatibility problems, while loading once avoids repeated disk access and deserialization.