CautCode

Neural_Network_from_scratch.py

Sep 5th, 2017
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.95 KB | None | 0 0
  1.  
  2. from numpy import dot, random, exp, array, mean, seterr
  3. import math
  4.  
  5. random.seed(1)
  6.  
  7. n_classes = 1
  8.  
  9. #hidden_layer sizes 5 nodes and 4 nodes
  10. n_nodes = [5,4]
  11.  
  12. training_set_inputs = array([[0,0,1],[1,1,1],[1,0,1],[0,1,1],[1,0,0]])
  13. training_set_outputs = array([[0,1,1,0,1]]).T
  14.  
  15. weights_biases = []
  16. layers = []
  17.  
  18. #this code is for implementing biases. This may help with the output but I don't know how to
  19. #backpropgate biases
  20. """for j in range(len(n_nodes)):
  21.    if j == 0:
  22.        weights_biases.append({"weights": random.randn(len(training_set_inputs[0]), n_nodes[j]),"biases": random.randn(n_nodes[j])})
  23.    else:
  24.        weights_biases.append({"weights": random.randn(n_nodes[j-1], n_nodes[j]),"biases": random.randn(n_nodes[j])})
  25. weights_biases.append({"weights": random.randn(n_nodes[-1], n_classes),"biases": random.randn(n_classes)})
  26.  
  27. def neural_network(data, g_nodes):
  28.    for j in range(len(g_nodes)):
  29.        if j == 0:
  30.            hidden_layer = np.add(dot(data, weights_biases[j]["weights"]), weights_biases[j]["biases"])
  31.            layers.append(sigmoid(hidden_layer))
  32.        elif j != 0:
  33.            hidden_layer = np.add(dot(layers[j-1], weights_biases[j]["weights"]), weights_biases[j]["biases"])
  34.            layers.append(sigmoid(hidden_layer))
  35.  
  36.    output = np.add(dot(layers[-1], weights_biases[-1]["weights"]), weights_biases[-1]["biases"])
  37.    return output
  38. """
  39. #we set the initial weights to random because we do not have any other suggestion
  40. #if what they should be yet
  41. #the biases are there so that if the weights return a value of 0  the bias
  42. #can correct that
  43. for j in range(len(n_nodes)):
  44.     if j == 0:
  45.         weights_biases.append({"weights": random.randn(len(training_set_inputs[0]), n_nodes[j])})
  46.     elif len(n_nodes) > 1 and j != 0:
  47.         weights_biases.append({"weights": random.randn(n_nodes[j-1], n_nodes[j])})
  48. weights_biases.append({"weights": random.randn(n_nodes[-1], n_classes)})
  49.  
  50. def neural_network(data, g_nodes):
  51.     #this updates the values for the hidden layers by using the weights and
  52.     #the values from the previous hidden layer to update them
  53.     for j in range(len(g_nodes)):
  54.         if j == 0:
  55.             hidden_layer = dot(data, weights_biases[j]["weights"])
  56.             layers.append(sigmoid(hidden_layer))
  57.         elif len(n_nodes) > 1 and j != 0:
  58.             hidden_layer = dot(layers[j-1], weights_biases[j]["weights"])
  59.             layers.append(sigmoid(hidden_layer))
  60.  
  61.     layers.append(dot(layers[-1], weights_biases[-1]["weights"]))
  62.     return layers[-len(n_nodes) - 1:]
  63.  
  64. #sigmoid activation function
  65. def sigmoid(x):
  66.   return 1 / (1 + exp(-x))
  67.  
  68. #derivative of sigmoid
  69. def sigmoid_derivative(x):
  70.     return x * (1 - x)
  71.  
  72. #training function that trains and updates the weights in our neural net
  73. def train(target, num_iterations, learning_rate):
  74.     for i in range(num_iterations):
  75.         #see what results our neural net gives us now
  76.         layers_vals = neural_network(training_set_inputs, n_nodes)
  77.  
  78.         #output from the hidden layers
  79.         output = layers_vals[-1]
  80.  
  81.         #deltas are the change needed to adjust the weights
  82.         delta4 = (target - output) * sigmoid_derivative(output)
  83.  
  84.         delta3 = dot(weights_biases[2]["weights"], delta4.T)*(sigmoid_derivative(layers_vals[1]).T)
  85.         delta2 = dot(weights_biases[1]["weights"], delta3)*(sigmoid_derivative(layers_vals[0]).T)
  86.  
  87.         adjustment3 = dot(layers_vals[1].T, delta4) * learning_rate
  88.         adjustment2 = dot(layers_vals[0].T, delta3.T) * learning_rate
  89.         adjustment1 = dot(training_set_inputs.T, delta2.T) * learning_rate
  90.  
  91.         #update the weights
  92.         weights_biases[0]["weights"] += adjustment1
  93.         weights_biases[1]["weights"] += adjustment2
  94.         weights_biases[2]["weights"] += adjustment3
  95.  
  96.         if i % 100 == 0:
  97.             print str(num_iterations/100) + " epoch error: " + str(mean(abs(target-output)))
  98.             print output
  99. train(training_set_outputs, 20000, 0.01)
Advertisement
Add Comment
Please, Sign In to add comment