Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a tflite model in script?

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 ?

like image 641
Harshit Mishra Avatar asked May 21 '18 06:05

Harshit Mishra


People also ask

Can you train Tflite model?

Model Maker allows you to train a TensorFlow Lite model using custom datasets in just a few lines of code. For example, here are the steps to train an image classification model. # Load input data specific to an on-device ML app.


1 Answers

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.

like image 107
Jing Zhao Avatar answered Sep 27 '22 22:09

Jing Zhao