Advertisement
cardel

Reto2 Oscar USA

Jun 24th, 2024
449
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.03 KB | None | 0 0
  1. import numpy as np
  2. from sklearn import datasets
  3. from sklearn.model_selection import train_test_split
  4. from sklearn.preprocessing import OneHotEncoder
  5. from sklearn.metrics import accuracy_score
  6.  
  7. # Inicializar la semilla para los números aleatorios
  8. np.random.seed(1)
  9.  
  10. # Definir funciones de activación y sus derivadas
  11. def sigmoid(x):
  12.     return 1 / (1 + np.exp(-x))
  13.  
  14. def sigmoid_derivative(x):
  15.     return x * (1 - x)
  16.  
  17. def relu(x):
  18.     return np.maximum(0, x)
  19.  
  20. def relu_derivative(x):
  21.     return np.where(x > 0, 1, 0)
  22.  
  23. # Función para entrenar la red neuronal
  24. def train(X, y, epochs, learning_rate, activation_hidden, activation_output, derivative_hidden, derivative_output):
  25.     input_layer_neurons = X.shape[1]
  26.     hidden_layer_neurons = 10
  27.     output_layer_neurons = y.shape[1]
  28.    
  29.     hidden_weights = np.random.randn(input_layer_neurons, hidden_layer_neurons)
  30.     hidden_bias = np.zeros((1, hidden_layer_neurons))
  31.     output_weights = np.random.randn(hidden_layer_neurons, output_layer_neurons)
  32.     output_bias = np.zeros((1, output_layer_neurons))
  33.  
  34.     for _ in range(epochs):
  35.         hidden_layer_activation = np.dot(X, hidden_weights) + hidden_bias
  36.         hidden_layer_output = activation_hidden(hidden_layer_activation)
  37.         output_layer_activation = np.dot(hidden_layer_output, output_weights) + output_bias
  38.         predicted_output = activation_output(output_layer_activation)
  39.  
  40.         error = y - predicted_output
  41.         d_predicted_output = error * derivative_output(predicted_output)
  42.         error_hidden_layer = d_predicted_output.dot(output_weights.T)
  43.         d_hidden_layer = error_hidden_layer * derivative_hidden(hidden_layer_output)
  44.  
  45.         output_weights += hidden_layer_output.T.dot(d_predicted_output) * learning_rate
  46.         output_bias += np.sum(d_predicted_output, axis=0, keepdims=True) * learning_rate
  47.         hidden_weights += X.T.dot(d_hidden_layer) * learning_rate
  48.         hidden_bias += np.sum(d_hidden_layer, axis=0, keepdims=True) * learning_rate
  49.  
  50.     return hidden_weights, hidden_bias, output_weights, output_bias
  51.  
  52. # Función para realizar predicciones
  53. def predict(X, hidden_weights, hidden_bias, output_weights, output_bias, activation_hidden, activation_output):
  54.     hidden_layer_activation = np.dot(X, hidden_weights) + hidden_bias
  55.     hidden_layer_output = activation_hidden(hidden_layer_activation)
  56.     output_layer_activation = np.dot(hidden_layer_output, output_weights) + output_bias
  57.     predicted_output = activation_output(output_layer_activation)
  58.     return predicted_output
  59.  
  60. # Preparar datos
  61. iris = datasets.load_iris()
  62. X = iris.data
  63. y = iris.target.reshape(-1, 1)
  64.  
  65. encoder = OneHotEncoder()
  66. y = encoder.fit_transform(y).toarray()
  67.  
  68. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
  69.  
  70. # Leer los parámetros de entrada
  71. console_input = input().split()
  72. epochs, learning_rate = int(console_input[0]), float(console_input[1])
  73. epochs = int(epochs)
  74.  
  75. # Entrenar y evaluar la red con ReLU en la capa oculta y Sigmoide en la capa de salida
  76. hidden_weights_relu, hidden_bias_relu, output_weights_relu, output_bias_relu = train(
  77.     X_train, y_train, epochs, learning_rate, relu, sigmoid, relu_derivative, sigmoid_derivative
  78. )
  79. predictions_relu = predict(X_test, hidden_weights_relu, hidden_bias_relu, output_weights_relu, output_bias_relu, relu, sigmoid)
  80. accuracy_relu = accuracy_score(np.argmax(y_test, axis=1), np.argmax(predictions_relu, axis=1))
  81.  
  82. # Entrenar y evaluar la red con Sigmoide en ambas capas
  83. hidden_weights_sigmoid, hidden_bias_sigmoid, output_weights_sigmoid, output_bias_sigmoid = train(
  84.     X_train, y_train, epochs, learning_rate, sigmoid, sigmoid, sigmoid_derivative, sigmoid_derivative
  85. )
  86. predictions_sigmoid = predict(X_test, hidden_weights_sigmoid, hidden_bias_sigmoid, output_weights_sigmoid, output_bias_sigmoid, sigmoid, sigmoid)
  87. accuracy_sigmoid = accuracy_score(np.argmax(y_test, axis=1), np.argmax(predictions_sigmoid, axis=1))
  88.  
  89. # Imprimir las precisiones de ambas redes
  90. print(f"{round(accuracy_relu,4)} {round(accuracy_sigmoid,4)}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement