Tensorflow - h5 model to tflite conversion error

泄露秘密 提交于 2019-12-11 03:12:28

问题


I've made a learning transfer using a pre-trained InceptionV3 model, and I saved the h5 model file. After that, I am able to make predictions. Now, I want to convert the h5 model to tflite file, using TFLiteConverter.convert() method, like this:

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

but I get this error:

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]'

I am running Anaconda Python 3.6.8 on Windows 10 64 bits. Thank you in advance for your help!


回答1:


Only the batch size (index 0) is allowed to be None when converting the model from TensorFlow to TensorFlow Lite. You should be able to use the input_shapes argument when calling from_keras_model_file to get the input array shape to be valid. For an InceptionV3 model, the input_shapes argument is often {'Mul' : [1,299,299,3]}.

The documentation for TFLiteConverter.from_keras_model_file is available here. The accepted parameters are as follows (copied from the documentation):

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



回答2:


  1. load the keras.model.h5
  2. set the input_shape, just avoid [None, None, None, 3]
  3. save it as a new model.
  4. Convert it just using the code you post in the question.



回答3:


The batch_size is the only dimension that can be given as none.

The first dimension in the input_shape is the batch_size, the second and third dimensions indicate the input size of the image while the last one indicates the number of channels (RGB).

To avoid the error you get, specify the dimensions beforehand.

This can be achieved using toco (a tool which directly converts the acquired keras model into .tflite without converting it first to a .pb model and then to a .tflite model). Using input_shape argument in toco you can specify the dimensions of the input_shape of your keras model.

Install toco for python and then run the following command,

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

Here the batch_size dimension might differ according to your model. As for the input size dimensions, 299x299 is the default input size for InceptionV3 models.



来源:https://stackoverflow.com/questions/54211413/tensorflow-h5-model-to-tflite-conversion-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!