Ejemplo de entrenamiento de una red neuronal feedforward (también conocida como red neuronal de alimentación hacia adelante) utilizando TensorFlow.
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# Crear datos de entrenamiento (ejemplo: clasificación de puntos en dos clases)
np.random.seed(0)
X = np.random.rand(100, 2) # 100 ejemplos con 2 características
Y = (X[:, 0] + X[:, 1] > 1).astype(int) # Clasificación: 1 si x + y > 1, 0 en caso contrario
# Definir el modelo de la red neuronal
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(2,)),
tf.keras.layers.Dense(4, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
# Compilar el modelo
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Entrenar el modelo
history = model.fit(X, Y, epochs=100, verbose=0)
# Evaluar el modelo
loss, accuracy = model.evaluate(X, Y)
print(f'Pérdida: {loss:.4f}')
print(f'Precisión: {accuracy*100:.2f}%')
# Visualizar la pérdida durante el entrenamiento
plt.plot(history.history['loss'])
plt.title('Pérdida durante el entrenamiento')
plt.xlabel('Época')
plt.ylabel('Pérdida')
plt.show()
Este código realiza lo siguiente:
- Genera datos de entrenamiento
X
y etiquetasY
para un problema de clasificación binaria. En este ejemplo, se generan aleatoriamente 100 ejemplos con dos características y se clasifican en función de si la suma de las características supera 1. - Define el modelo de la red neuronal utilizando TensorFlow y Keras. El modelo tiene una capa de entrada con dos neuronas, una capa oculta con cuatro neuronas y una función de activación ReLU, y una capa de salida con una neurona y una función de activación sigmoide.
- Compila el modelo, especificando el optimizador (‘adam’) y la función de pérdida (‘binary_crossentropy’) para la clasificación binaria.
- Entrena el modelo en los datos de entrenamiento durante 100 épocas. El historial del entrenamiento se almacena en la variable
history
. - Evalúa el modelo en los mismos datos de entrenamiento y muestra la pérdida y la precisión obtenidas.
- Visualiza la pérdida durante el entrenamiento para observar cómo disminuye con el tiempo.
Pérdida: 0.7018 Precisión: 51.00%
![](https://beastieux.com/wp-content/uploads/2023/10/image-2.png)
Pérdida: 0.6231 Precisión: 74.00%
![](https://beastieux.com/wp-content/uploads/2023/10/image-3.png)
Hey, Jack here. I’m hooked on your website’s content – it’s informative, engaging, and always up-to-date. Thanks for setting the bar high!
Hey, I’m Jack. Your blog is a game-changer! The content is insightful, well-researched, and always relevant. Great job!
BaddieHub 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!
BaddieHub This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your magnificent post. Also, I’ve shared your site in my social networks!
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.
Obrigado, há muito tempo que procuro informações sobre este assunto e a sua é a melhor que descobri até agora. Mas e em relação aos resultados financeiros Você tem certeza em relação ao fornecimento
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
Ive read several just right stuff here Certainly price bookmarking for revisiting I wonder how a lot effort you place to create this kind of great informative website
certainly like your website but you need to take a look at the spelling on quite a few of your posts Many of them are rife with spelling problems and I find it very troublesome to inform the reality nevertheless I will definitely come back again
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
Hi my loved one I wish to say that this post is amazing nice written and include approximately all vital infos Id like to peer more posts like this
Your articles never fail to captivate me. Each one is a testament to your expertise and dedication to your craft. Thank you for sharing your wisdom with the world.
Hello i think that i saw you visited my weblog so i came to Return the favore Im trying to find things to improve my web siteI suppose its ok to use some of your ideas
Simply wish to say your article is as amazing The clearness in your post is just nice and i could assume youre an expert on this subject Well with your permission let me to grab your feed to keep updated with forthcoming post Thanks a million and please carry on the gratifying work
Temp Mail 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.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
My brother recommended I might like this web site He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks
I have read some excellent stuff here Definitely value bookmarking for revisiting I wonder how much effort you put to make the sort of excellent informative website
Simply wish to say your article is as amazing The clearness in your post is just nice and i could assume youre an expert on this subject Well with your permission let me to grab your feed to keep updated with forthcoming post Thanks a million and please carry on the gratifying work
Your work has captivated me just as much as it has captivated you. The visual presentation is elegant, and the written content is sophisticated. However, you appear concerned about the possibility of presenting something that could be considered dubious. I’m confident you’ll be able to resolve this issue promptly.
My brother recommended I might like this web site He was totally right This post actually made my day You cannt imagine just how much time I had spent for this information Thanks
My brother was absolutely right when he suggested that I would like this website. You have no idea how much time I spent looking for this information, but this post made my day.
Thanks I have recently been looking for info about this subject for a while and yours is the greatest I have discovered so far However what in regards to the bottom line Are you certain in regards to the supply
Excellent rhythm, please let me know when you make modifications to your website so I may learn from you. How can I register with a blog website? I was aware of this to some extent, but your broadcast provided me with a comprehensive grasp of it, so the account was really helpful.
I just found this incredible website recently, they develop engaging content for customers. The site owner understands how to provide value to fans. I’m delighted and hope they continue sharing excellent insights.
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
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
I have read some excellent stuff here Definitely value bookmarking for revisiting I wonder how much effort you put to make the sort of excellent informative website
I loved as much as youll receive carried out right here The sketch is attractive your authored material stylish nonetheless you command get bought an nervousness over that you wish be delivering the following unwell unquestionably come more formerly again as exactly the same nearly a lot often inside case you shield this hike
Its like you read my mind You appear to know so much about this like you wrote the book in it or something I think that you can do with a few pics to drive the message home a little bit but other than that this is fantastic blog A great read Ill certainly be back