alxmrphi

Untitled

Sep 30th, 2017
962
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. @author: alex
  2. """
  3.  
  4. import numpy as np
  5.  
  6. train_data = np.array([[0,0],[0,1],[1,0],[1,1]]).T
  7. print(train_data)
  8. labels = np.array([0,1,1,0])
  9.  
  10. def sigmoid(z,deriv = False):
  11. sig = 1/(1+np.exp(-z))
  12. if deriv == True:
  13. return np.multiply(sig,1-sig)
  14. return sig
  15.  
  16.  
  17. w1 = np.random.randn(2,2)*0.01
  18. b1 = np.zeros((2,1))
  19.  
  20. w2 = np.random.randn(1,2)*0.01
  21. b2 = np.zeros((1,1))
  22.  
  23. lr = 5.5
  24.  
  25. for i in range(5000):
  26. # Shuffle data samples
  27. permutation = np.random.permutation([0,1,2,3])
  28. train_data = train_data[:,permutation]
  29. labels = labels[permutation]
  30.  
  31. z1 = np.dot(w1,train_data) + b1
  32. a1 = sigmoid(z1)
  33. z2 = np.dot(w2,a1) + b2
  34. a2 = sigmoid(z2)
  35.  
  36.  
  37. cost = np.dot(labels,np.log(a2).T) + np.dot(1-labels,np.log(1-a2).T)
  38. cost = cost*(-1/4)
  39.  
  40. # cost = ((1/4) * np.dot(labels,np.log(a2).T) + np.dot(1-labels,np.log(1-a2).T))
  41. cost = np.squeeze(cost)
  42.  
  43. #dz2 = np.multiply(da2,sigmoid(z2,deriv = True))
  44. dz2 = a2-labels
  45. dw2 = (1/4) * np.dot(dz2,a1.T)
  46. db2 = (1/4) * np.sum(dz2,axis=1,keepdims = True)
  47. dz1 = np.multiply(np.dot(w2.T, dz2),sigmoid(z1,deriv = True))
  48. dw1 = (1/4) * np.dot(dz1,train_data.T)
  49. db1 = (1/4) * np.sum(dz1,axis=1,keepdims = True) #backprop
  50.  
  51. w1 = w1 - lr*dw1
  52. w2 = w2 - lr*dw2
  53. b1 = b1 - lr*db1
  54. b2 = b2 - lr*db2 #update params
  55. print(np.abs(cost),'------',str(i))
  56.  
  57.  
  58. a1 = sigmoid(np.dot(w1, train_data) + b1)
  59. a2 = sigmoid(np.dot(w2, a1) + b2)
  60. print("Correct labels:", labels)
  61. print("Predicted labels:", np.round(a2[0]))
Advertisement
Add Comment
Please, Sign In to add comment