教程#

ONNX Runtime 提供了一种简单的方法,可以在 CPU 或 GPU 上高性能运行机器学习模型,且无需依赖于训练框架。机器学习框架通常针对批量训练而非预测进行优化,而预测是应用程序、网站和服务中更常见的场景。在宏观层面,您可以:

  1. 使用您喜欢的框架训练模型。

  2. 将模型转换或导出为 ONNX 格式。详情请参阅 ONNX 教程

  3. 使用 ONNX Runtime 加载并运行模型。

在本教程中,我们将简要地使用 scikit-learn 创建一个管道,将其转换为 ONNX 格式并运行首次预测。

步骤 1:使用您喜欢的框架训练模型#

我们将使用著名的鸢尾花数据集。

<<<

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y)

from sklearn.linear_model import LogisticRegression
clr = LogisticRegression()
clr.fit(X_train, y_train)
print(clr)

>>>

    LogisticRegression()

步骤 2:将模型转换或导出为 ONNX 格式#

ONNX 是一种描述机器学习模型的格式。它定义了一组常用的运算符来组合模型。有工具可以将其他模型格式转换为 ONNX。这里我们将使用 ONNXMLTools

<<<

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())

>>>

    

步骤 3:使用 ONNX Runtime 加载并运行模型#

我们将使用 ONNX Runtime 计算此机器学习模型的预测。

<<<

import numpy
import onnxruntime as rt

sess = rt.InferenceSession(
    "logreg_iris.onnx", providers=rt.get_available_providers())
input_name = sess.get_inputs()[0].name
pred_onx = sess.run(None, {input_name: X_test.astype(numpy.float32)})[0]
print(pred_onx)

>>>

    [1 2 1 2 2 2 0 1 0 2 2 2 2 1 1 1 1 2 0 1 0 2 0 2 0 0 0 0 2 2 1 2 1 1 1 0 2
     1]

可以通过将特定输出的名称指定到列表中来更改代码以获取该特定输出。

<<<

import numpy
import onnxruntime as rt

sess = rt.InferenceSession(
    "logreg_iris.onnx", providers=rt.get_available_providers())
input_name = sess.get_inputs()[0].name
label_name = sess.get_outputs()[0].name
pred_onx = sess.run(
    [label_name], {input_name: X_test.astype(numpy.float32)})[0]
print(pred_onx)

>>>

    [1 2 1 2 2 2 0 1 0 2 2 2 2 1 1 1 1 2 0 1 0 2 0 2 0 0 0 0 2 2 1 2 1 1 1 0 2
     1]