Load and predict with ONNX Runtime and a very simple model#

This example demonstrates how to load a model and compute the output for an input vector. It also shows how to retrieve the definition of its inputs and outputs.

import numpy

import onnxruntime as rt
from onnxruntime.datasets import get_example

Let’s load a very simple model. The model is available on github onnx…test_sigmoid.

example1 = get_example("sigmoid.onnx")
sess = rt.InferenceSession(example1, providers=rt.get_available_providers())

Let’s see the input name and shape.

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)

Let’s see the output name and shape.

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)

Let’s compute its outputs (or predictions if it is a machine learned model).

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.71643436, 0.51789904, 0.5776231 , 0.54161996, 0.6709081 ],
        [0.61651474, 0.62888134, 0.6780188 , 0.668985  , 0.50648594],
        [0.56173986, 0.6026399 , 0.7224795 , 0.54880357, 0.5932396 ],
        [0.6758331 , 0.69040954, 0.5648656 , 0.52470195, 0.62636435]],

       [[0.6880126 , 0.50053066, 0.6319874 , 0.63352334, 0.5132136 ],
        [0.6835232 , 0.61182904, 0.65675426, 0.64539117, 0.72575974],
        [0.56595016, 0.5505095 , 0.6397259 , 0.71825844, 0.6727885 ],
        [0.6772646 , 0.5363317 , 0.5059594 , 0.52682185, 0.5928872 ]],

       [[0.5426415 , 0.5070284 , 0.5905969 , 0.71749663, 0.68407834],
        [0.5367806 , 0.62588406, 0.7269159 , 0.536526  , 0.59537625],
        [0.68701804, 0.66258526, 0.55262274, 0.69248503, 0.5519953 ],
        [0.62890136, 0.7252861 , 0.5904105 , 0.6168434 , 0.650836  ]]],
      dtype=float32)]

Total running time of the script: (0 minutes 0.006 seconds)

Gallery generated by Sphinx-Gallery