I am using tensorflow version 2.3.1 and keras 2.4.3 I trained a keras model where after training I tried to convert it to tflite model using the following commands:
from keras.models import load_model
import tensorflow as tf
model = load_model("model.h5")
converter = tf.lite.TFLiteConverter.from_saved_model(model)
I get this error:
TypeError Traceback (most recent call last)
<ipython-input-4-759f94851ff5> in <module>
----> 1 converter = tf.lite.TFLiteConverter.from_saved_model(model)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\lite\python\lite.py in from_saved_model(cls, saved_model_dir, signature_keys, tags)
1026
1027 with context.eager_mode():
-> 1028 saved_model = _load(saved_model_dir, tags)
1029 if not signature_keys:
1030 signature_keys = saved_model.signatures
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\saved_model\load.py in load(export_dir, tags, options)
601 ValueError: If `tags` don't match a MetaGraph in the SavedModel.
602 """
--> 603 return load_internal(export_dir, tags, options)
604
605
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\saved_model\load.py in load_internal(export_dir, tags, options, loader_cls)
612 tags = nest.flatten(tags)
613 saved_model_proto, debug_info = (
--> 614 loader_impl.parse_saved_model_with_debug_info(export_dir))
615
616 if (len(saved_model_proto.meta_graphs) == 1 and
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\saved_model\loader_impl.py in parse_saved_model_with_debug_info(export_dir)
54 parsed. Missing graph debug info file is fine.
55 """
---> 56 saved_model = _parse_saved_model(export_dir)
57
58 debug_info_path = os.path.join(
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\saved_model\loader_impl.py in parse_saved_model(export_dir)
84 # Build the path to the SavedModel in pbtxt format.
85 path_to_pbtxt = os.path.join(
---> 86 compat.as_bytes(export_dir),
87 compat.as_bytes(constants.SAVED_MODEL_FILENAME_PBTXT))
88 # Build the path to the SavedModel in pb format.
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\util\compat.py in as_bytes(bytes_or_text, encoding)
84 return bytes_or_text
85 else:
---> 86 raise TypeError('Expected binary or unicode string, got %r' %
87 (bytes_or_text,))
88
TypeError: Expected binary or unicode string, got <tensorflow.python.keras.engine.functional.Functional object at 0x0000022EC9005250>
I have no idea how to resolve this and why this has occured. Any suggestion to resolve this?
You are trying to use converting method from saved_model
protobuf with keras model. Your method is tf.lite.TFLiteConverter.from_keras_model(model)
:
import tensorflow as tf
from tensorflow import keras
model = keras.models.load_model('path/to/location')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
See details here