How to load a tflite model in script?

Harshit Mishra picture Harshit Mishra · May 21, 2018 · Viewed 17.1k times · Source

I have converted the .pb file to tflite file using the bazel. Now I want to load this tflite model in my python script just to test that weather this is giving me correct output or not ?

Answer

Jing Zhao picture Jing Zhao · Aug 23, 2018

You can use TensorFlow Lite Python interpreter to load the tflite model in a python shell, and test it with your input data.

The code will be like this:

import numpy as np
import tensorflow as tf

# Load TFLite model and allocate tensors.
interpreter = tf.lite.Interpreter(model_path="converted_model.tflite")
interpreter.allocate_tensors()

# Get input and output tensors.
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()

# Test model on random input data.
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)

interpreter.invoke()

# The function `get_tensor()` returns a copy of the tensor data.
# Use `tensor()` in order to get a pointer to the tensor.
output_data = interpreter.get_tensor(output_details[0]['index'])
print(output_data)

The above code is from TensorFlow Lite official guide, for more detailed information, read this.