Note
Click here to download the full example code
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 onnxruntime as rt
import numpy
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)
Out:
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)
Out:
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
x = numpy.random.random((3,4,5))
x = x.astype(numpy.float32)
res = sess.run([output_name], {input_name: x})
print(res)
Out:
[array([[[0.7282232 , 0.55751914, 0.6318114 , 0.5736186 , 0.5210682 ],
[0.5551789 , 0.50124794, 0.5218111 , 0.58663917, 0.7030232 ],
[0.54759526, 0.60854995, 0.5004847 , 0.6313993 , 0.7113242 ],
[0.5441941 , 0.5421912 , 0.5857317 , 0.6881397 , 0.63593704]],
[[0.65265447, 0.52420175, 0.6876056 , 0.6252413 , 0.5143449 ],
[0.5869513 , 0.58136684, 0.60523754, 0.59603804, 0.70649385],
[0.65459174, 0.58812606, 0.59879124, 0.5215285 , 0.5047252 ],
[0.5102888 , 0.5441282 , 0.674335 , 0.6463818 , 0.7018383 ]],
[[0.592211 , 0.7291903 , 0.62842566, 0.50748336, 0.6976217 ],
[0.615195 , 0.609173 , 0.66978675, 0.573927 , 0.7099608 ],
[0.6536062 , 0.5290325 , 0.5949771 , 0.52116865, 0.5360124 ],
[0.6968157 , 0.67949474, 0.6668297 , 0.68328327, 0.6817404 ]]],
dtype=float32)]
Total running time of the script: ( 0 minutes 0.009 seconds)