Guest User

Untitled

a guest
Oct 17th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.09 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.  
  9. # Initialize weights
  10. self.weights_input_to_hidden = np.random.normal(0.0, self.input_nodes**-0.5,
  11. (self.input_nodes, self.hidden_nodes))
  12.  
  13. self.weights_hidden_to_output = np.random.normal(0.0, self.hidden_nodes**-0.5,
  14. (self.hidden_nodes, self.output_nodes))
  15. self.lr = learning_rate
  16.  
  17. #### TODO: Set self.activation_function to your implemented sigmoid function ####
  18. #
  19. # Note: in Python, you can define a function with a lambda expression,
  20. # as shown below.
  21. #self.activation_function = lambda x : 1 / (1 + np.exp(-x)) # Replace 0 with your sigmoid calculation.
  22.  
  23. ### If the lambda code above is not something you're familiar with,
  24. # You can uncomment out the following three lines and put your
  25. # implementation there instead.
  26. #
  27. def sigmoid(x):
  28. return 1 / (1 + np.exp(-x)) # Replace 0 with your sigmoid calculation here
  29. self.activation_function = sigmoid
  30.  
  31.  
  32. def train(self, features, targets):
  33. ''' Train the network on batch of features and targets.
  34.  
  35. Arguments
  36. ---------
  37.  
  38. features: 2D array, each row is one data record, each column is a feature
  39. targets: 1D array of target values
  40.  
  41. '''
  42. n_records = features.shape[0]
  43. delta_weights_i_h = np.zeros(self.weights_input_to_hidden.shape)
  44. delta_weights_h_o = np.zeros(self.weights_hidden_to_output.shape)
  45. for X, y in zip(features, targets):
  46. #### Implement the forward pass here ####
  47. ### Forward pass ###
  48. # TODO: Hidden layer - Replace these values with your calculations.
  49.  
  50. hidden_inputs = np.dot(X,self.weights_input_to_hidden)# signals into hidden layer
  51. hidden_outputs = self.activation_function(hidden_inputs)# signals from hidden layer
  52.  
  53. # TODO: Output layer - Replace these values with your calculations.
  54. final_inputs = np.dot(hidden_outputs,self.weights_hidden_to_output)# signals into final output layer
  55. final_outputs = final_inputs # signals from final output layer
  56.  
  57. ## ok
  58.  
  59.  
  60. #### Implement the backward pass here ####
  61. ### Backward pass ###
  62.  
  63. # TODO: Output error - Replace this value with your calculations.
  64. error = y - final_outputs # Output layer error is the difference between desired target and actual output.
  65.  
  66. # TODO: Calculate the backpropagated error term (delta) for the output
  67.  
  68. output_error_term = error
  69. # derivate f(x) = 1
  70.  
  71. # TODO: Calculate the hidden layer's contribution to the error
  72. hidden_error = np.dot(self.weights_hidden_to_output, output_error_term)
  73.  
  74. # TODO: Calculate the backpropagated error term (delta) for the hidden layer
  75. hidden_error_term = hidden_error * hidden_outputs * (1 - hidden_outputs)
  76.  
  77. # Weight step (input to hidden)
  78. #x = self.input_nodes
  79. delta_weights_i_h += hidden_error_term * X[:, None]
  80. # Weight step (hidden to output)
  81. delta_weights_h_o += output_error_term * hidden_outputs
  82.  
  83. # TODO: Update the weights - Replace these values with your calculations.
  84. self.weights_hidden_to_output += self.lr * delta_weights_h_o / n_records # update hidden-to-output weights with gradient descent step
  85. self.weights_input_to_hidden += self.lr * delta_weights_i_h / n_records # update input-to-hidden weights with gradient descent step
  86.  
  87. def run(self, features):
  88. ''' Run a forward pass through the network with input features
  89.  
  90. Arguments
  91. ---------
  92. features: 1D array of feature values
  93. '''
  94.  
  95. #### Implement the forward pass here ####
  96.  
  97. # TODO: Hidden layer - replace these values with the appropriate calculations.
  98. hidden_inputs = np.dot(self.input_nodes,self.weights_input_to_hidden) # signals into hidden layer
  99. hidden_outputs = self.activation_function(hidden_inputs) # signals from hidden layer
  100.  
  101. # TODO: Output layer - Replace these values with the appropriate calculations.
  102. final_inputs = np.dot(hidden_outputs,self.weights_hidden_to_output) # signals into final output layer
  103. final_outputs = final_inputs # signals from final output layer
  104.  
  105. return final_outputs
  106.  
  107.  
  108.  
  109.  
  110.  
  111. def MSE(y, Y):
  112. return np.mean((y-Y)**2)
  113.  
  114.  
  115. import unittest
  116.  
  117. inputs = np.array([[0.5, -0.2, 0.1]])
  118. targets = np.array([[0.4]])
  119. test_w_i_h = np.array([[0.1, -0.2],
  120. [0.4, 0.5],
  121. [-0.3, 0.2]])
  122. test_w_h_o = np.array([[0.3],
  123. [-0.1]])
  124.  
  125. class TestMethods(unittest.TestCase):
  126.  
  127. ##########
  128. # Unit tests for data loading
  129. ##########
  130.  
  131. def test_data_path(self):
  132. # Test that file path to dataset has been unaltered
  133. self.assertTrue(data_path.lower() == 'bike-sharing-dataset/hour.csv')
  134.  
  135. def test_data_loaded(self):
  136. # Test that data frame loaded
  137. self.assertTrue(isinstance(rides, pd.DataFrame))
  138.  
  139. ##########
  140. # Unit tests for network functionality
  141. ##########
  142.  
  143. def test_activation(self):
  144. network = NeuralNetwork(3, 2, 1, 0.5)
  145. # Test that the activation function is a sigmoid
  146. self.assertTrue(np.all(network.activation_function(0.5) == 1/(1+np.exp(-0.5))))
  147.  
  148. def test_train(self):
  149. # Test that weights are updated correctly on training
  150. network = NeuralNetwork(3, 2, 1, 0.5)
  151. network.weights_input_to_hidden = test_w_i_h.copy()
  152. network.weights_hidden_to_output = test_w_h_o.copy()
  153.  
  154. network.train(inputs, targets)
  155. self.assertTrue(np.allclose(network.weights_hidden_to_output,
  156. np.array([[ 0.37275328],
  157. [-0.03172939]])))
  158. self.assertTrue(np.allclose(network.weights_input_to_hidden,
  159. np.array([[ 0.10562014, -0.20185996],
  160. [0.39775194, 0.50074398],
  161. [-0.29887597, 0.19962801]])))
  162.  
  163. def test_run(self):
  164. # Test correctness of run method
  165. network = NeuralNetwork(3, 2, 1, 0.5)
  166. network.weights_input_to_hidden = test_w_i_h.copy()
  167. network.weights_hidden_to_output = test_w_h_o.copy()
  168.  
  169. self.assertTrue(np.allclose(network.run(inputs), 0.09998924))
  170.  
  171. suite = unittest.TestLoader().loadTestsFromModule(TestMethods())
  172. unittest.TextTestRunner().run(suite)
Add Comment
Please, Sign In to add comment