Sub topic 10
Alternatives: skops and ONNX
This chapter assumes you can save and load a model with joblib, and that you know why unpickling untrusted files is dangerous and why a file saved with one scikit-learn version may fail in another. Earlier chapters covered both. Here you will look at two formats that address those problems in different ways: skops, which keeps the scikit-learn workflow but removes arbitrary code execution on load, and ONNX, which moves the model out of Python and scikit-learn entirely.
What problem each format solves
Pickle and joblib files are Python programs in disguise. Loading one can run any code the file's author chose. Both formats also store the internal state of scikit-learn classes, so a different scikit-learn version may read that state incorrectly.
The two alternatives address these problems in different ways:
- skops stores the model in a structured archive instead of a pickle stream. On load, it checks the types in the file against a list you approve. It targets the security problem.
- ONNX (Open Neural Network Exchange) stores the model as a computation graph of operators, such as matrix multiplications and normalizations. A separate runtime executes the graph. It targets the deployment problem: you can serve the model without Python or scikit-learn, and the format does not depend on scikit-learn's class layout.
Neither format is a drop-in replacement for every case. Each has a narrower scope than joblib, and you should know where it stops before you adopt it.
skops
The skops library provides skops.io, a persistence module designed for scikit-learn objects. Install it with:
pip install skopsThe API mirrors joblib's dump and load, with one important difference: load refuses to reconstruct types it does not trust.
Saving, inspecting, and loading
The following example trains a pipeline, saves it, lists the types in the file that are not on skops' default trusted list, and then loads the file.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from skops.io import dump, get_untrusted_types, load
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]))get_untrusted_types reads the file's schema without constructing any objects. It returns the fully qualified names of types that are not on the default trusted list. For a pipeline of ordinary scikit-learn estimators, the list is usually empty or short. Print it and read it.
The trust step is a review, not a formality
The last line of the example passes the discovered list straight into trusted=. That is fine in a tutorial where you made the file yourself. It defeats the purpose when the file came from someone else, because you would be approving whatever the file asks for.
For a file from an outside source, do this instead:
- Call
get_untrusted_typesand read every name in the result. - Decide whether each type belongs in a scikit-learn model. A name such as
sklearn.preprocessing._data.StandardScaleris expected. A name such asos.systemor a module you do not recognize is not. - Pass only the names you accept to
trusted=.
If you call load without trusted and the file contains untrusted types, skops raises an exception that names them. That is the intended behavior.
Limits of skops
- It is scikit-learn specific. skops handles scikit-learn estimators, NumPy arrays, and common Python containers. Arbitrary objects, such as a custom transformer you wrote, appear as untrusted types, and some object kinds cannot be stored at all.
- It does not fix version drift. The file still describes scikit-learn objects. You still need the same scikit-learn version, or one known to be compatible, on the loading side. Record versions as you would for joblib.
- Files can be larger or slower. The archive format is not tuned for very large arrays the way joblib's NumPy handling is. Measure with your own model before you commit to it.
- It is a young project. Check the skops release notes for the version you install, because the trusted-type defaults and supported objects have changed between releases.
ONNX
An ONNX file describes a model as a graph of operators with fixed inputs and outputs. The file contains no Python code, so loading it cannot execute attacker-chosen Python. A runtime such as ONNX Runtime reads the graph and runs it. Runtimes exist for C++, C#, Java, JavaScript, and other languages, so the same file can serve predictions from a non-Python service.
For scikit-learn models, the usual converter is skl2onnx. Install it and the runtime:
pip install skl2onnx onnxruntimeConverting and running a pipeline
The converter needs to know the input types and shape. Passing a sample array lets it infer them. ONNX models normally use 32-bit floats, so convert the data first.
import numpy as np
import onnxruntime as ort
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)
X32 = X.astype(np.float32)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X32, y)
classifier = model[-1]
onnx_model = to_onnx(
model,
X32[:1],
options={id(classifier): {"zipmap": False}},
)
with open("iris_model.onnx", "wb") as f:
f.write(onnx_model.SerializeToString())
session = ort.InferenceSession(
"iris_model.onnx", providers=["CPUExecutionProvider"]
)
input_name = session.get_inputs()[0].name
labels, probabilities = session.run(None, {input_name: X32})
agreement = np.mean(labels == model.predict(X32))
max_diff = np.max(np.abs(probabilities - model.predict_proba(X32)))
print(f"label agreement: {agreement:.3f}")
print(f"max probability difference: {max_diff:.2e}")A few details in this code matter:
zipmap: False. By default, a converted classifier returns probabilities as a list of dictionaries, one per row. Turning ZipMap off returns a plain 2-D array, which is easier to compare and faster to produce.X32[:1]. The sample tells the converter that the input has four float columns and a variable number of rows. The values do not matter.session.run(None, ...). PassingNoneasks for all outputs. For a classifier these are the predicted labels and the class probabilities, in that order.- The comparison at the end. This is the round-trip check from the earlier chapter applied to a new format. Label agreement should be 1.000, and the probability difference should be tiny, on the order of float32 rounding error. Use a tolerance, not exact equality.
Limits of ONNX
- Not every estimator converts.
skl2onnxsupports many common estimators and transformers, but not all of them. Custom transformers need a hand-written converter, and an unsupported step raises an error at conversion time. Check support for every step in your pipeline before you design a deployment around ONNX. - The model becomes inference-only. An ONNX file cannot be refit, tuned, or inspected with
get_params. Keep the original scikit-learn model or its training code if you will retrain. - Numeric differences exist. The runtime computes in float32 by default, so predictions can differ slightly from the 64-bit Python model. Rows near a decision boundary may get a different label. Always compare on a representative dataset and decide whether the differences are acceptable for your use.
- The converter has its own version constraints.
skl2onnxsupports a range of scikit-learn versions and ONNX opsets. Record the versions ofskl2onnx,onnx, andonnxruntimenext to the file, as you record scikit-learn's version for joblib. - Input handling moves to the caller. The graph expects the input types it was built with. If your pipeline accepts strings or mixed-type DataFrame columns, you must declare each input type at conversion time and pass matching arrays at runtime.
Comparing the three formats
| Property | joblib | skops | ONNX |
|---|---|---|---|
| Arbitrary code execution on load | Yes | No, unless you trust a type that does it | No Python code in the file |
| Consumer needs Python and scikit-learn | Yes | Yes | No, only an ONNX runtime |
| Covers any scikit-learn object | Yes, including custom classes | Most scikit-learn objects, with trust review for custom ones | Only estimators with a converter |
| Sensitive to scikit-learn version | Yes | Yes | Only at conversion time |
| Can refit after loading | Yes | Yes | No |
| Typical use | Your own pinned environment | Sharing models between teams or publicly | Production inference, other languages |
Choosing a format
Use these criteria in order.
- Who creates the file, and who loads it? If the same team creates and loads it in an environment you control, joblib with recorded versions is the simplest choice. If the file crosses a trust boundary, prefer skops or ONNX.
- What does the consumer run? If it is Python with scikit-learn, skops keeps your workflow and adds a review step. If it is another language or a lightweight service, ONNX is the practical option.
- Will you retrain from the loaded object? If yes, use joblib or skops. ONNX cannot refit.
- Does every pipeline step convert? If a step has no ONNX converter, you either write one or choose another format.
- Can you verify the result? Whatever you choose, run the same check on every format: load the file and compare predictions with the original on a held-out sample.
The version-recording habit does not go away with a new format. Keep the metadata file from the earlier chapter, and add the versions of skops or of skl2onnx and onnxruntime when you use them.
Exercise
A colleague sends you a .skops file and says it is a scikit-learn pipeline. get_untrusted_types returns ['sklearn.pipeline.Pipeline', 'builtins.eval']. What should you do, and why?
Show answer
Do not load the file with trusted set to that list. builtins.eval runs arbitrary Python code and has no place in a scikit-learn model, so it is a sign that the file is hostile or was built unusually. Pass at most the names you can justify (for example only the scikit-learn classes you expect) and, in this case, ask the sender to explain or regenerate the file, or refuse to load it. The review step exists to catch exactly this.
Exercise
You convert a scikit-learn classifier to ONNX and find that 2 of 10,000 predicted labels differ from the original model, while the probabilities differ by at most 1e-6. Is the conversion broken? What would you check?
Show answer
Probably not. The ONNX runtime computes in float32 while scikit-learn uses float64, so rows whose top two class probabilities are nearly equal can flip labels. Check that the differing rows have near-tied probabilities, then decide whether that level of disagreement is acceptable for your application. If the differences are larger or involve confident predictions, check the input conversion, the converter options, and the versions of skl2onnx and onnxruntime.
Exercise
Your team deploys a model to a Java service and also retrains it every week in Python. Which format do you ship to the Java service, and what do you keep for retraining?
Show answer
Ship an ONNX file to the Java service, since ONNX Runtime has a Java API and the service does not need Python. Keep the training code and a joblib or skops file of the fitted scikit-learn model in the Python environment, because ONNX cannot be refit. Regenerate the ONNX file after each retraining and verify it against the new scikit-learn model before deploying it.