ONNX (Open Neural Network Exchange)

1.21.0 · active · verified Sun Apr 05

ONNX (Open Neural Network Exchange) is an open standard format designed to represent machine learning models, facilitating interoperability between different deep learning frameworks. The library is actively maintained with a regular release cadence, typically seeing major versions every few months interspersed with patch releases. It currently requires Python 3.10 or newer.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically create a simple ONNX model (Y = X + A), validate it using `onnx.checker`, and then save it to a `.onnx` file using the ONNX Python API. It also shows how to load the model back for inspection.

import onnx
from onnx import helper, checker, TensorProto
import numpy as np
import os

# Create a simple ONNX model: Y = X + A
# Define model inputs and outputs
X = helper.make_tensor_value_info('X', TensorProto.FLOAT, [None, 2])
A = helper.make_tensor_value_info('A', TensorProto.FLOAT, [2])
Y = helper.make_tensor_value_info('Y', TensorProto.FLOAT, [None, 2])

# Create a node for the Add operation
node_def = helper.make_node(
    'Add',
    inputs=['X', 'A'],
    outputs=['Y'],
)

# Create the graph
graph_def = helper.make_graph(
    [node_def],
    'simple-add-model',
    [X, A],
    [Y],
)

# Create the model with specified opset_imports (e.g., opset 13)
# Opset 13 is commonly used and widely supported.
model_def = helper.make_model(
    graph_def,
    producer_name='onnx-example',
    opset_imports=[helper.make_opsetid('', 13)]
)

# Check the model for validity
checker.check_model(model_def)
print('Model is valid!')

# Save the model to a file
model_path = 'simple_add_model.onnx'
onnx.save(model_def, model_path)
print(f'Model saved to {model_path}')

# Optional: Load the model back and print its structure
loaded_model = onnx.load(model_path)
print('\nLoaded model:\n', loaded_model.graph.node)

# Clean up the created file
# os.remove(model_path)

view raw JSON →