Foro de elhacker.net

Programación => Programación General => Mensaje iniciado por: 4v1dy4 en 18 Octubre 2023, 13:22 pm



Título: Backpropagation no funciona - Redes neuronales.
Publicado por: 4v1dy4 en 18 Octubre 2023, 13:22 pm
Tengo esta red neuronal simple:

Código
  1. import numpy as np
  2.  
  3. class NeuralNetwork:
  4.    def __init__(self):
  5.        self.W1 = np.random.randn(2, 3)
  6.        self.W2 = np.random.randn(3, 1)
  7.  
  8.    def sigmoid(self, x):
  9.        return 1 / (1 + np.exp(-x))
  10.  
  11.    def sigmoid_deriv(self, x):
  12.        return x * (1 - x)
  13.  
  14.    def mse(self, O, P):
  15.        x = (P - O) ** 2
  16.        x = np.mean(x)
  17.        y = P - O
  18.        return (x, y)
  19.  
  20.    def forward(self, I):
  21.        self.Z1 = I @ self.W1
  22.        self.A1 = self.sigmoid(self.Z1)
  23.        self.Z2 = self.A1 @ self.W2
  24.        self.A2 = self.sigmoid(self.Z2)
  25.        return self.A2
  26.  
  27.    def backward(self, P, I, O):
  28.        error = self.A2 - P
  29.        D = [error * self.sigmoid_deriv(self.A2)]
  30.  
  31.        delta = np.random.randn(2, 3)
  32.        D.append(delta)
  33.  
  34.        self.W2 = self.W2 + (-0.01 * self.A2.T.dot(D[0]))
  35.        self.W1 = self.W1 + (-0.01 * self.A1.T.dot(D[1]))
  36.  
  37.    def train(self, I, P):
  38.        O = self.forward(I)
  39.        self.backward(P, I, O)
  40.  
  41. if __name__ == '__main__':
  42.    NN = NeuralNetwork()
  43.    I = np.array([[0, 1]])
  44.    P = np.array([[1]])
  45.    for i in range(1):
  46.        NN.train(I, P)
  47.    exit()

Cuando quiero calcular delta de W1, obtengo un error de dimensiones.

¿Que estoy haciendo mal?

Gracias de antemano por cualquier ayuda.