注意
前往末尾以下载完整示例代码。
使用ONNX Runtime加载并预测一个非常简单的模型#
本示例演示了如何加载模型并计算输入向量的输出。它还展示了如何检索其输入和输出的定义。
import numpy
import onnxruntime as rt
from onnxruntime.datasets import get_example
让我们加载一个非常简单的模型。该模型可在GitHub上找到onnx…test_sigmoid。
让我们看看输入名称和形状。
input_name = sess.get_inputs()[0].name
print("input name", input_name)
input_shape = sess.get_inputs()[0].shape
print("input shape", input_shape)
input_type = sess.get_inputs()[0].type
print("input type", input_type)
input name x
input shape [3, 4, 5]
input type tensor(float)
让我们看看输出名称和形状。
output_name = sess.get_outputs()[0].name
print("output name", output_name)
output_shape = sess.get_outputs()[0].shape
print("output shape", output_shape)
output_type = sess.get_outputs()[0].type
print("output type", output_type)
output name y
output shape [3, 4, 5]
output type tensor(float)
让我们计算其输出(如果它是机器学习模型,则为预测)。
import numpy.random # noqa: E402
x = numpy.random.random((3, 4, 5))
x = x.astype(numpy.float32)
res = sess.run([output_name], {input_name: x})
print(res)
[array([[[0.621941 , 0.72691727, 0.68256164, 0.5876679 , 0.7139602 ],
[0.6425402 , 0.54794466, 0.69212383, 0.6305039 , 0.713959 ],
[0.6778656 , 0.5968877 , 0.65848243, 0.5313813 , 0.53988856],
[0.518672 , 0.53184295, 0.51939714, 0.72440046, 0.6525416 ]],
[[0.53604835, 0.7225403 , 0.7089075 , 0.73104435, 0.7309437 ],
[0.6551483 , 0.67507166, 0.5563903 , 0.5365574 , 0.68158686],
[0.5664121 , 0.5242777 , 0.61629784, 0.6485843 , 0.5870835 ],
[0.69044626, 0.7160908 , 0.7280123 , 0.70183516, 0.5370824 ]],
[[0.61034083, 0.5454058 , 0.7152703 , 0.71897334, 0.698861 ],
[0.6628639 , 0.5541799 , 0.67227405, 0.5210765 , 0.5099362 ],
[0.59387696, 0.64475983, 0.5747238 , 0.5491692 , 0.7048832 ],
[0.7134879 , 0.68937397, 0.5989742 , 0.61905456, 0.7057942 ]]],
dtype=float32)]
脚本总运行时间: (0分0.006秒)