无法将 .h5 文件转换为 tflite 模型

Unable to convert a .h5 fileto a tflite model

我训练了一个模型并将其保存为 h5 文件。因为我想在我的 android 应用程序中使用它,所以我希望将它转换为 Colab 上的 tflite。这是我的代码:

import tensorflow as tf
model = tf.keras.models.load_model('Final_model.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

我遇到的错误:

AttributeError: type object 'TFLiteConverter' has no attribute 'from_keras_model'

我该如何解决这个问题?

您使用的是 Tensorflow 1.x,在此上下文中稍微 different API。你应该使用的是 from_keras_model_file,即:

converter = tf.lite.TFLiteConverter.from_keras_model_file('Final_model.h5')

您正在使用 colab's 默认值 tensorflow,即 1.15.0

您可以通过从 colab 的 cell 发出来下载最新版本:

!pip install --upgrade pip && pip install tensorflow.

您可能需要通过以下命令预先卸载 tensorflow 版本 1.15.0:

!pip uninstall tensorflow (or tensorflow-gpu).

在那之后你应该能够运行tf2.x编码。

注意:很快 TF2.0 将成为默认版本,此解决方法是临时的。