将MobileNet模型从.h5转.tflite时遇属性缺失及LLVM类型推断错误求助
解决MobileNet模型转TFLite时的"missing attribute 'value'"和LLVM类型推断错误
可行解决方案:
1. 移除不必要的模型重新编译步骤
转TFLite不需要重新编译模型,这一步反而可能引发兼容性问题。直接删除loadmodel.compile(...)代码:
import tensorflow as tf loadmodel = tf.keras.models.load_model('trained_model.h5') converter = tf.lite.TFLiteConverter.from_keras_model(loadmodel) model = converter.convert() with open('trained_model.tflite' , 'wb') as file: file.write(model)
2. 强制使用TensorFlow内置Keras加载模型
Keras 3作为多后端框架,和TensorFlow 2.16.1存在适配问题。强制切换到TensorFlow原生Keras:
import tensorflow as tf from tensorflow import keras # 指定TensorFlow为Keras后端 keras.backend.set_backend('tensorflow') loadmodel = tf.keras.models.load_model('trained_model.h5') converter = tf.lite.TFLiteConverter.from_keras_model(loadmodel) model = converter.convert() with open('trained_model.tflite' , 'wb') as file: file.write(model)
3. 先转成SavedModel格式再转换TFLite
.h5格式在跨版本/跨框架场景下易出问题,先转成TensorFlow原生的SavedModel格式:
import tensorflow as tf # 加载模型并保存为SavedModel loadmodel = tf.keras.models.load_model('trained_model.h5') loadmodel.save('trained_savedmodel') # 从SavedModel转换为TFLite converter = tf.lite.TFLiteConverter.from_saved_model('trained_savedmodel') model = converter.convert() with open('trained_model.tflite' , 'wb') as file: file.write(model)
4. 启用TF算子兼容模式
如果是算子不兼容导致的类型推断失败,开启TF算子支持:
import tensorflow as tf loadmodel = tf.keras.models.load_model('trained_model.h5') converter = tf.lite.TFLiteConverter.from_keras_model(loadmodel) # 支持TFLite内置算子和TF原生算子 converter.target_spec.supported_ops = [ tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS ] converter.allow_custom_ops = True model = converter.convert() with open('trained_model.tflite' , 'wb') as file: file.write(model)
5. 指定输入输出数据类型
手动明确模型的输入输出类型为标准float32:
import tensorflow as tf loadmodel = tf.keras.models.load_model('trained_model.h5') converter = tf.lite.TFLiteConverter.from_keras_model(loadmodel) converter.inference_input_type = tf.float32 converter.inference_output_type = tf.float32 model = converter.convert() with open('trained_model.tflite' , 'wb') as file: file.write(model)
内容的提问来源于stack exchange,提问作者Los
相关产品推荐
相关产品推荐

