ONNX Runtime ONNX 后端#

ONNX Runtime 扩展了 onnx 后端 API,以便使用此运行时运行预测。让我们使用该 API 计算一个简单逻辑回归模型的预测。

import numpy as np
from onnx import load

import onnxruntime.backend as backend

设备取决于包的编译方式,可以是 GPU 或 CPU。

from onnxruntime import datasets, get_device
from onnxruntime.capi.onnxruntime_pybind11_state import InvalidArgument

device = get_device()

name = datasets.get_example("logreg_iris.onnx")
model = load(name)

rep = backend.prepare(model, device)
x = np.array([[-1.0, -2.0]], dtype=np.float32)
try:
    label, proba = rep.run(x)
    print(f"label={label}")
    print(f"probabilities={proba}")
except (RuntimeError, InvalidArgument) as e:
    print(e)
[ONNXRuntimeError] : 2 : INVALID_ARGUMENT : Got invalid dimensions for input: float_input for the following indices
 index: 0 Got: 1 Expected: 3
 Please fix either the inputs/outputs or the model.

后端也可以不使用 onnx 直接加载模型。

rep = backend.prepare(name, device)
x = np.array([[-1.0, -2.0]], dtype=np.float32)
try:
    label, proba = rep.run(x)
    print(f"label={label}")
    print(f"probabilities={proba}")
except (RuntimeError, InvalidArgument) as e:
    print(e)
[ONNXRuntimeError] : 2 : INVALID_ARGUMENT : Got invalid dimensions for input: float_input for the following indices
 index: 0 Got: 1 Expected: 3
 Please fix either the inputs/outputs or the model.

后端 API 由其他框架实现,这使得在多个运行时之间使用相同的 API 进行切换变得更容易。

脚本总运行时间: (0 分钟 0.026 秒)

图库由 Sphinx-Gallery 生成