Running TensorFlow Lite (TFLite) on a Raspberry Pi is an excellent way to deploy efficient, edge-based machine learning models for tasks like object detection, image classification, or audio recognition
import numpy as np
# Use 'import tensorflow as tf' if full TF is installed,
# otherwise use the standalone runtime import:
import tflite_runtime.interpreter as tflite
# 1. Load the TFLite model and allocate tensors
interpreter = tflite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
# 2. Get details about the model's expected inputs and outputs
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# 3. Prepare your dummy input data (must match the model's expected shape and type)
# For example: 1 image, 28x28 pixels, float32 format
input_shape = input_details[0]['shape']
input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)
# 4. Set the input tensor data
interpreter.set_tensor(input_details[0]['index'], input_data)
# 5. Invoke the interpreter to run the math/prediction
interpreter.invoke()
# 6. Retrieve the prediction results
output_data = interpreter.get_tensor(output_details[0]['index'])
print("Inference completed successfully!")
print("Output prediction array shape:", output_data.shape)
print("Raw prediction scores:", output_data)
import tensorflow as tf
# 1. Load your existing trained Keras model
# (Or replace with tf.keras.models.load_model('my_model.h5'))
model = tf.keras.Sequential([
tf.keras.layers.Flatten(input_shape=(28, 28)),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
# 2. Initialize the TFLite Converter
converter = tf.lite.TFLiteConverter.from_keras_model(model)
# 3. Optional: Apply post-training quantization to compress the model size
converter.optimizations = [tf.lite.Optimize.DEFAULT]
# 4. Convert the model
tflite_model = converter.convert()
# 5. Save the optimized .tflite file
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
print("Model successfully converted and saved as 'model.tflite'.")
import numpy as np
import matplotlib.pylab as plt
import matplotlib
#data for plot
import tensorflow as tf
tf.enable_eager_execution()
a=tf.contrib.eager.Varaible(0.)
b = tf.contrib.eager.Variable(1.)
for iteration in range(50)
a.assign(a +b)
b.assign(b *2)
print(a.numpy())
## REFERENCE
tensorflow 2.0
https://www.youtube.com/watch?v=tXVNS-V39A0&t=4s