You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Keras模型转ONNX格式报错求助:AttributeError问题

解决Keras模型转ONNX时的AttributeError问题

问题原因

keras2onnx库已停止维护,对新版TensorFlow的Keras模块兼容性较差,报错是因为它试图访问tensorflow.python.keras.applications,但新版TensorFlow的结构已调整,该路径下没有applications属性。

解决方案

改用tf2onnx库进行转换,这是官方推荐的TensorFlow转ONNX工具,对新版TensorFlow支持更完善。

步骤1:安装tf2onnx

执行以下命令安装:

pip install tf2onnx

步骤2:修改转换代码

替换原代码为:

import tensorflow as tf
import onnx

# 加载Keras模型
model = tf.keras.models.load_model('b_model.h5')

# 转换为ONNX格式并保存
onnx_model, _ = tf2onnx.convert.from_keras(model, output_path='onnx_model.onnx')

额外注意事项

  • 如果你的模型中使用了预训练模型,确保导入时用tf.keras.applications而非旧的keras.applications,避免路径混淆。
  • 转换完成后可验证模型有效性(根据自身模型输入形状调整测试数据):
import onnxruntime as rt

sess = rt.InferenceSession('onnx_model.onnx')
# 生成符合输入形状的测试数据
input_data = tf.random.normal([1, 224, 224, 3])
output = sess.run(None, {sess.get_inputs()[0].name: input_data.numpy()})
print(output)

内容的提问来源于stack exchange,提问作者user15675493

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:34:56