Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert keras(h5) file to a tflite file?

from tensorflow.contrib import lite
converter = lite.TFLiteConverter.from_keras_model_file( 'model.h5')
tfmodel = converter.convert()
open ("model.tflite" , "wb") .write(tfmodel)

You can use the TFLiteConverter to directly convert .h5 files to .tflite file. This does not work on Windows.

For Windows, use this Google Colab notebook to convert. Upload the .h5 file and it will convert it .tflite file.

Follow, if you want to try it yourself :

  1. Create a Google Colab Notebook. In the left top corner, click the "UPLOAD" button and upload your .h5 file.
  2. Create a code cell and insert this code.

    from tensorflow.contrib import lite
    converter = lite.TFLiteConverter.from_keras_model_file( 'model.h5' ) # Your model's name
    model = converter.convert()
    file = open( 'model.tflite' , 'wb' ) 
    file.write( model )
    
  3. Run the cell. You will get a model.tflite file. Right click on the file and select "DOWNLOAD" option.


This worked for me on Windows 10 using Tensorflow 2.1.0 and Keras 2.3.1

import tensorflow as tf

model = tf.keras.models.load_model('model.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

Just did this from CoLab using this code in a notebook:

import tensorflow as tf
model = tf.keras.models.load_model('yourmodel.h5')
converter = tf.lite.TFLiteConverter.from_keras_model(model)
tflmodel = converter.convert()
file = open( 'yourmodel.tflite' , 'wb' ) 
file.write( tflmodel )

I had difficulty uploading the h5 model via CoLab so I mounted my Google Drive, uploaded it there, and then moved it over to the notebook content folder.


Converting a GraphDef from the session.

converter = lite.TFLiteConverter.from_session(sess, in_tensors, out_tensors)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

Converting a GraphDef from file.

converter = lite.TFLiteConverter.from_frozen_graph(
graph_def_file, input_arrays, output_arrays)
tflite_model = converter.convert()
open("converted_model.tflite", "wb").write(tflite_model)

Converting a SavedModel.

converter = lite.TFLiteConverter.from_saved_model(saved_model_dir)
tflite_model = converter.convert()

import tensorflow as tf
from tensorflow import lite
from tensorflow.keras.models import load_model
converter = lite.TFLiteConverter.from_keras_model(model)
tfmodel = converter.convert()
open ("model.tflite" , "wb") .write(tfmodel)

This works for me. I am using keras==2.6.0 and tensorflow-cpu==2.5.0 version. For more information, you can visit https://www.tensorflow.org/guide/keras/save_and_serialize .