Guest User

Untitled

a guest
Feb 22nd, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. import matplotlib.pyplot as plt
  2. import random
  3. import numpy as np
  4. area_of_house = [10]
  5. prices=[10]
  6. for i in range(1,10):
  7. value = random.randint(0,100)
  8. area_of_house.append(value)
  9. prices.append(value*100)
  10. area_of_house.sort()
  11. prices.sort()
  12. n = len(area_of_house)
  13. theta_0 = 0
  14. theta_1 = 0
  15. alpha = 0.00009
  16.  
  17. def cal_error(theta_0,theta_1, n,area_of_price,prices):
  18. new_theta_0 = 0
  19. new_theta_1 = 0
  20. for i in range(n):
  21. new_theta_0 += ( theta_0 + theta_1 *area_of_house[i]) - prices[i]
  22. new_theta_1 += ((theta_0 + theta_1 * area_of_house[i])- prices[i])* area_of_house[i]
  23. return (new_theta_0/n, new_theta_1/n)
  24.  
  25.  
  26. def gradient_descent():
  27. theta_0_ = 0
  28. theta_1_ = 0
  29. list_theta_0 = []
  30. list_theta_1 = []
  31. counter = 0
  32. arraycounter=[]
  33.  
  34. while True:
  35. counter+=1
  36. arraycounter.append(counter)
  37.  
  38.  
  39. error_1,error_2 = cal_error(theta_0_,theta_1_, n, area_of_house,prices)
  40. theta_0_ = theta_0_ - alpha * (error_1)
  41. theta_1_ = theta_1_ - alpha * (error_2)
  42. list_theta_0.append(theta_0_)
  43. list_theta_1.append(theta_1_)
  44.  
  45. print(error_1, " ",error_2)
  46. if error_1<=0.01 or error_2 <=0.01 or counter == 300:
  47. list_theta_0 = np.asarray(list_theta_0)
  48. list_theta_1 = np.asarray(list_theta_1)
  49. plt.figure(figsize=(10, 6), dpi=80)
  50. plt.plot(list_theta_0, arraycounter, color="blue", linewidth=2.5, linestyle="-")
  51. plt.plot(list_theta_1,arraycounter, color="red", linewidth=2.5, linestyle="-")
  52. break
  53. return
  54.  
  55. gradient_descent()
Add Comment
Please, Sign In to add comment