Capítulo 3: Aprendizaje profundo con Keras
Ejercicios prácticos Capítulo 3
Ejercicio 1: Guardar y cargar un modelo Keras
Tarea: Entrenar una red neuronal simple en el conjunto de datos MNIST, guardar el modelo utilizando el formato SavedModel y luego cargar el modelo guardado para hacer predicciones en el conjunto de prueba.
Solución:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.datasets import mnist
# Load the MNIST dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Normalize the data
X_train, X_test = X_train / 255.0, X_test / 255.0
# Define a simple Sequential model
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=5)
# Save the model in SavedModel format
model.save('saved_model')
# Load the saved model
loaded_model = tf.keras.models.load_model('saved_model')
# Use the loaded model to make predictions
predictions = loaded_model.predict(X_test)
print(f"Predictions for the first test sample: {predictions[0]}")
Ejercicio 2: Desplegar un modelo Keras con TensorFlow Serving
Tarea: Entrenar una red neuronal, guardarla en el formato SavedModel y preparar el modelo para su despliegue utilizando TensorFlow Serving. Escribe un script del lado del cliente que envíe una solicitud a la API del modelo para obtener predicciones.
Solución:
Paso 1: Guardar el modelo para TensorFlow Serving.
# Save the model in SavedModel format for TensorFlow Serving
model.save('serving_model/keras_served_model')
Paso 2: Ejecutar TensorFlow Serving utilizando Docker.
docker pull tensorflow/serving
docker run -p 8501:8501 --name tf_serving \\
--mount type=bind,source=$(pwd)/serving_model/keras_served_model,target=/models/keras_served_model \\
-e MODEL_NAME=keras_served_model -t tensorflow/serving
Paso 3: Enviar una solicitud a TensorFlow Serving.
import requests
import json
import numpy as np
# Prepare input data
input_data = np.expand_dims(X_test[0], axis=0).tolist()
# Define the API URL for TensorFlow Serving
url = '<http://localhost:8501/v1/models/keras_served_model:predict>'
# Send a POST request to TensorFlow Serving
response = requests.post(url, json={"instances": input_data})
# Parse the response
predictions = response.json()['predictions']
print(f"Predictions: {predictions}")
Ejercicio 3: Desplegar un modelo Keras con Flask
Tarea: Crear una aplicación web en Flask que cargue un modelo Keras entrenado y lo sirva a través de una API para realizar predicciones. Escribe un script del lado del cliente para enviar una solicitud a la aplicación Flask.
Solución:
Paso 1: Crear la aplicación Flask.
from flask import Flask, request, jsonify
from tensorflow.keras.models import load_model
import numpy as np
# Initialize the Flask app
app = Flask(__name__)
# Load the trained Keras model
model = load_model('saved_model')
# Define an API route for predictions
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json(force=True)
input_data = np.array(data['instances'])
predictions = model.predict(input_data)
return jsonify(predictions=predictions.tolist())
# Run the Flask app
if __name__ == '__main__':
app.run(port=5000, debug=True)
Paso 2: Script del lado del cliente para enviar una solicitud a la aplicación Flask.
import requests
import json
import numpy as np
# Prepare input data
input_data = np.expand_dims(X_test[0], axis=0).tolist()
# Define the Flask API URL
url = '<http://localhost:5000/predict>'
# Send a POST request to the Flask API
response = requests.post(url, json={"instances": input_data})
# Parse the response
predictions = response.json()['predictions']
print(f"Predictions: {predictions}")
Ejercicio 4: Convertir un modelo Keras a TensorFlow Lite
Tarea: Convertir un modelo Keras entrenado al formato TensorFlow Lite y guardarlo. Utiliza el intérprete de TensorFlow Lite para ejecutar inferencias en el conjunto de datos de prueba.
Solución:
Paso 1: Convertir el modelo a TensorFlow Lite.
# Convert the Keras model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
Paso 2: Cargar y ejecutar el modelo con TensorFlow Lite.
import tensorflow as tf
import numpy as np
# Load and preprocess the MNIST dataset
_, (X_test, _) = tf.keras.datasets.mnist.load_data()
X_test = X_test.astype(np.float32) / 255.0
X_test = X_test.reshape((X_test.shape[0], 28, 28, 1)) # Ensure the correct input shape
# Load the 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 (e.g., first test sample)
test_sample = np.expand_dims(X_test[0], axis=0).astype(np.float32)
# Set the input tensor
interpreter.set_tensor(input_details[0]['index'], test_sample)
# Run the model
interpreter.invoke()
# Get the output tensor (predictions)
output_data = interpreter.get_tensor(output_details[0]['index'])
print(f"TensorFlow Lite model predictions: {output_data}")
Ejercicio 5: Usar Model Checkpointing y Early Stopping
Tarea: Entrenar un modelo Keras con model checkpointing y early stopping para guardar el modelo con mejor rendimiento y detener el entrenamiento cuando el rendimiento deje de mejorar.
Solución:
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
# Define the ModelCheckpoint and EarlyStopping callbacks
checkpoint_callback = ModelCheckpoint(filepath='best_model.h5', save_best_only=True, monitor='val_accuracy', mode='max', verbose=1)
early_stopping_callback = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True, verbose=1)
# Train the model with both callbacks
model.fit(X_train, y_train, epochs=20, validation_data=(X_test, y_test), callbacks=[checkpoint_callback, early_stopping_callback])
En esta solución:
- ModelCheckpoint guarda el mejor modelo basado en la precisión de validación.
- EarlyStopping detiene el entrenamiento cuando la pérdida de validación deja de mejorar durante 3 épocas consecutivas.
Estos ejercicios refuerzan los conceptos clave del Capítulo 3, incluyendo guardar y cargar modelos Keras, desplegarlos en entornos de producción utilizando TensorFlow Serving y Flask, convertir modelos a TensorFlow Lite para aplicaciones móviles, y utilizar model checkpointing y early stopping para entrenamientos eficientes. Estas tareas son esenciales para llevar los modelos desde la investigación hasta su uso en el mundo real.
Ejercicios prácticos Capítulo 3
Ejercicio 1: Guardar y cargar un modelo Keras
Tarea: Entrenar una red neuronal simple en el conjunto de datos MNIST, guardar el modelo utilizando el formato SavedModel y luego cargar el modelo guardado para hacer predicciones en el conjunto de prueba.
Solución:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.datasets import mnist
# Load the MNIST dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Normalize the data
X_train, X_test = X_train / 255.0, X_test / 255.0
# Define a simple Sequential model
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=5)
# Save the model in SavedModel format
model.save('saved_model')
# Load the saved model
loaded_model = tf.keras.models.load_model('saved_model')
# Use the loaded model to make predictions
predictions = loaded_model.predict(X_test)
print(f"Predictions for the first test sample: {predictions[0]}")
Ejercicio 2: Desplegar un modelo Keras con TensorFlow Serving
Tarea: Entrenar una red neuronal, guardarla en el formato SavedModel y preparar el modelo para su despliegue utilizando TensorFlow Serving. Escribe un script del lado del cliente que envíe una solicitud a la API del modelo para obtener predicciones.
Solución:
Paso 1: Guardar el modelo para TensorFlow Serving.
# Save the model in SavedModel format for TensorFlow Serving
model.save('serving_model/keras_served_model')
Paso 2: Ejecutar TensorFlow Serving utilizando Docker.
docker pull tensorflow/serving
docker run -p 8501:8501 --name tf_serving \\
--mount type=bind,source=$(pwd)/serving_model/keras_served_model,target=/models/keras_served_model \\
-e MODEL_NAME=keras_served_model -t tensorflow/serving
Paso 3: Enviar una solicitud a TensorFlow Serving.
import requests
import json
import numpy as np
# Prepare input data
input_data = np.expand_dims(X_test[0], axis=0).tolist()
# Define the API URL for TensorFlow Serving
url = '<http://localhost:8501/v1/models/keras_served_model:predict>'
# Send a POST request to TensorFlow Serving
response = requests.post(url, json={"instances": input_data})
# Parse the response
predictions = response.json()['predictions']
print(f"Predictions: {predictions}")
Ejercicio 3: Desplegar un modelo Keras con Flask
Tarea: Crear una aplicación web en Flask que cargue un modelo Keras entrenado y lo sirva a través de una API para realizar predicciones. Escribe un script del lado del cliente para enviar una solicitud a la aplicación Flask.
Solución:
Paso 1: Crear la aplicación Flask.
from flask import Flask, request, jsonify
from tensorflow.keras.models import load_model
import numpy as np
# Initialize the Flask app
app = Flask(__name__)
# Load the trained Keras model
model = load_model('saved_model')
# Define an API route for predictions
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json(force=True)
input_data = np.array(data['instances'])
predictions = model.predict(input_data)
return jsonify(predictions=predictions.tolist())
# Run the Flask app
if __name__ == '__main__':
app.run(port=5000, debug=True)
Paso 2: Script del lado del cliente para enviar una solicitud a la aplicación Flask.
import requests
import json
import numpy as np
# Prepare input data
input_data = np.expand_dims(X_test[0], axis=0).tolist()
# Define the Flask API URL
url = '<http://localhost:5000/predict>'
# Send a POST request to the Flask API
response = requests.post(url, json={"instances": input_data})
# Parse the response
predictions = response.json()['predictions']
print(f"Predictions: {predictions}")
Ejercicio 4: Convertir un modelo Keras a TensorFlow Lite
Tarea: Convertir un modelo Keras entrenado al formato TensorFlow Lite y guardarlo. Utiliza el intérprete de TensorFlow Lite para ejecutar inferencias en el conjunto de datos de prueba.
Solución:
Paso 1: Convertir el modelo a TensorFlow Lite.
# Convert the Keras model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
Paso 2: Cargar y ejecutar el modelo con TensorFlow Lite.
import tensorflow as tf
import numpy as np
# Load and preprocess the MNIST dataset
_, (X_test, _) = tf.keras.datasets.mnist.load_data()
X_test = X_test.astype(np.float32) / 255.0
X_test = X_test.reshape((X_test.shape[0], 28, 28, 1)) # Ensure the correct input shape
# Load the 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 (e.g., first test sample)
test_sample = np.expand_dims(X_test[0], axis=0).astype(np.float32)
# Set the input tensor
interpreter.set_tensor(input_details[0]['index'], test_sample)
# Run the model
interpreter.invoke()
# Get the output tensor (predictions)
output_data = interpreter.get_tensor(output_details[0]['index'])
print(f"TensorFlow Lite model predictions: {output_data}")
Ejercicio 5: Usar Model Checkpointing y Early Stopping
Tarea: Entrenar un modelo Keras con model checkpointing y early stopping para guardar el modelo con mejor rendimiento y detener el entrenamiento cuando el rendimiento deje de mejorar.
Solución:
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
# Define the ModelCheckpoint and EarlyStopping callbacks
checkpoint_callback = ModelCheckpoint(filepath='best_model.h5', save_best_only=True, monitor='val_accuracy', mode='max', verbose=1)
early_stopping_callback = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True, verbose=1)
# Train the model with both callbacks
model.fit(X_train, y_train, epochs=20, validation_data=(X_test, y_test), callbacks=[checkpoint_callback, early_stopping_callback])
En esta solución:
- ModelCheckpoint guarda el mejor modelo basado en la precisión de validación.
- EarlyStopping detiene el entrenamiento cuando la pérdida de validación deja de mejorar durante 3 épocas consecutivas.
Estos ejercicios refuerzan los conceptos clave del Capítulo 3, incluyendo guardar y cargar modelos Keras, desplegarlos en entornos de producción utilizando TensorFlow Serving y Flask, convertir modelos a TensorFlow Lite para aplicaciones móviles, y utilizar model checkpointing y early stopping para entrenamientos eficientes. Estas tareas son esenciales para llevar los modelos desde la investigación hasta su uso en el mundo real.
Ejercicios prácticos Capítulo 3
Ejercicio 1: Guardar y cargar un modelo Keras
Tarea: Entrenar una red neuronal simple en el conjunto de datos MNIST, guardar el modelo utilizando el formato SavedModel y luego cargar el modelo guardado para hacer predicciones en el conjunto de prueba.
Solución:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.datasets import mnist
# Load the MNIST dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Normalize the data
X_train, X_test = X_train / 255.0, X_test / 255.0
# Define a simple Sequential model
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=5)
# Save the model in SavedModel format
model.save('saved_model')
# Load the saved model
loaded_model = tf.keras.models.load_model('saved_model')
# Use the loaded model to make predictions
predictions = loaded_model.predict(X_test)
print(f"Predictions for the first test sample: {predictions[0]}")
Ejercicio 2: Desplegar un modelo Keras con TensorFlow Serving
Tarea: Entrenar una red neuronal, guardarla en el formato SavedModel y preparar el modelo para su despliegue utilizando TensorFlow Serving. Escribe un script del lado del cliente que envíe una solicitud a la API del modelo para obtener predicciones.
Solución:
Paso 1: Guardar el modelo para TensorFlow Serving.
# Save the model in SavedModel format for TensorFlow Serving
model.save('serving_model/keras_served_model')
Paso 2: Ejecutar TensorFlow Serving utilizando Docker.
docker pull tensorflow/serving
docker run -p 8501:8501 --name tf_serving \\
--mount type=bind,source=$(pwd)/serving_model/keras_served_model,target=/models/keras_served_model \\
-e MODEL_NAME=keras_served_model -t tensorflow/serving
Paso 3: Enviar una solicitud a TensorFlow Serving.
import requests
import json
import numpy as np
# Prepare input data
input_data = np.expand_dims(X_test[0], axis=0).tolist()
# Define the API URL for TensorFlow Serving
url = '<http://localhost:8501/v1/models/keras_served_model:predict>'
# Send a POST request to TensorFlow Serving
response = requests.post(url, json={"instances": input_data})
# Parse the response
predictions = response.json()['predictions']
print(f"Predictions: {predictions}")
Ejercicio 3: Desplegar un modelo Keras con Flask
Tarea: Crear una aplicación web en Flask que cargue un modelo Keras entrenado y lo sirva a través de una API para realizar predicciones. Escribe un script del lado del cliente para enviar una solicitud a la aplicación Flask.
Solución:
Paso 1: Crear la aplicación Flask.
from flask import Flask, request, jsonify
from tensorflow.keras.models import load_model
import numpy as np
# Initialize the Flask app
app = Flask(__name__)
# Load the trained Keras model
model = load_model('saved_model')
# Define an API route for predictions
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json(force=True)
input_data = np.array(data['instances'])
predictions = model.predict(input_data)
return jsonify(predictions=predictions.tolist())
# Run the Flask app
if __name__ == '__main__':
app.run(port=5000, debug=True)
Paso 2: Script del lado del cliente para enviar una solicitud a la aplicación Flask.
import requests
import json
import numpy as np
# Prepare input data
input_data = np.expand_dims(X_test[0], axis=0).tolist()
# Define the Flask API URL
url = '<http://localhost:5000/predict>'
# Send a POST request to the Flask API
response = requests.post(url, json={"instances": input_data})
# Parse the response
predictions = response.json()['predictions']
print(f"Predictions: {predictions}")
Ejercicio 4: Convertir un modelo Keras a TensorFlow Lite
Tarea: Convertir un modelo Keras entrenado al formato TensorFlow Lite y guardarlo. Utiliza el intérprete de TensorFlow Lite para ejecutar inferencias en el conjunto de datos de prueba.
Solución:
Paso 1: Convertir el modelo a TensorFlow Lite.
# Convert the Keras model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
Paso 2: Cargar y ejecutar el modelo con TensorFlow Lite.
import tensorflow as tf
import numpy as np
# Load and preprocess the MNIST dataset
_, (X_test, _) = tf.keras.datasets.mnist.load_data()
X_test = X_test.astype(np.float32) / 255.0
X_test = X_test.reshape((X_test.shape[0], 28, 28, 1)) # Ensure the correct input shape
# Load the 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 (e.g., first test sample)
test_sample = np.expand_dims(X_test[0], axis=0).astype(np.float32)
# Set the input tensor
interpreter.set_tensor(input_details[0]['index'], test_sample)
# Run the model
interpreter.invoke()
# Get the output tensor (predictions)
output_data = interpreter.get_tensor(output_details[0]['index'])
print(f"TensorFlow Lite model predictions: {output_data}")
Ejercicio 5: Usar Model Checkpointing y Early Stopping
Tarea: Entrenar un modelo Keras con model checkpointing y early stopping para guardar el modelo con mejor rendimiento y detener el entrenamiento cuando el rendimiento deje de mejorar.
Solución:
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
# Define the ModelCheckpoint and EarlyStopping callbacks
checkpoint_callback = ModelCheckpoint(filepath='best_model.h5', save_best_only=True, monitor='val_accuracy', mode='max', verbose=1)
early_stopping_callback = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True, verbose=1)
# Train the model with both callbacks
model.fit(X_train, y_train, epochs=20, validation_data=(X_test, y_test), callbacks=[checkpoint_callback, early_stopping_callback])
En esta solución:
- ModelCheckpoint guarda el mejor modelo basado en la precisión de validación.
- EarlyStopping detiene el entrenamiento cuando la pérdida de validación deja de mejorar durante 3 épocas consecutivas.
Estos ejercicios refuerzan los conceptos clave del Capítulo 3, incluyendo guardar y cargar modelos Keras, desplegarlos en entornos de producción utilizando TensorFlow Serving y Flask, convertir modelos a TensorFlow Lite para aplicaciones móviles, y utilizar model checkpointing y early stopping para entrenamientos eficientes. Estas tareas son esenciales para llevar los modelos desde la investigación hasta su uso en el mundo real.
Ejercicios prácticos Capítulo 3
Ejercicio 1: Guardar y cargar un modelo Keras
Tarea: Entrenar una red neuronal simple en el conjunto de datos MNIST, guardar el modelo utilizando el formato SavedModel y luego cargar el modelo guardado para hacer predicciones en el conjunto de prueba.
Solución:
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.datasets import mnist
# Load the MNIST dataset
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# Normalize the data
X_train, X_test = X_train / 255.0, X_test / 255.0
# Define a simple Sequential model
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(64, activation='relu'),
Dense(10, activation='softmax')
])
# Compile the model
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
# Train the model
model.fit(X_train, y_train, epochs=5)
# Save the model in SavedModel format
model.save('saved_model')
# Load the saved model
loaded_model = tf.keras.models.load_model('saved_model')
# Use the loaded model to make predictions
predictions = loaded_model.predict(X_test)
print(f"Predictions for the first test sample: {predictions[0]}")
Ejercicio 2: Desplegar un modelo Keras con TensorFlow Serving
Tarea: Entrenar una red neuronal, guardarla en el formato SavedModel y preparar el modelo para su despliegue utilizando TensorFlow Serving. Escribe un script del lado del cliente que envíe una solicitud a la API del modelo para obtener predicciones.
Solución:
Paso 1: Guardar el modelo para TensorFlow Serving.
# Save the model in SavedModel format for TensorFlow Serving
model.save('serving_model/keras_served_model')
Paso 2: Ejecutar TensorFlow Serving utilizando Docker.
docker pull tensorflow/serving
docker run -p 8501:8501 --name tf_serving \\
--mount type=bind,source=$(pwd)/serving_model/keras_served_model,target=/models/keras_served_model \\
-e MODEL_NAME=keras_served_model -t tensorflow/serving
Paso 3: Enviar una solicitud a TensorFlow Serving.
import requests
import json
import numpy as np
# Prepare input data
input_data = np.expand_dims(X_test[0], axis=0).tolist()
# Define the API URL for TensorFlow Serving
url = '<http://localhost:8501/v1/models/keras_served_model:predict>'
# Send a POST request to TensorFlow Serving
response = requests.post(url, json={"instances": input_data})
# Parse the response
predictions = response.json()['predictions']
print(f"Predictions: {predictions}")
Ejercicio 3: Desplegar un modelo Keras con Flask
Tarea: Crear una aplicación web en Flask que cargue un modelo Keras entrenado y lo sirva a través de una API para realizar predicciones. Escribe un script del lado del cliente para enviar una solicitud a la aplicación Flask.
Solución:
Paso 1: Crear la aplicación Flask.
from flask import Flask, request, jsonify
from tensorflow.keras.models import load_model
import numpy as np
# Initialize the Flask app
app = Flask(__name__)
# Load the trained Keras model
model = load_model('saved_model')
# Define an API route for predictions
@app.route('/predict', methods=['POST'])
def predict():
data = request.get_json(force=True)
input_data = np.array(data['instances'])
predictions = model.predict(input_data)
return jsonify(predictions=predictions.tolist())
# Run the Flask app
if __name__ == '__main__':
app.run(port=5000, debug=True)
Paso 2: Script del lado del cliente para enviar una solicitud a la aplicación Flask.
import requests
import json
import numpy as np
# Prepare input data
input_data = np.expand_dims(X_test[0], axis=0).tolist()
# Define the Flask API URL
url = '<http://localhost:5000/predict>'
# Send a POST request to the Flask API
response = requests.post(url, json={"instances": input_data})
# Parse the response
predictions = response.json()['predictions']
print(f"Predictions: {predictions}")
Ejercicio 4: Convertir un modelo Keras a TensorFlow Lite
Tarea: Convertir un modelo Keras entrenado al formato TensorFlow Lite y guardarlo. Utiliza el intérprete de TensorFlow Lite para ejecutar inferencias en el conjunto de datos de prueba.
Solución:
Paso 1: Convertir el modelo a TensorFlow Lite.
# Convert the Keras model to TensorFlow Lite format
converter = tf.lite.TFLiteConverter.from_saved_model('saved_model')
tflite_model = converter.convert()
# Save the TensorFlow Lite model to a file
with open('model.tflite', 'wb') as f:
f.write(tflite_model)
Paso 2: Cargar y ejecutar el modelo con TensorFlow Lite.
import tensorflow as tf
import numpy as np
# Load and preprocess the MNIST dataset
_, (X_test, _) = tf.keras.datasets.mnist.load_data()
X_test = X_test.astype(np.float32) / 255.0
X_test = X_test.reshape((X_test.shape[0], 28, 28, 1)) # Ensure the correct input shape
# Load the 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 (e.g., first test sample)
test_sample = np.expand_dims(X_test[0], axis=0).astype(np.float32)
# Set the input tensor
interpreter.set_tensor(input_details[0]['index'], test_sample)
# Run the model
interpreter.invoke()
# Get the output tensor (predictions)
output_data = interpreter.get_tensor(output_details[0]['index'])
print(f"TensorFlow Lite model predictions: {output_data}")
Ejercicio 5: Usar Model Checkpointing y Early Stopping
Tarea: Entrenar un modelo Keras con model checkpointing y early stopping para guardar el modelo con mejor rendimiento y detener el entrenamiento cuando el rendimiento deje de mejorar.
Solución:
from tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping
# Define the ModelCheckpoint and EarlyStopping callbacks
checkpoint_callback = ModelCheckpoint(filepath='best_model.h5', save_best_only=True, monitor='val_accuracy', mode='max', verbose=1)
early_stopping_callback = EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True, verbose=1)
# Train the model with both callbacks
model.fit(X_train, y_train, epochs=20, validation_data=(X_test, y_test), callbacks=[checkpoint_callback, early_stopping_callback])
En esta solución:
- ModelCheckpoint guarda el mejor modelo basado en la precisión de validación.
- EarlyStopping detiene el entrenamiento cuando la pérdida de validación deja de mejorar durante 3 épocas consecutivas.
Estos ejercicios refuerzan los conceptos clave del Capítulo 3, incluyendo guardar y cargar modelos Keras, desplegarlos en entornos de producción utilizando TensorFlow Serving y Flask, convertir modelos a TensorFlow Lite para aplicaciones móviles, y utilizar model checkpointing y early stopping para entrenamientos eficientes. Estas tareas son esenciales para llevar los modelos desde la investigación hasta su uso en el mundo real.