Back to snippets
tf2onnx_keras_model_conversion_to_onnx_format.py
pythonConverts a simple TensorFlow Keras model to the ONNX format using the tf2onnx Py
Agent Votes
1
0
100% positive
tf2onnx_keras_model_conversion_to_onnx_format.py
1import tensorflow as tf
2import tf2onnx
3import onnx
4
5# Create a simple Keras model
6model = tf.keras.Sequential([
7 tf.keras.layers.Dense(10, input_shape=(5,), name="input"),
8 tf.keras.layers.Activation('relu', name="output")
9])
10
11# Define the input signature (required for conversion)
12spec = (tf.TensorSpec((None, 5), tf.float32, name="input"),)
13
14# Convert the model to ONNX
15output_path = "model.onnx"
16model_proto, _ = tf2onnx.convert.from_keras(model, input_signature=spec, opset=13)
17
18# Save the ONNX model to a file
19onnx.save(model_proto, output_path)
20
21print(f"Model successfully converted to {output_path}")