使用TensorFlow Lite转换Keras模型报错:无from_keras_model_file属性
Keras模型转TFLite报错:AttributeError: TFLiteConverterV2 has no attribute 'from_keras_model_file'
错误信息
执行模型转换代码时触发以下错误:
converter = tf.lite.TFLiteConverter.from_keras_model_file('models/modelo.h5') AttributeError: type object 'TFLiteConverterV2' has no attribute 'from_keras_model_file'
完整复现代码
import tensorflow as tf from tensorflow import keras # 加载数据集 mnist = keras.datasets.mnist (x_train, y_train),(x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 # 自定义回调(注释状态) # class myCallback(tf.keras.callbacks.Callback): # def on_epoch_end(self, epoch, logs={}): # # TF1.x中需将'accuracy'改为'acc' # if(logs.get('accuracy')>0.99): # print("\n准确率达到99.0%,终止训练!") # self.model.stop_training = True # 构建模型 model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 训练模型 model.fit(x_train, y_train, epochs=25,) # callbacks=[myCallback()]) # 评估模型 model.evaluate(x_test, y_test) # 保存模型 model.save('models/modelo.h5') # 转换模型(报错代码) converter = tf.lite.TFLiteConverter.from_keras_model_file('models/modelo.h5') tflite_model = converter.convert() open("models/converted_mnist_model.tflite", "wb").write(tflite_model)
解决方案
错误原因是TensorFlow 2.x 已移除from_keras_model_file方法,该方法属于TF1.x的旧API,以下是三种可行的替代方案:
方案1:直接用训练好的模型对象转换
无需先保存再加载,训练完成后直接使用内存中的model对象转换,步骤最少:
# 替换原转换代码段 converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert() open("models/converted_mnist_model.tflite", "wb").write(tflite_model)
方案2:加载.h5模型后转换
如果需要从已保存的.h5文件加载,先通过Keras加载模型再转换:
# 加载.h5格式模型 loaded_model = tf.keras.models.load_model('models/modelo.h5') # 转换为TFLite格式 converter = tf.lite.TFLiteConverter.from_keras_model(loaded_model) tflite_model = converter.convert() open("models/converted_mnist_model.tflite", "wb").write(tflite_model)
方案3:使用SavedModel格式(TF2.x推荐)
TF2.x推荐使用SavedModel格式保存模型,兼容性更好:
- 修改模型保存代码:
# 替换原model.save('models/modelo.h5') model.save('models/saved_model') # 保存为SavedModel格式
- 修改转换代码:
# 替换原转换代码段 converter = tf.lite.TFLiteConverter.from_saved_model('models/saved_model') tflite_model = converter.convert() open("models/converted_mnist_model.tflite", "wb").write(tflite_model)
内容的提问来源于stack exchange,提问作者mauricio
相关产品推荐
相关产品推荐

