.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_plot_train_convert_predict.py: .. _l-logreg-example: Train, convert and predict with ONNX Runtime ============================================ This example demonstrates an end to end scenario starting with the training of a machine learned model to its use in its converted from. .. contents:: :local: Train a logistic regression +++++++++++++++++++++++++++ The first step consists in retrieving the iris datset. .. code-block:: python from sklearn.datasets import load_iris iris = load_iris() X, y = iris.data, iris.target from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y) Then we fit a model. .. code-block:: python from sklearn.linear_model import LogisticRegression clr = LogisticRegression() clr.fit(X_train, y_train) We compute the prediction on the test set and we show the confusion matrix. .. code-block:: python from sklearn.metrics import confusion_matrix pred = clr.predict(X_test) print(confusion_matrix(y_test, pred)) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [[11 0 0] [ 0 12 4] [ 0 0 11]] Conversion to ONNX format +++++++++++++++++++++++++ We use module `sklearn-onnx `_ to convert the model into ONNX format. .. code-block:: python from skl2onnx import convert_sklearn from skl2onnx.common.data_types import FloatTensorType initial_type = [('float_input', FloatTensorType([None, 4]))] onx = convert_sklearn(clr, initial_types=initial_type) with open("logreg_iris.onnx", "wb") as f: f.write(onx.SerializeToString()) We load the model with ONNX Runtime and look at its input and output. .. code-block:: python import onnxruntime as rt sess = rt.InferenceSession("logreg_iris.onnx") print("input name='{}' and shape={}".format( sess.get_inputs()[0].name, sess.get_inputs()[0].shape)) print("output name='{}' and shape={}".format( sess.get_outputs()[0].name, sess.get_outputs()[0].shape)) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none input name='float_input' and shape=[None, 4] output name='output_label' and shape=[1] We compute the predictions. .. code-block:: python input_name = sess.get_inputs()[0].name label_name = sess.get_outputs()[0].name import numpy pred_onx = sess.run([label_name], {input_name: X_test.astype(numpy.float32)})[0] print(confusion_matrix(pred, pred_onx)) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [[11 0 0] [ 0 12 0] [ 0 0 15]] The prediction are perfectly identical. Probabilities +++++++++++++ Probabilities are needed to compute other relevant metrics such as the ROC Curve. Let's see how to get them first with scikit-learn. .. code-block:: python prob_sklearn = clr.predict_proba(X_test) print(prob_sklearn[:3]) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [[1.04597336e-03 3.26972202e-01 6.71981824e-01] [8.07529571e-01 1.92267362e-01 2.03067523e-04] [3.75046145e-02 6.77776609e-01 2.84718777e-01]] And then with ONNX Runtime. The probabilies appear to be .. code-block:: python prob_name = sess.get_outputs()[1].name prob_rt = sess.run([prob_name], {input_name: X_test.astype(numpy.float32)})[0] import pprint pprint.pprint(prob_rt[0:3]) .. rst-class:: sphx-glr-script-out Out: .. code-block:: none [{0: 0.0010459469631314278, 1: 0.32697227597236633, 2: 0.6719817519187927}, {0: 0.807529628276825, 1: 0.19226738810539246, 2: 0.00020308367675170302}, {0: 0.037504520267248154, 1: 0.6777766942977905, 2: 0.2847188115119934}] Let's benchmark. .. code-block:: python from timeit import Timer def speed(inst, number=10, repeat=20): timer = Timer(inst, globals=globals()) raw = numpy.array(timer.repeat(repeat, number=number)) ave = raw.sum() / len(raw) / number mi, ma = raw.min() / number, raw.max() / number print("Average %1.3g min=%1.3g max=%1.3g" % (ave, mi, ma)) return ave print("Execution time for clr.predict") speed("clr.predict(X_test)") print("Execution time for ONNX Runtime") speed("sess.run([label_name], {input_name: X_test.astype(numpy.float32)})[0]") .. rst-class:: sphx-glr-script-out Out: .. code-block:: none Execution time for clr.predict Average 2.35e-05 min=1.95e-05 max=4.43e-05 Execution time for ONNX Runtime Average 2.9e-05 min=2.69e-05 max=4.27e-05 Let's benchmark a scenario similar to what a webservice experiences: the model has to do one prediction at a time as opposed to a batch of prediction. .. code-block:: python def loop(X_test, fct, n=None): nrow = X_test.shape[0] if n is None: n = nrow for i in range(0, n): im = i % nrow fct(X_test[im: im+1]) print("Execution time for clr.predict") speed("loop(X_test, clr.predict, 100)") def sess_predict(x): return sess.run([label_name], {input_name: x.astype(numpy.float32)})[0] print("Execution time for sess_predict") speed("loop(X_test, sess_predict, 100)") .. rst-class:: sphx-glr-script-out Out: .. code-block:: none Execution time for clr.predict Average 0.00202 min=0.00181 max=0.00239 Execution time for sess_predict Average 0.00155 min=0.00128 max=0.00247 Let's do the same for the probabilities. .. code-block:: python print("Execution time for predict_proba") speed("loop(X_test, clr.predict_proba, 100)") def sess_predict_proba(x): return sess.run([prob_name], {input_name: x.astype(numpy.float32)})[0] print("Execution time for sess_predict_proba") speed("loop(X_test, sess_predict_proba, 100)") .. rst-class:: sphx-glr-script-out Out: .. code-block:: none Execution time for predict_proba Average 0.00396 min=0.0034 max=0.00516 Execution time for sess_predict_proba Average 0.00171 min=0.0014 max=0.00269 This second comparison is better as ONNX Runtime, in this experience, computes the label and the probabilities in every case. Benchmark with RandomForest +++++++++++++++++++++++++++ We first train and save a model in ONNX format. .. code-block:: python from sklearn.ensemble import RandomForestClassifier rf = RandomForestClassifier() rf.fit(X_train, y_train) initial_type = [('float_input', FloatTensorType([1, 4]))] onx = convert_sklearn(rf, initial_types=initial_type) with open("rf_iris.onnx", "wb") as f: f.write(onx.SerializeToString()) We compare. .. code-block:: python sess = rt.InferenceSession("rf_iris.onnx") def sess_predict_proba_rf(x): return sess.run([prob_name], {input_name: x.astype(numpy.float32)})[0] print("Execution time for predict_proba") speed("loop(X_test, rf.predict_proba, 100)") print("Execution time for sess_predict_proba") speed("loop(X_test, sess_predict_proba_rf, 100)") .. rst-class:: sphx-glr-script-out Out: .. code-block:: none Execution time for predict_proba Average 0.0578 min=0.0551 max=0.0601 Execution time for sess_predict_proba Average 0.00177 min=0.00145 max=0.0029 Let's see with different number of trees. .. code-block:: python measures = [] for n_trees in range(5, 51, 5): print(n_trees) rf = RandomForestClassifier(n_estimators=n_trees) rf.fit(X_train, y_train) initial_type = [('float_input', FloatTensorType([1, 4]))] onx = convert_sklearn(rf, initial_types=initial_type) with open("rf_iris_%d.onnx" % n_trees, "wb") as f: f.write(onx.SerializeToString()) sess = rt.InferenceSession("rf_iris_%d.onnx" % n_trees) def sess_predict_proba_loop(x): return sess.run([prob_name], {input_name: x.astype(numpy.float32)})[0] tsk = speed("loop(X_test, rf.predict_proba, 100)", number=5, repeat=5) trt = speed("loop(X_test, sess_predict_proba_loop, 100)", number=5, repeat=5) measures.append({'n_trees': n_trees, 'sklearn': tsk, 'rt': trt}) from pandas import DataFrame df = DataFrame(measures) ax = df.plot(x="n_trees", y="sklearn", label="scikit-learn", c="blue", logy=True) df.plot(x="n_trees", y="rt", label="onnxruntime", ax=ax, c="green", logy=True) ax.set_xlabel("Number of trees") ax.set_ylabel("Prediction time (s)") ax.set_title("Speed comparison between scikit-learn and ONNX Runtime\nFor a random forest on Iris dataset") ax.legend() .. image:: /auto_examples/images/sphx_glr_plot_train_convert_predict_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out Out: .. code-block:: none 5 Average 0.0353 min=0.0324 max=0.0386 Average 0.00156 min=0.00135 max=0.00173 10 Average 0.0541 min=0.0519 max=0.0567 Average 0.00157 min=0.00145 max=0.00167 15 Average 0.079 min=0.0768 max=0.0806 Average 0.00187 min=0.00155 max=0.00216 20 Average 0.103 min=0.0994 max=0.109 Average 0.0017 min=0.00168 max=0.00176 25 Average 0.121 min=0.117 max=0.125 Average 0.00195 min=0.00159 max=0.00231 30 Average 0.149 min=0.145 max=0.153 Average 0.00239 min=0.0016 max=0.00324 35 Average 0.17 min=0.163 max=0.178 Average 0.00199 min=0.00162 max=0.00269 40 Average 0.191 min=0.189 max=0.192 Average 0.00183 min=0.00171 max=0.00197 45 Average 0.214 min=0.212 max=0.216 Average 0.00252 min=0.00187 max=0.00345 50 Average 0.236 min=0.226 max=0.243 Average 0.00237 min=0.00182 max=0.00326 **Total running time of the script:** ( 0 minutes 49.102 seconds) .. _sphx_glr_download_auto_examples_plot_train_convert_predict.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: plot_train_convert_predict.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: plot_train_convert_predict.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_