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.
Newtoki For the reason that the admin of this site is working, no uncertainty very quickly it will be renowned, due to its quality contents.
Strands Hint There is definately a lot to find out about this subject. I like all the points you made
Thinker Pedia I do not even understand how I ended up here, but I assumed this publish used to be great
Thinker Pedia I very delighted to find this internet site on bing, just what I was searching for as well saved to fav
Keep up the fantastic work! Kalorifer Sobası odun, kömür, pelet gibi yakıtlarla çalışan ve ısıtma işlevi gören bir soba türüdür. Kalorifer Sobası içindeki yakıtın yanmasıyla oluşan ısıyı doğrudan çevresine yayar ve aynı zamanda suyun ısınmasını sağlar.
Masalqseen I really like reading through a post that can make men and women think. Also, thank you for allowing me to comment!
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.
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 trouble You are amazing Thanks
I do not even know how I ended up here but I thought this post was great I do not know who you are but certainly youre going to a famous blogger if you are not already Cheers
Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content
allegheny county real estate I truly appreciate your technique of writing a blog. I added it to my bookmark site list and will
Simplywall I do not even understand how I ended up here, but I assumed this publish used to be great
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
Internet Chicks For the reason that the admin of this site is working, no uncertainty very quickly it will be renowned, due to its quality contents.
Fourweekmba I’m often to blogging and i really appreciate your content. The article has actually peaks my interest. I’m going to bookmark your web site and maintain checking for brand spanking new information.
Real Estate very informative articles or reviews at this time.
Mygreat learning I just like the helpful information you provide in your articles
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
Nice blog here Also your site loads up fast What 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
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
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
Vitazen Keto Gummies You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
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
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
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
Nice blog here Also your site loads up fast What 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
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
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
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
Thank you for the auspicious writeup It in fact was a amusement account it Look advanced to more added agreeable from you By the way how could we communicate
I really like reading through a post that can make men and women think. Also, thank you for allowing me to comment!
This site is incredible. The radiant material shows the essayist’s enthusiasm. I’m dumbfounded and envision more such astonishing presents.
Hi my love, I just wanted to say how well written and packed with virtually all the essential information this post is. I’m hoping for more blogs similar to this one.
Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Nice blog here Also your site loads up very fast What host are you using Can I get your affiliate link to your host I wish my site loaded up as quickly as yours lol
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
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
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
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
Wonderful web site Lots of useful info here Im sending it to a few friends ans additionally sharing in delicious And obviously thanks to your effort
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.
Which hosting service are you using? Could I have your host’s affiliate link? My website loads far slower than yours does. Excellent blog as well.
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.
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.
Excellent information was provided. I truly liked reading this piece, and I’m grateful to the author for providing it. Thank you for sharing this blog post. Once again, thanks. Nice.