TensorFlow / Python: Reconocimiento de Dígitos Manuscritos con Redes Neuronales Convolucionales

Ejemplo simple de código en Python utilizando la biblioteca Keras y TensorFlow, para construir y entrenar una red neuronal para la clasificación de dígitos escritos a mano, usando el dataset MNIST.

# Importar bibliotecas necesarias
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist
import matplotlib.pyplot as plt

# Cargar y preprocesar los datos
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0  # Normalizar los valores de píxeles

# Crear el modelo de red neuronal convolucional (CNN)
model = keras.Sequential([
    layers.Input(shape=(28, 28, 1)),  # Capa de entrada con imágenes en escala de grises
    layers.Conv2D(32, kernel_size=(3, 3), activation='relu'),  # Capa convolucional con 32 filtros
    layers.MaxPooling2D(pool_size=(2, 2)),  # Capa de max-pooling para reducir el tamaño
    layers.Conv2D(64, kernel_size=(3, 3), activation='relu'),  # Otra capa convolucional con 64 filtros
    layers.MaxPooling2D(pool_size=(2, 2)),  # Otra capa de max-pooling
    layers.Flatten(),  # Capa de aplanamiento para convertir la salida en un vector
    layers.Dense(128, activation='relu'),  # Capa oculta con 128 neuronas y ReLU
    layers.Dropout(0.5),  # Regularización Dropout
    layers.Dense(10, activation='softmax')  # Capa de salida con 10 neuronas y activación softmax
])

# Compilar el modelo
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# Entrenar el modelo
history = model.fit(x_train, y_train, epochs=5, validation_data=(x_test, y_test))

# Evaluar el modelo con los datos de prueba
test_loss, test_acc = model.evaluate(x_test, y_test)
print(f'Precisión en datos de prueba: {test_acc*100:.2f}%')

# Visualizar la precisión y la pérdida durante el entrenamiento
plt.plot(history.history['accuracy'], label='Precisión de entrenamiento')
plt.plot(history.history['val_accuracy'], label='Precisión de prueba')
plt.xlabel('Épocas')
plt.ylabel('Precisión')
plt.legend(loc='lower right')
plt.show()

Precisión en datos de prueba: 99.03%

Este código realiza lo siguiente:

Importación de bibliotecas: Se importan las bibliotecas necesarias, incluyendo TensorFlow, Keras y Matplotlib para trabajar con redes neuronales y visualización.

Carga y preprocesamiento de datos: Se cargan los datos del conjunto de datos MNIST, que contiene imágenes de dígitos escritos a mano y sus etiquetas asociadas. Las imágenes se escalan normalizándolas, dividiendo cada valor de píxel por 255.0 para que estén en el rango de 0 a 1.

Definición del modelo de red neuronal convolucional (CNN): Se crea un modelo secuencial de Keras, que es una pila lineal de capas de red neuronal.

  • La capa de entrada (Input) se define con un tamaño de (28, 28, 1) para imágenes en escala de grises de 28×28 píxeles.
  • El modelo consta de capas convolucionales (Conv2D) con filtros y activaciones ReLU, seguidas de capas de max-pooling (MaxPooling2D) para reducir el tamaño de las características extraídas.
  • Después de las capas convolucionales, hay una capa de aplanamiento (Flatten) que convierte la salida en un vector unidimensional.
  • Luego, se agregan capas completamente conectadas (Dense) con activaciones ReLU y una capa de dropout (Dropout) para la regularización.
  • Finalmente, se agrega una capa de salida con 10 neuronas y activación softmax para clasificar los dígitos del 0 al 9.

Compilación del modelo: Se compila el modelo especificando el optimizador (en este caso, ‘adam’), la función de pérdida (‘sparse_categorical_crossentropy’ para clasificación) y las métricas a seguir (en este caso, la precisión).

Entrenamiento del modelo: El modelo se entrena usando el conjunto de entrenamiento (las imágenes de dígitos y sus etiquetas) durante 5 épocas (puedes ajustar este valor según tus necesidades). El entrenamiento se realiza utilizando el método fit, y la historia del entrenamiento se almacena en la variable history.

Evaluación del modelo: El modelo se evalúa en el conjunto de datos de prueba (x_test e y_test) para medir su rendimiento en datos no vistos. La precisión en datos de prueba y la pérdida se imprimen en la consola.

