Sub topic 10
Alternatives: skops and ONNX
This chapter assumes you can save and load a model with joblib, and that you know why loading a pickle-based file can run arbitrary code and why library versions matter. Here you will see two alternatives, skops and ONNX, and learn when each is worth using.
What problem each format solves
A joblib file is a pickle. Loading it executes whatever instructions the file contains, and it only works reliably with the same scikit-learn version that wrote it. Two tools address these problems in different ways.
- skops is a library from the scikit-learn ecosystem. It stores scikit-learn objects in a format that cannot run arbitrary code on load. It is still Python-only and still tied to scikit-learn versions.
- ONNX (Open Neural Network Exchange) is a language-neutral model format. A converted model runs in a separate runtime such as ONNX Runtime, with no scikit-learn installed. The runtime can be called from Python, C++, C#, Java, and other languages.
Saving with skops
skops writes a zip archive that describes the object's structure instead of embedding executable pickle instructions. On load, it refuses any type it does not trust unless you list that type explicitly.
from skops.io import dump, get_untrusted_types, 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.skops")
unknown_types = get_untrusted_types(file="iris_model.skops")
print(unknown_types)
loaded = load("iris_model.skops", trusted=unknown_types)
print(loaded.predict(X[:3]))For a plain pipeline like this one, unknown_types is usually an empty list, because skops already trusts the standard scikit-learn types. If the list is not empty, read it before you continue.
skops has limits. It does not cover every object that pickle can handle, and custom classes or functions inside a pipeline show up as untrusted types. It also does not remove version coupling, so keep recording versions next to the file as you did earlier.
Exporting to ONNX
ONNX conversion turns a fitted model into a graph of numeric operations. The skl2onnx package does the conversion, and onnxruntime runs the result. Install both with pip install skl2onnx onnxruntime.
import numpy as np
import onnxruntime as rt
from skl2onnx import to_onnx
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)
X = X.astype(np.float32)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X, y)
onx = to_onnx(model, X[:1])
with open("iris_model.onnx", "wb") as f:
f.write(onx.SerializeToString())
session = rt.InferenceSession(
"iris_model.onnx", providers=["CPUExecutionProvider"]
)
input_name = session.get_inputs()[0].name
labels = session.run(None, {input_name: X[:3]})[0]
print(labels)
print(model.predict(X[:3]))The sample row passed to to_onnx tells the converter the input type and shape. The two printed arrays should match. Compare them on more rows with np.array_equal, as you did in the round-trip check.
ONNX has trade-offs that matter in practice:
- Not every estimator or transformer has a converter, and custom code in a pipeline usually does not convert.
- Inputs are typically
float32, so tiny numeric differences from the originalfloat64model are possible. Usenp.allclosefor probabilities. - The file holds the fitted model but not your training code, so you cannot load it back into a scikit-learn object.
Choosing a format
The right choice depends on who loads the file and where.
| Need | Format | Reason |
|---|---|---|
| Your own service, same environment, trusted storage | joblib | Simplest, covers the most objects |
| Sharing with others, or storing where files could be tampered with | skops | Load does not run arbitrary code, and untrusted types are listed first |
| Serving from a non-Python system or a lean runtime | ONNX | No scikit-learn needed at prediction time |
Whichever format you pick, run a round-trip check on predictions after saving. This catches missing converters, dtype problems, and silent changes between environments.
Exercise
A teammate sends you a model file and says it is safe. You want to load it in Python without risking code execution. Which format should the file be in, and what do you do before calling load?
Show answer
The file should be in skops format. Call get_untrusted_types(file=...) and read the list. Pass it to load as trusted only if every type is one you expect. A joblib or pickle file is not safe to load this way, because loading it can execute arbitrary code.
Exercise
You export a scikit-learn pipeline to ONNX, and predict_proba values differ from the original in the seventh decimal place. Is the export broken, and how should the check be written?
Show answer
Probably not. ONNX inputs are usually float32, which causes small numeric differences. Compare labels with np.array_equal and probabilities with np.allclose using a suitable tolerance, instead of requiring exact equality.