Introduction
Deploying machine learning models on a Raspberry Pi lets you run smart applications locally without needing a big computer or internet connection.
Jump into concepts and practice - no test required
import tensorflow as tf import numpy as np # Load a TensorFlow Lite model interpreter = tf.lite.Interpreter(model_path='model.tflite') interpreter.allocate_tensors() # Get input and output details input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Prepare input data input_data = np.array(your_input_data, dtype=np.float32) # Set the tensor interpreter.set_tensor(input_details[0]['index'], input_data) # Run inference interpreter.invoke() # Get output data output_data = interpreter.get_tensor(output_details[0]['index'])
interpreter = tf.lite.Interpreter(model_path='mobilenet_v2.tflite')
interpreter.allocate_tensors()input_data = np.array(image_data, dtype=np.float32).reshape(1, 224, 224, 3)
interpreter.set_tensor(input_details[0]['index'], input_data) interpreter.invoke() output = interpreter.get_tensor(output_details[0]['index'])
import tensorflow as tf import numpy as np # Load the TFLite model interpreter = tf.lite.Interpreter(model_path='model.tflite') interpreter.allocate_tensors() # Get input and output details input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() # Create dummy input data matching model input shape input_shape = input_details[0]['shape'] input_data = np.array(np.random.random_sample(input_shape), dtype=np.float32) # Set input tensor interpreter.set_tensor(input_details[0]['index'], input_data) # Run inference interpreter.invoke() # Get output tensor output_data = interpreter.get_tensor(output_details[0]['index']) print('Model output:', output_data)
tflite_runtime.tensorflow is large and not optimized for Pi; scikit-learn is for classical ML; opencv-python is for image processing.output_data contain?
import numpy as np from tflite_runtime.interpreter import Interpreter interpreter = Interpreter(model_path='model.tflite') interpreter.allocate_tensors() input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() 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() output_data = interpreter.get_tensor(output_details[0]['index'])
invoke(), then gets output tensor.output_data holdsinvoke(), get_tensor() returns the model's prediction output as a numpy array.ValueError: Cannot set tensor: Dimension mismatch. What is the likely cause?
input_shape = interpreter.get_input_details()[0]['shape'] input_data = np.array([1, 2, 3], dtype=np.float32) interpreter.set_tensor(interpreter.get_input_details()[0]['index'], input_data)
input_shape, but input_data is a 1D array of length 3, likely mismatched.