Tensorflow-H5模型到Tflite转换错误

时间:2019-01-16 06:18:56

标签: tensorflow keras tensorflow-lite

我已经使用预先训练的InceptionV3模型进行了学习转移,并保存了h5模型文件。之后,我可以做出预测。 现在,我想使用TFLiteConverter.convert()方法将h5模型转换为tflite文件,如下所示:

converter = lite.TFLiteConverter.from_keras_model_file('keras.model.h5')
tflite_model = converter.convert()

但我收到此错误:

File "from_saved_model.py", line 28, in <module>
    tflite_model = converter.convert()
  File "C:\Anaconda3\lib\site-packages\tensorflow\contrib\lite\python\lite.py", line 409, in convert
    "invalid shape '{1}'.".format(_tensor_name(tensor), shape))
ValueError: None is only supported in the 1st dimension. Tensor 'input_1' has invalid shape '[None, None, None, 3]'

我正在Windows 10 64位上运行Anaconda Python 3.6.8。预先感谢您的帮助!

3 个答案:

答案 0 :(得分:2)

将模型从TensorFlow转换为TensorFlow Lite时,仅批次大小(索引0)允许为None。调用input_shapes时,应该能够使用from_keras_model_file参数来使输入数组形状有效。对于InceptionV3模型,input_shapes参数通常为{'Mul' : [1,299,299,3]}

here提供了TFLiteConverter.from_keras_model_file的文档。可接受的参数如下(从文档中复制):

from_keras_model_file(
    cls,
    model_file,
    input_arrays=None,
    input_shapes=None,
    output_arrays=None
)

答案 1 :(得分:0)

  1. 加载keras.model.h5
  2. 设置input_shape,只需避免[无,无,无,3]
  3. 将其另存为新模型。
  4. 仅使用您在问题中发布的代码对其进行转换。

答案 2 :(得分:0)

batch_size是唯一可以不指定的尺寸。

input_shape中的第一个尺寸是batch_size,第二个和第三个尺寸表示图像的输入尺寸,最后一个表示通道数(RGB)。

为避免出现错误,请事先指定尺寸。

这可以使用toco(一种将获取的keras模型直接转换为.tflite而不先将其转换为.pb模型然后再转换为.tflite模型的工具来实现)。 在toco中使用input_shape参数,您可以指定keras模型的input_shape的尺寸。

安装适用于python的toco,然后运行以下命令,

toco --output_file = output_model.tflite --keras_model_file = keras.model.h5 --input_arrays input_1 --input_shape 1,299,299,3

此处,batch_size尺寸可能会因您的型号而异。至于输入尺寸,299x299是InceptionV3型号的默认输入尺寸。

相关问题