Advertisement
Guest User

Untitled

a guest
May 21st, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. from sklearn.datasets import make_regression #dataset
  3. import random
  4.  
  5.  
  6. X,Y = make_regression(n_features=1, noise=10, n_samples=1000)
  7.  
  8. plt.scatter(X,Y,s=5 , label = "training")
  9. plt.xlabel('Feature - X')
  10. plt.ylabel('Target - Y')
  11.  
  12. const = [random.random(), random.random()] #const[0] is m and const[1] is b (assuming y = mx + b)
  13.  
  14. def hypothesis(x , m , c):
  15. return (m*x) + c
  16.  
  17. def cost(m , c):
  18. error = 0
  19. i = 0
  20. while i < len(X):
  21. error += (hypothesis(X[i], m , c) - Y[i])**2
  22. i+=1
  23. return error
  24.  
  25. def SGD(x , y , learning_rate = 0.001):
  26. dCdm = 2*(hypothesis(x , const[0] , const[1]) - y)*x #dC/dm where C is cost function, found this out by chain rule
  27. dCdc = 2*(hypothesis(x , const[0] , const[1]) - y) #Similarly dC/db
  28. const[0] -= learning_rate * dCdm
  29. const[1] -= learning_rate * dCdc
  30.  
  31.  
  32. def epoch(j):
  33. i = 0
  34. while i < len(X):
  35. SGD(X[i] , Y[i])
  36. i+=1
  37. print("Epoch number "+str(j+1)+" cost equals " + str(cost(const[0], const[1])))
  38.  
  39. print("Initial Cost = " + str(cost(const[0] , const[1])))
  40.  
  41.  
  42. for i in range(100):
  43. epoch(i+1)
  44.  
  45. y = []
  46. for x in X:
  47. y.append(hypothesis(x , const[0] , const[1]))
  48.  
  49. plt.scatter(X,y,s=5 , label = "prediction")
  50.  
  51. plt.show()
  52. print(const[0] , const[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement