Create and check your first ONNX model
ONNX defines a common model format and operators. The Python package lets you create, inspect, and check models. To run a model for inference, choose a compatible runtime.
This example creates a tiny model with one ReLU operator, which replaces negative values with zero. It saves the model to a file, loads it, and checks its structure. No training framework or model download is needed.
1. Install ONNX
With Python and pip available, run this in your terminal, preferably in a virtual environment:
python -m pip install onnx
2. Save this as quickstart.py
import onnx
from onnx import TensorProto, helper
graph = helper.make_graph(
[helper.make_node("Relu", ["X"], ["Y"])],
"relu-example",
[helper.make_tensor_value_info("X", TensorProto.FLOAT, [3])],
[helper.make_tensor_value_info("Y", TensorProto.FLOAT, [3])],
)
model = helper.make_model(graph)
onnx.save(model, "relu.onnx")
loaded_model = onnx.load("relu.onnx")
onnx.checker.check_model(loaded_model)
print("Model structure is valid.")
3. Run the check
python quickstart.py
You should see Model structure is valid. and a new relu.onnx file in your working directory. To check an existing model, use its path in onnx.load() and pass the loaded model to onnx.checker.check_model().
The checker validates model structure; it does not run inference or verify prediction accuracy. See the checker documentation and ONNX with Python for more examples.
Export and run your own model
- Export: use your framework's ONNX exporter or a converter. Start with the converter guide.
- Check: load the exported model and validate it with the checker, as above.
- Run: choose a compatible runtime. For one example, follow the ONNX Runtime Python guide.
An opset version identifies the operator definitions a model uses. Choose an opset supported by both your exporter and target runtime, and check the runtime's support for the model's IR (file format) version, operators, and data types. Passing the checker alone does not guarantee runtime compatibility. Read more about ONNX concepts and versioning.
Build Model
Build and train a machine learning model to meet your project goals using the tools that best meet your needs.
Machine learning frameworks
Develop from scratch using the framework of your choice.
Cloud services
Tools from our partners help you build your model and include both no code and code-first experiences.
Pre-trained models
The Model Zoo provides pre-trained models in ONNX format.
Export to ONNX Format
The process to export your model to ONNX format depends on the framework or service used to train your model.
Models developed using machine learning frameworks
Install the associated library, convert to ONNX format, and save your results.
Reference tutorialsModels from ONNX Model Zoo
No action required.