How to beginner · 3 min read

How to export TensorFlow model to ONNX

Quick answer
Use the tf2onnx Python package to convert a TensorFlow model to ONNX format. Load your TensorFlow model, then run tf2onnx.convert.from_keras() or tf2onnx.convert.from_saved_model() to export it as an ONNX file.

PREREQUISITES

  • Python 3.8+
  • pip install tensorflow
  • pip install tf2onnx

Setup

Install the required packages tensorflow and tf2onnx using pip.

bash
pip install tensorflow tf2onnx

Step by step

This example shows how to export a simple TensorFlow Keras model to ONNX format using tf2onnx.

python
import tensorflow as tf
import tf2onnx

# Create a simple Keras model
model = tf.keras.Sequential([
    tf.keras.layers.InputLayer(input_shape=(28, 28)),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(10, activation='softmax')
])

# Save the model in SavedModel format
saved_model_path = "./saved_model"
model.save(saved_model_path)

# Convert the Keras model to ONNX
import tf2onnx.convert

spec = (tf.TensorSpec((None, 28, 28), tf.float32, name="input"),)

model_proto, external_tensor_storage = tf2onnx.convert.from_keras(
    model,
    input_signature=spec,
    opset=17
)

# Save the ONNX model to a file
onnx_model_path = "model.onnx"
with open(onnx_model_path, "wb") as f:
    f.write(model_proto.SerializeToString())

print(f"ONNX model saved to {onnx_model_path}")
output
ONNX model saved to model.onnx

Common variations

You can also convert a TensorFlow SavedModel directory directly to ONNX using tf2onnx.convert.from_saved_model(). For example:

python
import tf2onnx

saved_model_path = "./saved_model"

model_proto, _ = tf2onnx.convert.from_saved_model(
    saved_model_path,
    opset=17
)

onnx_model_path = "model_from_saved_model.onnx"
with open(onnx_model_path, "wb") as f:
    f.write(model_proto.SerializeToString())

print(f"ONNX model saved to {onnx_model_path}")
output
ONNX model saved to model_from_saved_model.onnx

Troubleshooting

  • If you get errors about unsupported ops, try upgrading tf2onnx to the latest version.
  • Ensure your TensorFlow model uses ops supported by ONNX opset 17 or adjust the opset parameter accordingly.
  • For complex models, exporting from the SavedModel directory is more reliable than from Keras directly.

Key Takeaways

  • Use tf2onnx to convert TensorFlow models to ONNX format easily.
  • Export from Keras models or SavedModel directories depending on your workflow.
  • Always specify the ONNX opset version (e.g., 17) for compatibility.
  • Upgrade tf2onnx if you encounter unsupported operator errors.
  • Saving the ONNX model requires writing the serialized protobuf to a file.
Verified 2026-04 · tf2onnx, tensorflow
Verify ↗