Checking Input and Output Shapes of a TFLite Model in Python
To check the input and output shapes of a TensorFlow Lite (TFLite) model in Python, you can use the Interpreter class from the tflite_runtime package. Here's how to do it:
Method 1: Using tflite_runtime
import tflite_runtime.interpreter as tflite
# Load the TFLite model
interpreter = tflite.Interpreter(model_path="your_model.tflite")
# Allocate tensors
interpreter.allocate_tensors()
# Get input details
input_details = interpreter.get_input_details()
print("Input details:")
for detail in input_details:
print(f"Name: {detail['name']}")
print(f"Shape: {detail['shape']}")
print(f"Type: {detail['dtype']}")
print("---")
# Get output details
output_details = interpreter.get_output_details()
print("\nOutput details:")
for detail in output_details:
print(f"Name: {detail['name']}")
print(f"Shape: {detail['shape']}")
print(f"Type: {detail['dtype']}")
print("---")
Method 2: Using TensorFlow (if you have it installed)
import tensorflow as tf
# Load the TFLite model
interpreter = tf.lite.Interpreter(model_path="your_model.tflite")
# Allocate tensors
interpreter.allocate_tensors()
# Get input details
input_details = interpreter.get_input_details()
print("Input details:")
for detail in input_details:
print(f"Name: {detail['name']}")
print(f"Shape: {detail['shape']}")
print(f"Type: {detail['dtype']}")
print("---")
# Get output details
output_details = interpreter.get_output_details()
print("\nOutput details:")
for detail in output_details:
print(f"Name: {detail['name']}")
print(f"Shape: {detail['shape']}")
print(f"Type: {detail['dtype']}")
print("---")
Notes:
- The
shape property returns a tuple representing the dimensions of the tensor.
- The
dtype property returns the data type of the tensor (e.g., float32, uint8, etc.).
- If your model has multiple inputs or outputs, the details will be returned as a list.
- Make sure to call
allocate_tensors() before getting the input/output details.
Example Output:
Input details:
Name: input_1
Shape: [1, 224, 224, 3]
Type: <class 'numpy.float32'>
---
Output details:
Name: output_1
Shape: [1, 1000]
Type: <class 'numpy.float32'>
---
This shows that the model expects a 224x224 RGB image as input and produces a 1000-element vector as output.