adica007
adica007

Reputation: 31

Tensorflow - h5 model to tflite conversion error

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!

Upvotes: 3

Views: 2986

Answers (3)

Savini Abayaratne
Savini Abayaratne

Reputation: 1

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.

Upvotes: 0

Li Mengyu
Li Mengyu

Reputation: 1

  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.

Upvotes: 0

Nupur Garg
Nupur Garg

Reputation: 524

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
)

Upvotes: 2

Related Questions