【问题标题】:Tensorflow - h5 model to tflite conversion errorTensorflow - h5模型到tflite转换错误
【发布时间】:2019-06-10 04:56:54
【问题描述】:

我使用预训练的 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。提前感谢您的帮助!

【问题讨论】:

  • 在保存 keras 模型之前,能否确保 in_tensors 的形状正确([None, x, y, 3])?
  • 您的问题解决了吗?我面临着完全相同的问题

标签: tensorflow keras keras-layer tensorflow-lite


【解决方案1】:

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

TFLiteConverter.from_keras_model_file 的文档可在here 获得。接受的参数如下(从文档中复制):

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

【讨论】:

    【解决方案2】:
    1. 加载 keras.model.h5
    2. 设置input_shape,避免[None, None, None, 3]
    3. 将其另存为新模型。
    4. 仅使用您在问题中发布的代码进行转换。

    【讨论】:

      【解决方案3】:

      batch_size 是唯一可以指定为 none 的维度。

      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 模型的默认输入尺寸。

      【讨论】:

        猜你喜欢
        • 2020-09-10
        • 1970-01-01
        • 2021-06-11
        • 2021-12-09
        • 2020-10-10
        • 1970-01-01
        • 2022-06-30
        • 1970-01-01
        • 2018-08-17
        相关资源
        最近更新 更多