Advertisement
Guest User

Untitled

a guest
Dec 11th, 2021
294
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.23 KB | None | 0 0
  1.     class NeuralNetwork(object):
  2.    
  3.     def __init__(self, input_nodes, hidden_nodes, output_nodes, learning_rate):
  4.         # Set number of nodes in input, hidden and output layers.
  5.         self.input_nodes = input_nodes
  6.         self.hidden_nodes = hidden_nodes
  7.         self.output_nodes = output_nodes
  8.         self.lr = learning_rate
  9.        
  10.         # Initialize weights
  11.         self.input_hidden_weights = np.random.randn(hidden_nodes, input_nodes) # 10x7
  12.         self.hidden_output_weights = np.random.randn(output_nodes, hidden_nodes) # 1x10
  13.        
  14.        
  15.         # Sigmoid activation funciton
  16.         self.sigmoid = lambda x: 1/(1+np.exp(-x))
  17.         self.diff_sigm = lambda x: x*(1-x)
  18.        
  19.     def train(self, input_list, label_list):
  20.        
  21.         # Create an array of inputs and labels
  22.         inputs = np.array(input_list, ndmin=2).T # 7x1
  23.         labels = np.array(label_list, ndmin=2) # 1x1
  24.                
  25.         # Forward propagation
  26.         hidden_layer = self.sigmoid(np.dot(self.input_hidden_weights, inputs))        
  27.         output_layer = self.sigmoid(np.dot(self.hidden_output_weights, hidden_layer))
  28.        
  29.         final_output = output_layer
  30.        
  31.        
  32.         # Error function
  33.         output_errors = labels-final_output
  34.        
  35.         # Backpropagation  
  36.         output_delta = output_errors * self.diff_sigm(output_layer)
  37.         hidden_delta = np.dot(self.hidden_output_weights.T, output_delta) * self.diff_sigm(hidden_layer)
  38.        
  39.         # Update the weights
  40.         self.hidden_output_weights += np.dot(output_delta, hidden_layer.T) * self.lr
  41.         self.input_hidden_weights += np.dot(hidden_delta, inputs.T) * self.lr
  42.        
  43.        
  44.         """
  45.        # Backpropagation
  46.        hidden_errors = np.dot(self.hidden_output_weights.T, output_errors)        
  47.        hidden_grad = hidden_layer * (1.0 - hidden_layer)
  48.        
  49.        # Update the weights
  50.        self.hidden_output_weights += self.lr * np.dot(output_errors.T, output_layer.T) # update hidden-to-output weights with gradient descent step    
  51.        self.input_hidden_weights += self.lr * np.dot(hidden_errors * hidden_grad, inputs.T)  # update input-to-hidden weights with gradient descent step
  52.        """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement