Tensorflow - h5 model to tflite conversion error

2019-07-11 03:50发布

问题:

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.