Advertisement
Guest User

Untitled

a guest
Oct 25th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. import matplotlib
  2. import numpy as np
  3. import matplotlib.cm as cm
  4. import matplotlib.mlab as mlab
  5. import matplotlib.pyplot as plt
  6.  
  7. %matplotlib inline
  8.  
  9.  
  10. features = np.array([0.8,0.9,1.0,1.1,1.4,\
  11. 1.4,1.5,1.6,1.8,2.0,2.4,2.5,2.7,3.2,3.5])
  12. target = np.array([70,83,74,93,89,58,85,114,95,100,138,111,124,161,172])
  13.  
  14. plt.plot(features,target,'o', markersize=10)
  15. plt.show()
  16.  
  17. def cost(t0,t1):
  18. return (np.sum(((features*t1 +t0)- target)**2))/(2*len(features))
  19.  
  20. def cost_del_t0(t0,t1):
  21. return np.sum(((features*t1 +t0)- target))/len(features)
  22.  
  23. def cost_del_t1(t0,t1):
  24. return np.sum((features*t0) + (features**2)*t1\
  25. - features*target)/len(features)
  26.  
  27.  
  28. #gradient Descent fixed alpha
  29. def gra_de1(alpha, times, inicial0, inicial1):
  30. i0 = inicial0
  31. i1 = inicial1
  32. for i in range(times):
  33. temp0 = i0 - alpha*cost_del_t0(i0,i1)
  34. temp1 = i1 - alpha*cost_del_t1(i0,i1)
  35. i0 = temp0
  36. i1 = temp1
  37. return i0,i1
  38.  
  39.  
  40.  
  41. #gradient Descent decreasing alpha
  42. def gra_de2(alpha, times, inicial0, inicial1):
  43. i0 = inicial0
  44. i1 = inicial1
  45. for i in range(times):
  46. alpha = alpha - alpha*(i/(times-1))
  47. temp0 = i0 - alpha*cost_del_t0(i0,i1)
  48. temp1 = i1 - alpha*cost_del_t1(i0,i1)
  49. i0 = temp0
  50. i1 = temp1
  51. return i0,i1
  52.  
  53.  
  54. test1 = gra_de1(0.3, 500,0,0)
  55.  
  56. test2 = gra_de2(0.6, 500,0,0)
  57.  
  58. def hypothesis1(x):
  59. return test1[0] + test1[1]*x
  60.  
  61. def hypothesis2(x):
  62. return test2[0] + test2[1]*x
  63.  
  64. plt.plot(features, hypothesis1(features),\
  65. features,hypothesis2(features),features,target,'o', markersize=10)
  66. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement