Felanpro

NeuralNetworkFrameworkBetaVersionStrongestAndLatest

Dec 11th, 2022
782
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.40 KB | Source Code | 0 0
  1. '''
  2. This neural network framework nudges both weights and biases in all layers when it performs backpropagation. It can handle multiple outputs and inputs. Working on implementing the relu activation function in backpropagation (try it out it should work)
  3. '''
  4.  
  5. import numpy as np
  6. import random
  7.  
  8. class Layer:
  9.     def __init__(self, inputNodes, outputNodes):
  10.         self.weights = 0.1 * np.random.randn(inputNodes, outputNodes)
  11.         self.biases = 0 + np.zeros((1, outputNodes))
  12.    
  13.     def forward(self, inputs):
  14.         self.output = np.dot(inputs, self.weights) + self.biases
  15. class Activation_ReLU:
  16.     def forward(self, inputs):
  17.         self.output = np.maximum(0, inputs)    
  18.  
  19.  
  20. learningRate = 0.00000001
  21. def backwards(network, input_, desired):
  22.     currentLayer = len(network) - 1
  23.  
  24.     dError = 2*(network[currentLayer].output[0] - desired)
  25.    
  26.     gradients = np.zeros((len(network), 10)) #The digit here represent maximum number of neurons per layer
  27.  
  28.     #This presumes the last layer is a normal one and not an activation
  29.     for neuronsPerLastLayer in range(len(network[currentLayer].output[0])):
  30.         gradients[currentLayer][neuronsPerLastLayer] = dError[neuronsPerLastLayer]    
  31.  
  32.     # Start backpropagation for the rest of the layer
  33.     while currentLayer >= 0: # Per layer except last one that's connected to the network input
  34.         if currentLayer == 0:
  35.             # Nudge the weights and biases in the first layer
  36.             for neuronCurrentLayer in range(len(network[currentLayer].output[0])): # Per neuron in current layer
  37.                 network[currentLayer].biases[0][neuronCurrentLayer] -= 1 * gradients[currentLayer][neuronCurrentLayer] * learningRate
  38.                 for neuronPreviousLayer in range(len(input_)): # Per neuron in previous layer
  39.                     network[currentLayer].weights[neuronPreviousLayer][neuronCurrentLayer] -= input_[neuronPreviousLayer] * gradients[currentLayer][neuronCurrentLayer] * learningRate
  40.            
  41.             currentLayer -= 1
  42.         else:
  43.             #Nudge the weights and biases
  44.             for neuronCurrentLayer in range(len(network[currentLayer].output[0])): # Per neuron in current layer
  45.                 network[currentLayer].biases[0][neuronCurrentLayer] -= 1 * gradients[currentLayer][neuronCurrentLayer] * learningRate
  46.                 for neuronPreviousLayer in range(len(network[currentLayer - 1].output[0])): # Per neuron in previous layer/per weight per neuron in current layer
  47.                     network[currentLayer].weights[neuronPreviousLayer][neuronCurrentLayer] -= network[currentLayer - 1].output[0][neuronPreviousLayer] * gradients[currentLayer][neuronCurrentLayer] * learningRate    
  48.            
  49.             # Calculate gradients for every neuron in the next layer you're going to adjust
  50.             if type(network[currentLayer - 1]) == Activation_ReLU:
  51.                 for neuronCurrentLayer in range(len(network[currentLayer].output[0])): # Per neuron in current layer
  52.                     for neuronPreviousLayer in range(len(network[currentLayer - 2].output[0])): # Per neuron in previous normal layer (skips activation layer)
  53.                         if(network[currentLayer - 2].output[0][neuronPreviousLayer] > 0):
  54.                             gradients[currentLayer - 2][neuronPreviousLayer] += network[currentLayer].weights[neuronPreviousLayer][neuronCurrentLayer] * gradients[currentLayer][neuronCurrentLayer]
  55.                         else:
  56.                             gradients[currentLayer - 2][neuronPreviousLayer] = 0
  57.  
  58.                 currentLayer -= 2
  59.             else:
  60.                 for neuronCurrentLayer in range(len(network[currentLayer].output[0])): # Per neuron in current layer
  61.                     for neuronPreviousLayer in range(len(network[currentLayer - 1].output[0])): # Per neuron in previous layer
  62.                         gradients[currentLayer - 1][neuronPreviousLayer] += network[currentLayer].weights[neuronPreviousLayer][neuronCurrentLayer] * gradients[currentLayer][neuronCurrentLayer]
  63.                        
  64.                 currentLayer -= 1
  65.  
  66.     #print("Error: ", (network[len(network) - 1].output[0] - desired))
  67.     #error = network[len(network) - 1].output[0] - desired
  68.     #print("Gradients total: \n", gradients)
  69.  
  70.        
  71. #Create training data
  72. #inputs = [3, 6, 2, 8, 12, 90, 45, 23, 88, 18]
  73. #desired = np.array([[6, 6], [12, 12], [4, 4], [16, 16], [24, 24], [180, 180], [90, 90], [46, 46], [176, 176], [36, 36]])
  74. #inputs = [4, 6, 1, 3, 9, 2, 3, 7, 10, 34]
  75. #desired = [8, 12, 2, 6, 18, 4, 6, 14, 20, 68]
  76.  
  77. inputs = []
  78. desired = []
  79.  
  80. for y in range(1000):
  81.     inputs.append(y + 1)
  82.    
  83. random.shuffle(inputs)
  84.  
  85. for y in range(1000):
  86.     desired.append(inputs[y] * 2)
  87.  
  88.  
  89. #Create neural network
  90. layer1 = Layer(1, 3)
  91.  
  92. layer2 = Layer(3, 3)
  93. activation2 = Activation_ReLU()
  94.  
  95. layer3 = Layer(3, 3)
  96. activation3 = Activation_ReLU()
  97.  
  98. layer4 = Layer(3, 1)
  99.  
  100. #Train the network
  101. for samples_in_batch in range(10):
  102.     for x in range(len(inputs)):
  103.  
  104.         '''
  105.        #With activations
  106.        layer1.forward(inputs[x])
  107.        layer2.forward(layer1.output)
  108.        activation2.forward(layer2.output)
  109.        layer3.forward(activation2.output)
  110.        activation3.forward(layer3.output)
  111.        layer4.forward(activation3.output)
  112.    
  113.        backwards([layer1, layer2, activation2, layer3, activation3, layer4], inputs[x], desired[x])
  114.        '''
  115.  
  116.         #Without activations
  117.         layer1.forward(inputs[x])
  118.         layer2.forward(layer1.output)
  119.        
  120.         layer3.forward(layer2.output)
  121.         layer4.forward(layer3.output)
  122.        
  123.         #inputToList = [inputs[x]]
  124.         backwards([layer1, layer2, layer3, layer4], [inputs[x]], desired[x])
  125.  
  126. #Test the network
  127. testInput = 333 #Always has to be a list or np.array even if it's just one input element
  128.  
  129. #With activations
  130. '''
  131. layer1.forward(testInput)
  132. layer2.forward(layer1.output)
  133. activation2.forward(layer2.output)
  134. layer3.forward(activation2.output)
  135. activation3.forward(layer3.output)
  136. layer4.forward(activation3.output)
  137. #backwards([layer1, layer2, activation2, layer3, activation3, layer4], testInput, 48)
  138. '''
  139.  
  140. #Without activations
  141. layer1.forward(testInput)
  142. layer2.forward(layer1.output)
  143. layer3.forward(layer2.output)
  144. layer4.forward(layer3.output)
  145.  
  146. backwards([layer1, layer2, layer3, layer4], [testInput], testInput*2)
  147.  
  148. print("Guess: ", layer4.output)
  149. print("Error: ", layer4.output - (testInput * 2))
  150.  
  151.  
  152.  
Advertisement
Add Comment
Please, Sign In to add comment