Google Colab中tf2onnx转换突然失效,如何修复?
解决Colab中tf2onnx转换Keras模型的AttributeError问题
近期Google Colab里所有用到tf2onnx的笔记本都突然无法正常工作,执行Keras转ONNX的代码时会触发如下错误:
测试代码:
import tensorflow as tf import tf2onnx import onnx model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(4, activation="relu")) input_signature = [tf.TensorSpec([3, 3], tf.float32, name='x')] onnx_model, _ = tf2onnx.convert.from_keras(model, input_signature, opset=13) onnx.save(onnx_model, "test_model.onnx")
报错信息:
AttributeError Traceback (most recent call last) <ipython-input-2-820fe10709d8> in <cell line: 13>() 11 input_signature = [tf.TensorSpec([3, 3], tf.float32, name='x')] 12 ---> 13 onnx_model, _ = tf2onnx.convert.from_keras(model, input_signature, opset=13) 14 onnx.save(onnx_model, "test_model.onnx") 1 frames /usr/local/lib/python3.10/dist-packages/tf2onnx/convert.py in _rename_duplicate_keras_model_names(model) 329 """ 330 old_out_names = None ---> 331 if model.output_names and len(set(model.output_names)) != len(model.output_names): 332 # In very rare cases, keras has a bug where it will give multiple outputs the same name 333 # We must edit the model or the TF trace will fail AttributeError: 'Sequential' object has no attribute 'output_names'
试过使用tf2onnx.convert.from_function也无效,下面是两种可行的解决办法:
方案1:安装兼容版本的tf2onnx
问题根源是新版Keras(随TensorFlow更新)移除了Sequential模型的output_names属性,但当前Colab默认安装的tf2onnx版本仍依赖该属性。直接锁定到兼容版本即可:
!pip uninstall -y tf2onnx !pip install tf2onnx==1.15.0
亲测1.15.0版本能适配Colab当前的TensorFlow环境,后续若版本更新可尝试更高的兼容版本。
方案2:手动给模型添加output_names属性
如果不想改动包版本,也可以在转换前手动给模型补上这个属性:
import tensorflow as tf import tf2onnx import onnx model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(4, activation="relu")) # 手动添加output_names属性,名称可自定义 model.output_names = ["output_layer"] input_signature = [tf.TensorSpec([3, 3], tf.float32, name='x')] onnx_model, _ = tf2onnx.convert.from_keras(model, input_signature, opset=13) onnx.save(onnx_model, "test_model.onnx")
内容的提问来源于stack exchange,提问作者olegeskevich
相关产品推荐
相关产品推荐

