Search code examples
pythontensorflowtensorflow-lite

Tensorflow Convert pb file to TFLITE using python


I have a model saved after training as pb file, I want to use tensorflow mobile and it's important to work with TFLITE file. The problem is most of the examples I found after googling for converters are command on terminal or cmd. Can you please share with me an example of converting to tflite files using python code?


Solution

  • Following this TF example you can pass "--Saved_model_dir" parameter to export the saved_model.pb and variables folder to some directory (none existing dir) before running retrain.py script:

    python retrain.py ...... --saved_model_dir /home/..../export

    In order to convert your model to tflite you need to use below line:

    convert_saved_model.convert(saved_model_dir='/home/.../export',output_arrays="final_result",output_tflite='/home/.../export/graph.tflite')
    

    Note: you need to import convert_saved_model:

    from tensorflow.contrib.lite.python import convert_saved_model

    Remember you can convert to tflite in 2 ways:

    enter image description here

    But the easiest way is to export saved_model.pb with variables in case you want to avoid using builds tools like Bazel.