TensorFlow / Python: Entrenamiento de Redes Neuronales Feedforward

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:

  1. Genera datos de entrenamiento X y etiquetas Y 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.
  2. 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.
  3. Compila el modelo, especificando el optimizador (‘adam’) y la función de pérdida (‘binary_crossentropy’) para la clasificación binaria.
  4. Entrena el modelo en los datos de entrenamiento durante 100 épocas. El historial del entrenamiento se almacena en la variable history.
  5. Evalúa el modelo en los mismos datos de entrenamiento y muestra la pérdida y la precisión obtenidas.
  6. Visualiza la pérdida durante el entrenamiento para observar cómo disminuye con el tiempo.

Pérdida: 0.7018 Precisión: 51.00%

Pérdida: 0.6231 Precisión: 74.00%

31 thoughts on “TensorFlow / Python: Entrenamiento de Redes Neuronales Feedforward

  1. 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!

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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.

  9. 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.

  10. 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.

  11. 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.

  12. 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

  13. 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

  14. 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

  15. 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

Deja un comentario