2018-11-19 16:48:22 -08:00
|
|
|
# Copyright (c) Microsoft Corporation. All rights reserved.
|
|
|
|
|
# Licensed under the MIT License.
|
|
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
.. _l-example-backend-api:
|
|
|
|
|
|
|
|
|
|
ONNX Runtime Backend for ONNX
|
|
|
|
|
=============================
|
|
|
|
|
|
2022-08-30 13:41:42 -07:00
|
|
|
*ONNX Runtime* extends the
|
|
|
|
|
`onnx backend API <https://github.com/onnx/onnx/blob/main/docs/ImplementingAnOnnxBackend.md>`_
|
2018-11-19 16:48:22 -08:00
|
|
|
to run predictions using this runtime.
|
|
|
|
|
Let's use the API to compute the prediction
|
|
|
|
|
of a simple logistic regression model.
|
|
|
|
|
"""
|
2025-01-16 11:14:15 -08:00
|
|
|
|
2018-11-19 16:48:22 -08:00
|
|
|
import numpy as np
|
|
|
|
|
from onnx import load
|
|
|
|
|
|
2022-04-26 09:35:16 -07:00
|
|
|
import onnxruntime.backend as backend
|
|
|
|
|
|
2021-03-22 10:20:33 -07:00
|
|
|
########################################
|
|
|
|
|
# The device depends on how the package was compiled,
|
|
|
|
|
# GPU or CPU.
|
2022-04-26 09:35:16 -07:00
|
|
|
from onnxruntime import datasets, get_device
|
|
|
|
|
from onnxruntime.capi.onnxruntime_pybind11_state import InvalidArgument
|
|
|
|
|
|
2021-03-22 10:20:33 -07:00
|
|
|
device = get_device()
|
|
|
|
|
|
2018-11-19 16:48:22 -08:00
|
|
|
name = datasets.get_example("logreg_iris.onnx")
|
|
|
|
|
model = load(name)
|
|
|
|
|
|
2021-03-22 10:20:33 -07:00
|
|
|
rep = backend.prepare(model, device)
|
2018-11-19 16:48:22 -08:00
|
|
|
x = np.array([[-1.0, -2.0]], dtype=np.float32)
|
2019-09-26 20:25:59 +02:00
|
|
|
try:
|
|
|
|
|
label, proba = rep.run(x)
|
2023-03-24 15:29:03 -07:00
|
|
|
print(f"label={label}")
|
|
|
|
|
print(f"probabilities={proba}")
|
2019-09-26 20:25:59 +02:00
|
|
|
except (RuntimeError, InvalidArgument) as e:
|
|
|
|
|
print(e)
|
2018-11-19 16:48:22 -08:00
|
|
|
|
|
|
|
|
########################################
|
|
|
|
|
# The backend can also directly load the model
|
|
|
|
|
# without using *onnx*.
|
|
|
|
|
|
2021-03-22 10:20:33 -07:00
|
|
|
rep = backend.prepare(name, device)
|
2018-11-19 16:48:22 -08:00
|
|
|
x = np.array([[-1.0, -2.0]], dtype=np.float32)
|
2019-09-26 20:25:59 +02:00
|
|
|
try:
|
|
|
|
|
label, proba = rep.run(x)
|
2023-03-24 15:29:03 -07:00
|
|
|
print(f"label={label}")
|
|
|
|
|
print(f"probabilities={proba}")
|
2019-09-26 20:25:59 +02:00
|
|
|
except (RuntimeError, InvalidArgument) as e:
|
|
|
|
|
print(e)
|
2018-11-19 16:48:22 -08:00
|
|
|
|
|
|
|
|
#######################################
|
|
|
|
|
# The backend API is implemented by other frameworks
|
|
|
|
|
# and makes it easier to switch between multiple runtimes
|
|
|
|
|
# with the same API.
|