Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. import numpy as np
  2.  
  3. X_and = np.array([[0,0], [0,1], [1,0], [1,1]])
  4. Y_and = np.array([ [0], [0], [0], [1]])
  5.  
  6. X_or = np.array([[0, 0], [0,1], [1,0], [1,1]])
  7. Y_or = np.array([ [0], [1], [1], [1]])
  8.  
  9. X_nor = np.array([[0,0], [0,1], [1,0], [1,1]])
  10. Y_nor = np.array([ [1], [0], [0], [0]])
  11.  
  12. X_xor = np.array([[0,0], [0,1], [1,0], [1,1]])
  13. Y_xor = np.array([ [0], [1], [1], [0]])
  14.  
  15. iteration = 10000
  16. inputLayerSize, hiddenLayerSize, outputLayerSize = 2, 3, 1
  17.  
  18. w_l1 = np.random.uniform(size=(inputLayerSize, hiddenLayerSize))
  19. w_l2 = np.random.uniform(size=(hiddenLayerSize,outputLayerSize))
  20.  
  21. hiddenLayer_val = np.random.uniform(size=(inputLayerSize, hiddenLayerSize))
  22. outputLayer_val = np.random.uniform(size=(hiddenLayerSize,outputLayerSize))
  23. predict_and = np.random.uniform(size=(hiddenLayerSize,outputLayerSize))
  24. predict_or = np.random.uniform(size=(hiddenLayerSize,outputLayerSize))
  25. predict_nor = np.random.uniform(size=(hiddenLayerSize,outputLayerSize))
  26. predict_xor = np.random.uniform(size=(hiddenLayerSize,outputLayerSize))
  27.  
  28. def sigmoid (x): return 1/(1 + np.exp(-x))
  29. def sigmoid_(x): return x * (1 - x)
  30.  
  31.  
  32. for a in range(4):
  33.  
  34. X = X_and if a == 0 else X_or if a == 1 else X_nor if a == 2 else X_xor
  35. Y = Y_and if a == 0 else Y_or if a == 1 else Y_nor if a == 2 else Y_xor
  36.  
  37. for i in range(iteration):
  38. hiddenLayer_val = sigmoid(np.dot(X, w_l1))
  39. outputLayer_val = sigmoid(np.dot(hiddenLayer_val, w_l2))
  40.  
  41. error = Y - outputLayer_val
  42.  
  43. dF2 = error * sigmoid_(outputLayer_val)
  44. dF1 = dF2.dot(w_l2.T) * sigmoid_(hiddenLayer_val)
  45.  
  46. w_l2 += hiddenLayer_val.T.dot(dF2)
  47. w_l1 += X.T.dot(dF1)
  48.  
  49. if a == 0:
  50. predict_and = Y.T
  51. elif a == 1:
  52. predict_or = Y.T
  53. elif a == 2:
  54. predict_nor = Y.T
  55. elif a == 3:
  56. predict_xor = Y.T
  57.  
  58.  
  59. print("Predict AND: " + str(predict_and))
  60. print("Predict OR: " + str(predict_or))
  61. print("Predict NOR: " + str(predict_nor))
  62. print("Predict XOR: " + str(predict_xor))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement