Advertisement
Guest User

Untitled

a guest
Dec 15th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. import numpy as np
  2.  
  3.  
  4.  
  5. class Neural_Network(object):
  6. def __init__(self):
  7. #parameters
  8. self.inputSize = 2
  9. self.outputSize = 1
  10. self.hiddenSize = 3
  11.  
  12. #weights
  13. self.W1 = np.random.randn(self.inputSize, self.hiddenSize) # (3x2) weight matrix from input to hidden layer
  14. self.W2 = np.random.randn(self.hiddenSize, self.outputSize) # (3x1) weight matrix from hidden to output layer
  15.  
  16. def forward(self, X):
  17. #forward propagation through our network
  18. self.z = np.dot(X, self.W1) # dot product of X (input) and first set of 3x2 weights
  19. self.z2 = self.sigmoid(self.z) # activation function
  20. self.z3 = np.dot(self.z2, self.W2) # dot product of hidden layer (z2) and second set of 3x1 weights
  21. o = self.sigmoid(self.z3) # final activation function
  22. return o
  23.  
  24. def sigmoid(self, s):
  25. # activation function
  26. return 1/(1+np.exp(-s))
  27.  
  28. def sigmoidPrime(self, s):
  29. #derivative of sigmoid
  30. return s * (1 - s)
  31.  
  32. def backward(self, X, y, o):
  33. # backward propgate through the network
  34. self.o_error = y - o # error in output
  35. self.o_delta = self.o_error*self.sigmoidPrime(o) # applying derivative of sigmoid to error
  36.  
  37. self.z2_error = self.o_delta.dot(self.W2.T) # z2 error: how much our hidden layer weights contributed to output error
  38. self.z2_delta = self.z2_error*self.sigmoidPrime(self.z2) # applying derivative of sigmoid to z2 error
  39.  
  40. self.W1 += X.T.dot(self.z2_delta) # adjusting first set (input --> hidden) weights
  41. self.W2 += self.z2.T.dot(self.o_delta) # adjusting second set (hidden --> output) weights
  42.  
  43. def train (self, X, y):
  44. o = self.forward(X)
  45. self.backward(X, y, o)
  46.  
  47.  
  48.  
  49. if __name__ == '__main__':
  50. from sklearn import datasets
  51.  
  52. X = np.matrix([[0,0], [0,1], [1,0], [1,1]])
  53. y = np.matrix([[0], [1], [1], [0]])
  54.  
  55. NN = Neural_Network()
  56. for i in range(1000): # trains the NN 1,000 times
  57. print ("Input: \n" + str(X))
  58. print ("Actual Output: \n" + str(y) )
  59. print ("Predicted Output: \n" + str(NN.forward(X)) )
  60. print ("Loss: \n" + str(np.mean(np.square(y - NN.forward(X))))) # mean sum squared loss
  61. print ("\n")
  62. NN.train(X, y)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement