Keras .h5模型转TensorFlow Lite时出现核心转储错误求助
解决Keras模型转TensorFlow Lite时的Core Dump错误
你遇到的核心转储错误源于独立Keras 3.x与TensorFlow 2.16.x的TF Lite转换器兼容性冲突。Keras 3.x作为独立框架,内部实现逻辑与TensorFlow原生tf.keras存在差异,触发了MLIR转换流程中的类型推断异常。以下是具体修复方案:
方案1:改用TensorFlow内置的tf.keras
直接使用TensorFlow自带的Keras实现,彻底规避独立Keras包的兼容性问题:
- 修改代码导入逻辑,替换所有
keras相关导入为tf.keras:
import tensorflow as tf # 创建tf.keras模型 model = tf.keras.Sequential([ tf.keras.layers.Dense(64, activation='relu', input_shape=(784,)), tf.keras.layers.Dense(64, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 转换并保存TFLite模型 converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() with open('model.tflite', 'wb') as f: f.write(tflite_model) print("TensorFlow Lite model saved successfully!")
- 卸载冲突的独立Keras包:
pip uninstall -y keras keras-core keras-cv
方案2:降级Keras到2.x版本
若需保留独立Keras使用习惯,可降级到与TensorFlow 2.16兼容的Keras 2.x版本:
- 执行降级命令:
pip install keras==2.16.0
- 保持原代码不变,重新运行转换脚本即可。
方案3:先保存为SavedModel再转换
通过SavedModel格式中转,绕开直接转换的兼容性问题:
import tensorflow as tf from keras.models import Sequential from keras.layers import Dense # 创建并编译原模型 model = Sequential([ Dense(64, activation='relu', input_shape=(784,)), Dense(64, activation='relu'), Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 保存为SavedModel格式 model.save('saved_model') # 从SavedModel转换为TFLite converter = tf.lite.TFLiteConverter.from_saved_model('saved_model') tflite_model = converter.convert() # 保存TFLite模型 with open('model.tflite', 'wb') as f: f.write(tflite_model) print("TensorFlow Lite model saved successfully!")
内容的提问来源于stack exchange,提问作者architect
相关产品推荐
相关产品推荐

