Cannot convert TensorFlow (Keras) model to ONNX

2.5k views Asked by At

I'm trying to convert a saved TensorFlow model to the ONNX format, but am getting the following error.

in _load_nodes
    slot_variable = optimizer_object.add_slot(
AttributeError: '_UserObject' object has no attribute 'add_slot'

I used Keras (2.6) to save the model with model.save(os.path.join("models", 'modelData')). Then, I used python -m tf2onnx.convert --saved-model modelData --output model.onnx to convert the model.

Using keras2onnx doesn't work for me, because the library is too old (and their repository redirects to tf2onnx anyway).

I tried converting from a checkpoint file, by using python -m tf2onnx.convert --checkpoint checkpoint/keras_metadata.pb --output model.onnx --inputs input0:0,input1:0 --outputs output0:0, but I get the following error.

    saver = tf_import_meta_graph(model_path, clear_devices=True)
  File "####\anaconda3\envs\##\lib\site-packages\tensorflow\python\training\saver.py", line 1465, in import_meta_graph
    return _import_meta_graph_with_return_elements(meta_graph_or_file,
  File "####\anaconda3\envs\##\lib\site-packages\tensorflow\python\training\saver.py", line 1481, in _import_meta_graph_with_return_elements
    meta_graph_def = meta_graph.read_meta_graph_file(meta_graph_or_file)
  File "####\anaconda3\envs\##\lib\site-packages\tensorflow\python\framework\meta_graph.py", line 643, in read_meta_graph_file
    text_format.Merge(file_content.decode("utf-8"), meta_graph_def)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 1: invalid start byte

Is there something special that I should do to the model before saving it? Could this be some version mismatch? Any feedback would be helpful.

1

There are 1 answers

0
Igor Ševo On

I resolved the issue by converting the model immediately after training. I used the following piece of code.

(onnx_model_proto, storage) = tf2onnx.convert.from_keras(model)
with open(os.path.join("models", 'modelData.onnx'), "wb") as f:
    f.write(onnx_model_proto.SerializeToString())

However, this does not solve the conversion problem with the saved model.