7

I'm trying to convert my Keras hdf5 file into a TensorFlow Lite file with the following code:

import tensorflow as tf

# Convert the model.
converter = tf.lite.TFLiteConverter.from_keras_model("/content/best_model_11class.hdf5")
tflite_model = converter.convert()

# Save the TF Lite model.
with tf.io.gfile.GFile('model.tflite', 'wb') as f:
  f.write(tflite_model)

I'm getting this error on the from_keras_model line:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-14-26467c686751> in <module>()
      2 
      3 # Convert the model.
----> 4 converter = tf.lite.TFLiteConverter.from_keras_model("/content/best_model_11class.hdf5")
      5 tflite_model = converter.convert()
      6 

/usr/local/lib/python3.6/dist-packages/tensorflow/lite/python/lite.py in from_keras_model(cls, model)
    426     # to None.
    427     # Once we have better support for dynamic shapes, we can remove this.
--> 428     if not isinstance(model.call, _def_function.Function):
    429       # Pass `keep_original_batch_size=True` will ensure that we get an input
    430       # signature including the batch dimension specified by the user.

AttributeError: 'str' object has no attribute 'call'

How do I fix this? By the way, I'm using Google Colab.

Bert Hanz
  • 417
  • 1
  • 7
  • 16

3 Answers3

12

I'm not sure how stuff works on Colab, but looking at the documentation for tf.lite.TFLiteConverter.from_keras_model I can see that it expects a Keras model instance as an argument but you are giving it a string. Maybe you need to load the Keras model first?

Something like:

keras_model = tf.keras.models.load_model("/content/best_model_11class.hdf5")
converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
matias
  • 340
  • 2
  • 9
  • When I run it now I get `ValueError: None is only supported in the 1st dimension. Tensor 'input_1' has invalid shape '[None, None, None, 3]'.` for the `tfmodel = converter.convert()`. – Bert Hanz Jul 12 '20 at 04:38
3
import tensorflow as tf
model=tf.keras.models.load_model(""/content/best_model_11class.hdf5"")
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.experimental_new_converter = True
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model) 

This worked according to https://github.com/tensorflow/tensorflow/issues/32693

Mados
  • 53
  • 8
0

This error can also appear when, by accident, you try to load only the weights of a saved model instead of the model fully.

For example, it can occur when using ModelCheckpoint() and save_weights_only = True, when only the weights are saved and not other model metadata, hence the same error.

Timbus Calin
  • 13,809
  • 5
  • 41
  • 59