tensorflow can not convert keras model to tensorflow lite

Issue

so this is my model

model = tf.keras.Sequential([
layers.Dense(40, activation='tanh'),
layers.Dense(9)   
])
learning_rate=tf.keras.optimizers.schedules.ExponentialDecay(
                                                                                                        
initial_learning_rate=0.001,
                                                                                                        
decay_steps=640000,
                                                                                                        
decay_rate=0.001,
                                                                                                                        
 )
 model.compile(
optimizer=tf.keras.optimizers.Adam(learning_rate=learning_rate),
                      loss='MSE',
                    metrics = distance,
 )  

save_callback = keras.callbacks.ModelCheckpoint(
'modle_new',
monitor='distance',
save_best_only=True
 )
model.fit(x, y, epochs=100,batch_size=64, callbacks=save_callback, verbose=2)

and I try to convert this model to tensorflow lite model.

converter = tf.lite.TFLiteConverter.from_saved_model('modle_new')
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]
tflite_model = converter.convert()

and it does not work.

this is errors

and I try to use tf.lite.TFLiteConverter.from_keras_model(model), it does not work neither.I hope someone can solve this problem, and thanks in advance.

Solution

I have already solved this problem, though I don’t know the priciple.

converter = tf.lite.TFLiteConverter.from_saved_model('modle_new/')
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.float16]
converter.target_spec.supported_ops = [
  tf.lite.OpsSet.TFLITE_BUILTINS, # enable TensorFlow Lite ops.
  tf.lite.OpsSet.SELECT_TF_OPS # enable TensorFlow ops.]
tflite_model = converter.convert()
with tf.io.gfile.GFile('model.tflite', 'wb') as f:
f.write(tflite_model)

if you have the same problem, you can try my code, it may solve your problem.

Answered By – 李嘉浩

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published