pythontensorflowonnx

onnx_tf import showing error for module note found


I'm trying to convert my onnx model to tflite model, using the following code:

import tensorflow as tf
import onnx
from onnx_tf.backend import prepare

onnx_model = onnx.load(onnx_path)
tf_rep = prepare(onnx_model)
tf_rep.export_graph(pb_path)

converter = tf.lite.TFLiteConverter.from_frozen_graph(pb_path,
                                                      input_arrays=input_nodes,
                                                      output_arrays=output_nodes)
tflite_rep = converter.convert()

open(tflite_path, "wb").write(tflite_rep)

I'm getting the following error when importing onnx_tf.backend

ModuleNotFoundError: No module named 'keras.src.engine'

I've read other forums about this issue, but the answers seem to be extremely old, and the library upgrade/downgrade don't seem to work for my problem anymore


Solution

  • As you are not naming a specific library I guess you are using the old onnx-tensorflow backend. Regretfully that repository is currently not being maintained and will be deprecated in the future. Lately when I need to convert a model from onnx to tf-lite I've been using the onnx2tflite repository:

    https://github.com/MPolaris/onnx2tflite

    It is really simple to install and use. I've been able to easily convert all the models I needed, including fp16 or int8 versions of them. You can find a minimal example of conversion below:

    from onnx2tflite import onnx_converter
    res = onnx_converter(
            onnx_model_path = "./target-model.onnx"
            output_path = "./output-models/",
            target_formats = ['tflite'],
        )