Grid search ONNX models

This example uses OnnxTransformer to freeze a model. Many preprocessing are fitted, converted into ONNX and inserted into a pipeline with OnnxTransformer si that they do not have to be fitted again. The grid search will pick the best one for the task.

Fit all preprocessings and serialize with ONNX

from sklearn.pipeline import make_pipeline
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.exceptions import ConvergenceWarning
from sklearn.utils._testing import ignore_warnings
from skl2onnx.common.data_types import FloatTensorType
from skl2onnx import convert_sklearn
from mlprodict.sklapi import OnnxTransformer

iris = load_iris()
X, y =,
X_train, X_test, y_train, y_test = train_test_split(X, y)

dec_models = [

onx_bytes = []

for model in dec_models:
    onx = convert_sklearn(
        model, initial_types=[('X', FloatTensorType((None, X.shape[1])))])

Pipeline with OnnxTransformer

pipe = make_pipeline(OnnxTransformer(onx_bytes[0]),

Best preprocessing?

We get the best parameters returned by the grid search and we search for it in the list of serialized preprocessing models. And the winner is…

bp = clf.best_params_
best_step = onx_bytes.index(bp["onnxtransformer__onnx_bytes"])



Total running time of the script: ( 0 minutes 0.180 seconds)

Gallery generated by Sphinx-Gallery