Visualización de resultados: Se utiliza Matplotlib para graficar la precisión del entrenamiento y la precisión en el conjunto de datos de prueba a lo largo de las épocas.

import matplotlib.pyplot as plt

# Función para mostrar imágenes y predicciones
def visualize_images_with_predictions(model, images, labels, num_images=5):
    predictions = model.predict(images)
    plt.figure(figsize=(12, 8))
    for i in range(num_images):
        plt.subplot(1, num_images, i + 1)
        plt.imshow(images[i].reshape(28, 28), cmap='gray')
        predicted_label = predictions[i].argmax()
        true_label = labels[i]
        title = f"Predicción: {predicted_label}\nEtiqueta real: {true_label}"
        plt.title(title)
        plt.axis('off')
    plt.show()

# Elegir un número de imágenes para visualizar
num_images_to_visualize = 5
visualize_images_with_predictions(model, x_test[:num_images_to_visualize], y_test[:num_images_to_visualize])

    Este código es un ejemplo típico de entrenamiento de una red neuronal convolucional para la clasificación de imágenes y es aplicable a tareas como el reconocimiento de dígitos escritos a mano. La visualización de la precisión y la pérdida durante el entrenamiento es útil para evaluar el rendimiento del modelo.

    45 thoughts on “TensorFlow / Python: Reconocimiento de Dígitos Manuscritos con Redes Neuronales Convolucionales

    1. Your blog is a testament to your dedication to your craft. Your commitment to excellence is evident in every aspect of your writing. Thank you for being such a positive influence in the online community.

    2. you are truly a just right webmaster The site loading speed is incredible It kind of feels that youre doing any distinctive trick In addition The contents are masterwork you have done a great activity in this matter

    3. Magnificent beat I would like to apprentice while you amend your site how can i subscribe for a blog web site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear idea

    4. Batida maravilhosa, gostaria de aprender enquanto você altera seu site, como posso me inscrever em um blog? A conta me ajudou a fazer um acordo aceitável. Eu estava um pouco ciente disso, sua transmissão forneceu uma ideia clara e clara

    5. Excellent blog here Also your website loads up very fast What web host are you using Can I get your affiliate link to your host I wish my web site loaded up as quickly as yours lol

    6. Usually I do not read article on blogs however I would like to say that this writeup very compelled me to take a look at and do it Your writing style has been amazed me Thank you very nice article

    7. Somebody essentially lend a hand to make significantly posts I might state That is the very first time I frequented your web page and up to now I surprised with the research you made to create this particular put up amazing Excellent job

    8. I loved as much as you will receive carried out right here The sketch is attractive your authored material stylish nonetheless you command get got an impatience over that you wish be delivering the following unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike

    9. I simply could not go away your web site prior to suggesting that I really enjoyed the standard info a person supply on your guests Is going to be back incessantly to investigate crosscheck new posts

    10. Fantastic beat I would like to apprentice while you amend your web site how could i subscribe for a blog site The account helped me a acceptable deal I had been a little bit acquainted of this your broadcast offered bright clear concept

    11. of course like your website but you have to check the spelling on several of your posts A number of them are rife with spelling issues and I in finding it very troublesome to inform the reality on the other hand I will certainly come back again

    12. Somebody essentially lend a hand to make significantly posts I might state That is the very first time I frequented your web page and up to now I surprised with the research you made to create this particular put up amazing Excellent job

    13. I was recommended this website by my cousin I am not sure whether this post is written by him as nobody else know such detailed about my difficulty You are wonderful Thanks

    14. Excellent blog here Also your website loads up very fast What web host are you using Can I get your affiliate link to your host I wish my web site loaded up as quickly as yours lol

    15. Thank you I have just been searching for information approximately this topic for a while and yours is the best I have found out so far However what in regards to the bottom line Are you certain concerning the supply

    16. I loved even more than you will get done right here. The overall look is nice, and the writing is stylish, but there’s something off about the way you write that makes me think that you should be careful what you say next. I will definitely be back again and again if you protect this hike.

    17. I just wanted to say how amazing your post is. It’s so apparent that I could tell you were an expert on the subject. If it’s okay with you, I’d like to subscribe to your RSS feed so I can be updated when you write more. Thank you so much, and please keep up the fun work.

    18. I loved even more than you will get done right here. The picture is nice, and your writing is stylish, but you seem to be rushing through it, and I think you should give it again soon. I’ll probably do that again and again if you protect this walk.

    Deja un comentario