Capítulo 8: Aprendizaje Automático en la Nube y Computación en el Borde
Ejercicios Prácticos del Capítulo 8
Ejercicio 1: Convertir un Modelo de TensorFlow a TensorFlow Lite
Tarea: Convierte un modelo preentrenado de TensorFlow (por ejemplo, un modelo simple de clasificación de imágenes) al formato TensorFlow Lite para el despliegue en el borde. Aplica cuantización para reducir el tamaño del modelo.
Solución:
import tensorflow as tf
# Load a pre-trained model (for example, from a saved model directory)
model = tf.keras.models.load_model('my_saved_model')
# Convert the model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_keras_model(model)
# Apply quantization to optimize the model
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('model_quantized.tflite', 'wb') as f:
f.write(tflite_model)
print("Model successfully converted and quantized to TensorFlow Lite format.")
En este ejercicio:
- Cargamos un modelo de TensorFlow y lo convertimos al formato TensorFlow Lite.
- Se aplica cuantización post-entrenamiento para optimizar el modelo, reduciendo su tamaño y mejorando la velocidad de inferencia en dispositivos edge.
Ejercicio 2: Ejecutar un Modelo de TensorFlow Lite en Android
Tarea: Integrar un modelo TensorFlow Lite en una aplicación de Android y realizar inferencia. Supongamos que ya tienes un modelo TFLite listo (model.tflite
), y el objetivo es ejecutar la inferencia en un dispositivo Android.
Solución:
import org.tensorflow.lite.Interpreter;
import android.content.res.AssetManager;
import java.io.FileInputStream;
import java.io.File;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.io.IOException;
public class TFLiteModel {
private Interpreter tflite;
// Load the TensorFlow Lite model from assets
public TFLiteModel(AssetManager assetManager, String modelPath) throws IOException {
ByteBuffer modelBuffer = loadModelFile(assetManager, modelPath);
tflite = new Interpreter(modelBuffer);
}
// Load model into ByteBuffer
private ByteBuffer loadModelFile(AssetManager assetManager, String modelPath) throws IOException {
FileInputStream fis = new FileInputStream(new File(modelPath));
FileChannel fileChannel = fis.getChannel();
long fileSize = fileChannel.size();
ByteBuffer buffer = ByteBuffer.allocateDirect((int) fileSize).order(ByteOrder.nativeOrder());
fileChannel.read(buffer);
buffer.rewind();
return buffer;
}
// Perform inference with input data
public float[] runInference(float[] inputData) {
float[] outputData = new float[10]; // Assuming 10 output classes
tflite.run(inputData, outputData);
return outputData;
}
}
En este ejercicio:
- Cargamos el modelo TensorFlow Lite utilizando el TFLite Interpreter en una aplicación de Android.
- El modelo se usa para realizar inferencia en datos de entrada, como características de imágenes, devolviendo predicciones.
Ejercicio 3: Desplegar un Modelo Usando ONNX Runtime
Tarea: Convertir un modelo de PyTorch al formato ONNX y ejecutar la inferencia utilizando ONNX Runtime en un dispositivo con recursos limitados como un Raspberry Pi.
Solución:
import torch
import torch.nn as nn
import onnx
import onnxruntime as ort
# Define a simple PyTorch model
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(784, 10)
def forward(self, x):
return self.fc(x)
# Create an instance of the model
model = SimpleModel()
# Create a dummy input for model tracing
dummy_input = torch.randn(1, 784)
# Export the model to ONNX format
torch.onnx.export(model, dummy_input, "model.onnx")
print("Model successfully converted to ONNX format.")
# Run inference using ONNX Runtime
ort_session = ort.InferenceSession("model.onnx")
def to_numpy(tensor):
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
# Run inference
input_data = to_numpy(dummy_input)
outputs = ort_session.run(None, {"input": input_data})
print("ONNX Model Inference Output:", outputs)
En este ejercicio:
- Definimos un modelo simple de PyTorch y lo convertimos al formato ONNX utilizando
torch.onnx.export()
. - Se utiliza ONNX Runtime para ejecutar la inferencia en el modelo convertido, haciéndolo adecuado para dispositivos edge como el Raspberry Pi.
Ejercicio 4: Desplegar un Modelo de TensorFlow Lite en Raspberry Pi
Tarea: Desplegar un modelo de TensorFlow Lite en un Raspberry Pi y ejecutar la inferencia en un conjunto de datos de muestra.
Solución:
import numpy as np
import tensorflow as tf
# Load the TensorFlow Lite model
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
# Get input and output tensor details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Prepare a sample input (assuming the model expects a 1D array)
input_data = np.array([[1.0, 2.0, 3.0, 4.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
# Run inference
interpreter.invoke()
# Retrieve the output from the model
output_data = interpreter.get_tensor(output_details[0]['index'])
print(f"Model output: {output_data}")
En este ejercicio:
- Desplegamos un modelo de TensorFlow Lite en un Raspberry Pi utilizando el TFLite Interpreter.
- El modelo realiza inferencia en los datos de entrada, generando predicciones basadas en el modelo entrenado.
Ejercicio 5: Convertir un Modelo de TensorFlow Lite a Core ML
Tarea: Convertir un modelo de TensorFlow Lite al formato Core ML para su despliegue en un dispositivo iOS.
Solución:
import coremltools
import tensorflow as tf
# Load the TensorFlow Lite model
model = tf.keras.models.load_model('my_model.h5')
# Convert the model to Core ML format
coreml_model = coremltools.convert(model)
# Save the Core ML model
coreml_model.save('MyCoreMLModel.mlmodel')
print("Model successfully converted to Core ML format.")
En este ejercicio:
- Convertimos un modelo de TensorFlow Lite al formato Core ML utilizando la biblioteca coremltools.
- El modelo ahora puede desplegarse en una aplicación de iOS usando Core ML.
Estos ejercicios prácticos cubrieron los pasos clave para desplegar modelos de machine learning en dispositivos móviles y de borde utilizando frameworks como TensorFlow Lite, ONNX y Core ML. Al completar estos ejercicios, obtendrás experiencia práctica en la optimización y ejecución de modelos en dispositivos con recursos limitados, haciendo que tus aplicaciones de machine learning sean más versátiles y eficientes.
Ejercicios Prácticos del Capítulo 8
Ejercicio 1: Convertir un Modelo de TensorFlow a TensorFlow Lite
Tarea: Convierte un modelo preentrenado de TensorFlow (por ejemplo, un modelo simple de clasificación de imágenes) al formato TensorFlow Lite para el despliegue en el borde. Aplica cuantización para reducir el tamaño del modelo.
Solución:
import tensorflow as tf
# Load a pre-trained model (for example, from a saved model directory)
model = tf.keras.models.load_model('my_saved_model')
# Convert the model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_keras_model(model)
# Apply quantization to optimize the model
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('model_quantized.tflite', 'wb') as f:
f.write(tflite_model)
print("Model successfully converted and quantized to TensorFlow Lite format.")
En este ejercicio:
- Cargamos un modelo de TensorFlow y lo convertimos al formato TensorFlow Lite.
- Se aplica cuantización post-entrenamiento para optimizar el modelo, reduciendo su tamaño y mejorando la velocidad de inferencia en dispositivos edge.
Ejercicio 2: Ejecutar un Modelo de TensorFlow Lite en Android
Tarea: Integrar un modelo TensorFlow Lite en una aplicación de Android y realizar inferencia. Supongamos que ya tienes un modelo TFLite listo (model.tflite
), y el objetivo es ejecutar la inferencia en un dispositivo Android.
Solución:
import org.tensorflow.lite.Interpreter;
import android.content.res.AssetManager;
import java.io.FileInputStream;
import java.io.File;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.io.IOException;
public class TFLiteModel {
private Interpreter tflite;
// Load the TensorFlow Lite model from assets
public TFLiteModel(AssetManager assetManager, String modelPath) throws IOException {
ByteBuffer modelBuffer = loadModelFile(assetManager, modelPath);
tflite = new Interpreter(modelBuffer);
}
// Load model into ByteBuffer
private ByteBuffer loadModelFile(AssetManager assetManager, String modelPath) throws IOException {
FileInputStream fis = new FileInputStream(new File(modelPath));
FileChannel fileChannel = fis.getChannel();
long fileSize = fileChannel.size();
ByteBuffer buffer = ByteBuffer.allocateDirect((int) fileSize).order(ByteOrder.nativeOrder());
fileChannel.read(buffer);
buffer.rewind();
return buffer;
}
// Perform inference with input data
public float[] runInference(float[] inputData) {
float[] outputData = new float[10]; // Assuming 10 output classes
tflite.run(inputData, outputData);
return outputData;
}
}
En este ejercicio:
- Cargamos el modelo TensorFlow Lite utilizando el TFLite Interpreter en una aplicación de Android.
- El modelo se usa para realizar inferencia en datos de entrada, como características de imágenes, devolviendo predicciones.
Ejercicio 3: Desplegar un Modelo Usando ONNX Runtime
Tarea: Convertir un modelo de PyTorch al formato ONNX y ejecutar la inferencia utilizando ONNX Runtime en un dispositivo con recursos limitados como un Raspberry Pi.
Solución:
import torch
import torch.nn as nn
import onnx
import onnxruntime as ort
# Define a simple PyTorch model
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(784, 10)
def forward(self, x):
return self.fc(x)
# Create an instance of the model
model = SimpleModel()
# Create a dummy input for model tracing
dummy_input = torch.randn(1, 784)
# Export the model to ONNX format
torch.onnx.export(model, dummy_input, "model.onnx")
print("Model successfully converted to ONNX format.")
# Run inference using ONNX Runtime
ort_session = ort.InferenceSession("model.onnx")
def to_numpy(tensor):
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
# Run inference
input_data = to_numpy(dummy_input)
outputs = ort_session.run(None, {"input": input_data})
print("ONNX Model Inference Output:", outputs)
En este ejercicio:
- Definimos un modelo simple de PyTorch y lo convertimos al formato ONNX utilizando
torch.onnx.export()
. - Se utiliza ONNX Runtime para ejecutar la inferencia en el modelo convertido, haciéndolo adecuado para dispositivos edge como el Raspberry Pi.
Ejercicio 4: Desplegar un Modelo de TensorFlow Lite en Raspberry Pi
Tarea: Desplegar un modelo de TensorFlow Lite en un Raspberry Pi y ejecutar la inferencia en un conjunto de datos de muestra.
Solución:
import numpy as np
import tensorflow as tf
# Load the TensorFlow Lite model
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
# Get input and output tensor details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Prepare a sample input (assuming the model expects a 1D array)
input_data = np.array([[1.0, 2.0, 3.0, 4.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
# Run inference
interpreter.invoke()
# Retrieve the output from the model
output_data = interpreter.get_tensor(output_details[0]['index'])
print(f"Model output: {output_data}")
En este ejercicio:
- Desplegamos un modelo de TensorFlow Lite en un Raspberry Pi utilizando el TFLite Interpreter.
- El modelo realiza inferencia en los datos de entrada, generando predicciones basadas en el modelo entrenado.
Ejercicio 5: Convertir un Modelo de TensorFlow Lite a Core ML
Tarea: Convertir un modelo de TensorFlow Lite al formato Core ML para su despliegue en un dispositivo iOS.
Solución:
import coremltools
import tensorflow as tf
# Load the TensorFlow Lite model
model = tf.keras.models.load_model('my_model.h5')
# Convert the model to Core ML format
coreml_model = coremltools.convert(model)
# Save the Core ML model
coreml_model.save('MyCoreMLModel.mlmodel')
print("Model successfully converted to Core ML format.")
En este ejercicio:
- Convertimos un modelo de TensorFlow Lite al formato Core ML utilizando la biblioteca coremltools.
- El modelo ahora puede desplegarse en una aplicación de iOS usando Core ML.
Estos ejercicios prácticos cubrieron los pasos clave para desplegar modelos de machine learning en dispositivos móviles y de borde utilizando frameworks como TensorFlow Lite, ONNX y Core ML. Al completar estos ejercicios, obtendrás experiencia práctica en la optimización y ejecución de modelos en dispositivos con recursos limitados, haciendo que tus aplicaciones de machine learning sean más versátiles y eficientes.
Ejercicios Prácticos del Capítulo 8
Ejercicio 1: Convertir un Modelo de TensorFlow a TensorFlow Lite
Tarea: Convierte un modelo preentrenado de TensorFlow (por ejemplo, un modelo simple de clasificación de imágenes) al formato TensorFlow Lite para el despliegue en el borde. Aplica cuantización para reducir el tamaño del modelo.
Solución:
import tensorflow as tf
# Load a pre-trained model (for example, from a saved model directory)
model = tf.keras.models.load_model('my_saved_model')
# Convert the model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_keras_model(model)
# Apply quantization to optimize the model
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('model_quantized.tflite', 'wb') as f:
f.write(tflite_model)
print("Model successfully converted and quantized to TensorFlow Lite format.")
En este ejercicio:
- Cargamos un modelo de TensorFlow y lo convertimos al formato TensorFlow Lite.
- Se aplica cuantización post-entrenamiento para optimizar el modelo, reduciendo su tamaño y mejorando la velocidad de inferencia en dispositivos edge.
Ejercicio 2: Ejecutar un Modelo de TensorFlow Lite en Android
Tarea: Integrar un modelo TensorFlow Lite en una aplicación de Android y realizar inferencia. Supongamos que ya tienes un modelo TFLite listo (model.tflite
), y el objetivo es ejecutar la inferencia en un dispositivo Android.
Solución:
import org.tensorflow.lite.Interpreter;
import android.content.res.AssetManager;
import java.io.FileInputStream;
import java.io.File;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.io.IOException;
public class TFLiteModel {
private Interpreter tflite;
// Load the TensorFlow Lite model from assets
public TFLiteModel(AssetManager assetManager, String modelPath) throws IOException {
ByteBuffer modelBuffer = loadModelFile(assetManager, modelPath);
tflite = new Interpreter(modelBuffer);
}
// Load model into ByteBuffer
private ByteBuffer loadModelFile(AssetManager assetManager, String modelPath) throws IOException {
FileInputStream fis = new FileInputStream(new File(modelPath));
FileChannel fileChannel = fis.getChannel();
long fileSize = fileChannel.size();
ByteBuffer buffer = ByteBuffer.allocateDirect((int) fileSize).order(ByteOrder.nativeOrder());
fileChannel.read(buffer);
buffer.rewind();
return buffer;
}
// Perform inference with input data
public float[] runInference(float[] inputData) {
float[] outputData = new float[10]; // Assuming 10 output classes
tflite.run(inputData, outputData);
return outputData;
}
}
En este ejercicio:
- Cargamos el modelo TensorFlow Lite utilizando el TFLite Interpreter en una aplicación de Android.
- El modelo se usa para realizar inferencia en datos de entrada, como características de imágenes, devolviendo predicciones.
Ejercicio 3: Desplegar un Modelo Usando ONNX Runtime
Tarea: Convertir un modelo de PyTorch al formato ONNX y ejecutar la inferencia utilizando ONNX Runtime en un dispositivo con recursos limitados como un Raspberry Pi.
Solución:
import torch
import torch.nn as nn
import onnx
import onnxruntime as ort
# Define a simple PyTorch model
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(784, 10)
def forward(self, x):
return self.fc(x)
# Create an instance of the model
model = SimpleModel()
# Create a dummy input for model tracing
dummy_input = torch.randn(1, 784)
# Export the model to ONNX format
torch.onnx.export(model, dummy_input, "model.onnx")
print("Model successfully converted to ONNX format.")
# Run inference using ONNX Runtime
ort_session = ort.InferenceSession("model.onnx")
def to_numpy(tensor):
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
# Run inference
input_data = to_numpy(dummy_input)
outputs = ort_session.run(None, {"input": input_data})
print("ONNX Model Inference Output:", outputs)
En este ejercicio:
- Definimos un modelo simple de PyTorch y lo convertimos al formato ONNX utilizando
torch.onnx.export()
. - Se utiliza ONNX Runtime para ejecutar la inferencia en el modelo convertido, haciéndolo adecuado para dispositivos edge como el Raspberry Pi.
Ejercicio 4: Desplegar un Modelo de TensorFlow Lite en Raspberry Pi
Tarea: Desplegar un modelo de TensorFlow Lite en un Raspberry Pi y ejecutar la inferencia en un conjunto de datos de muestra.
Solución:
import numpy as np
import tensorflow as tf
# Load the TensorFlow Lite model
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
# Get input and output tensor details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Prepare a sample input (assuming the model expects a 1D array)
input_data = np.array([[1.0, 2.0, 3.0, 4.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
# Run inference
interpreter.invoke()
# Retrieve the output from the model
output_data = interpreter.get_tensor(output_details[0]['index'])
print(f"Model output: {output_data}")
En este ejercicio:
- Desplegamos un modelo de TensorFlow Lite en un Raspberry Pi utilizando el TFLite Interpreter.
- El modelo realiza inferencia en los datos de entrada, generando predicciones basadas en el modelo entrenado.
Ejercicio 5: Convertir un Modelo de TensorFlow Lite a Core ML
Tarea: Convertir un modelo de TensorFlow Lite al formato Core ML para su despliegue en un dispositivo iOS.
Solución:
import coremltools
import tensorflow as tf
# Load the TensorFlow Lite model
model = tf.keras.models.load_model('my_model.h5')
# Convert the model to Core ML format
coreml_model = coremltools.convert(model)
# Save the Core ML model
coreml_model.save('MyCoreMLModel.mlmodel')
print("Model successfully converted to Core ML format.")
En este ejercicio:
- Convertimos un modelo de TensorFlow Lite al formato Core ML utilizando la biblioteca coremltools.
- El modelo ahora puede desplegarse en una aplicación de iOS usando Core ML.
Estos ejercicios prácticos cubrieron los pasos clave para desplegar modelos de machine learning en dispositivos móviles y de borde utilizando frameworks como TensorFlow Lite, ONNX y Core ML. Al completar estos ejercicios, obtendrás experiencia práctica en la optimización y ejecución de modelos en dispositivos con recursos limitados, haciendo que tus aplicaciones de machine learning sean más versátiles y eficientes.
Ejercicios Prácticos del Capítulo 8
Ejercicio 1: Convertir un Modelo de TensorFlow a TensorFlow Lite
Tarea: Convierte un modelo preentrenado de TensorFlow (por ejemplo, un modelo simple de clasificación de imágenes) al formato TensorFlow Lite para el despliegue en el borde. Aplica cuantización para reducir el tamaño del modelo.
Solución:
import tensorflow as tf
# Load a pre-trained model (for example, from a saved model directory)
model = tf.keras.models.load_model('my_saved_model')
# Convert the model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_keras_model(model)
# Apply quantization to optimize the model
converter.optimizations = [tf.lite.Optimize.DEFAULT]
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('model_quantized.tflite', 'wb') as f:
f.write(tflite_model)
print("Model successfully converted and quantized to TensorFlow Lite format.")
En este ejercicio:
- Cargamos un modelo de TensorFlow y lo convertimos al formato TensorFlow Lite.
- Se aplica cuantización post-entrenamiento para optimizar el modelo, reduciendo su tamaño y mejorando la velocidad de inferencia en dispositivos edge.
Ejercicio 2: Ejecutar un Modelo de TensorFlow Lite en Android
Tarea: Integrar un modelo TensorFlow Lite en una aplicación de Android y realizar inferencia. Supongamos que ya tienes un modelo TFLite listo (model.tflite
), y el objetivo es ejecutar la inferencia en un dispositivo Android.
Solución:
import org.tensorflow.lite.Interpreter;
import android.content.res.AssetManager;
import java.io.FileInputStream;
import java.io.File;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.io.IOException;
public class TFLiteModel {
private Interpreter tflite;
// Load the TensorFlow Lite model from assets
public TFLiteModel(AssetManager assetManager, String modelPath) throws IOException {
ByteBuffer modelBuffer = loadModelFile(assetManager, modelPath);
tflite = new Interpreter(modelBuffer);
}
// Load model into ByteBuffer
private ByteBuffer loadModelFile(AssetManager assetManager, String modelPath) throws IOException {
FileInputStream fis = new FileInputStream(new File(modelPath));
FileChannel fileChannel = fis.getChannel();
long fileSize = fileChannel.size();
ByteBuffer buffer = ByteBuffer.allocateDirect((int) fileSize).order(ByteOrder.nativeOrder());
fileChannel.read(buffer);
buffer.rewind();
return buffer;
}
// Perform inference with input data
public float[] runInference(float[] inputData) {
float[] outputData = new float[10]; // Assuming 10 output classes
tflite.run(inputData, outputData);
return outputData;
}
}
En este ejercicio:
- Cargamos el modelo TensorFlow Lite utilizando el TFLite Interpreter en una aplicación de Android.
- El modelo se usa para realizar inferencia en datos de entrada, como características de imágenes, devolviendo predicciones.
Ejercicio 3: Desplegar un Modelo Usando ONNX Runtime
Tarea: Convertir un modelo de PyTorch al formato ONNX y ejecutar la inferencia utilizando ONNX Runtime en un dispositivo con recursos limitados como un Raspberry Pi.
Solución:
import torch
import torch.nn as nn
import onnx
import onnxruntime as ort
# Define a simple PyTorch model
class SimpleModel(nn.Module):
def __init__(self):
super(SimpleModel, self).__init__()
self.fc = nn.Linear(784, 10)
def forward(self, x):
return self.fc(x)
# Create an instance of the model
model = SimpleModel()
# Create a dummy input for model tracing
dummy_input = torch.randn(1, 784)
# Export the model to ONNX format
torch.onnx.export(model, dummy_input, "model.onnx")
print("Model successfully converted to ONNX format.")
# Run inference using ONNX Runtime
ort_session = ort.InferenceSession("model.onnx")
def to_numpy(tensor):
return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()
# Run inference
input_data = to_numpy(dummy_input)
outputs = ort_session.run(None, {"input": input_data})
print("ONNX Model Inference Output:", outputs)
En este ejercicio:
- Definimos un modelo simple de PyTorch y lo convertimos al formato ONNX utilizando
torch.onnx.export()
. - Se utiliza ONNX Runtime para ejecutar la inferencia en el modelo convertido, haciéndolo adecuado para dispositivos edge como el Raspberry Pi.
Ejercicio 4: Desplegar un Modelo de TensorFlow Lite en Raspberry Pi
Tarea: Desplegar un modelo de TensorFlow Lite en un Raspberry Pi y ejecutar la inferencia en un conjunto de datos de muestra.
Solución:
import numpy as np
import tensorflow as tf
# Load the TensorFlow Lite model
interpreter = tf.lite.Interpreter(model_path="model.tflite")
interpreter.allocate_tensors()
# Get input and output tensor details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
# Prepare a sample input (assuming the model expects a 1D array)
input_data = np.array([[1.0, 2.0, 3.0, 4.0]], dtype=np.float32)
interpreter.set_tensor(input_details[0]['index'], input_data)
# Run inference
interpreter.invoke()
# Retrieve the output from the model
output_data = interpreter.get_tensor(output_details[0]['index'])
print(f"Model output: {output_data}")
En este ejercicio:
- Desplegamos un modelo de TensorFlow Lite en un Raspberry Pi utilizando el TFLite Interpreter.
- El modelo realiza inferencia en los datos de entrada, generando predicciones basadas en el modelo entrenado.
Ejercicio 5: Convertir un Modelo de TensorFlow Lite a Core ML
Tarea: Convertir un modelo de TensorFlow Lite al formato Core ML para su despliegue en un dispositivo iOS.
Solución:
import coremltools
import tensorflow as tf
# Load the TensorFlow Lite model
model = tf.keras.models.load_model('my_model.h5')
# Convert the model to Core ML format
coreml_model = coremltools.convert(model)
# Save the Core ML model
coreml_model.save('MyCoreMLModel.mlmodel')
print("Model successfully converted to Core ML format.")
En este ejercicio:
- Convertimos un modelo de TensorFlow Lite al formato Core ML utilizando la biblioteca coremltools.
- El modelo ahora puede desplegarse en una aplicación de iOS usando Core ML.
Estos ejercicios prácticos cubrieron los pasos clave para desplegar modelos de machine learning en dispositivos móviles y de borde utilizando frameworks como TensorFlow Lite, ONNX y Core ML. Al completar estos ejercicios, obtendrás experiencia práctica en la optimización y ejecución de modelos en dispositivos con recursos limitados, haciendo que tus aplicaciones de machine learning sean más versátiles y eficientes.