Guest User

Untitled

a guest
Jul 7th, 2018
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. __author__ = "Bharat Kul Ratan"
  2.  
  3. import random
  4. import matplotlib.pyplot as plt
  5. import seaborn as sns
  6. import pandas as pd
  7.  
  8.  
  9. def plot_points():
  10. x_coordinates = pd.Series(random.sample(range(1, 20), 10), name='x_axis')
  11. y_coordinates = list(map(lambda x: 2*x+3, x_coordinates))
  12. # Add a random value, so that y values does not lie on the equation exactly
  13. y_coordinates = pd.Series([y + random.randint(-5, 5) for y in y_coordinates], name='y_axis')
  14.  
  15. x_and_y = [{'x': item[0], 'y': item[1]} for item in zip(x_coordinates, y_coordinates)]
  16. sns.regplot(x=x_coordinates, y=y_coordinates, fit_reg=False)
  17. plt.show()
  18. return x_and_y
  19.  
  20.  
  21. def mse(slope, intercept, points):
  22. error = 0
  23. for item in points:
  24. predicted = item['x'] * slope + intercept
  25. output = item['y']
  26. error += ((predicted - output) ** 2)
  27. error /= len(points)
  28. return error
  29.  
  30.  
  31. def update_weights(slope, intercept, learning_rate, points):
  32. m_update = 0
  33. c_update = 0
  34. for item in points:
  35. m_update += -2 * item['x'] * (item['y'] - (slope * item['x'] + intercept))
  36. c_update += -2 * (item['y'] - (slope * item['x'] + intercept))
  37.  
  38. slope -= (m_update/float(len(points))) * learning_rate
  39. intercept -= (c_update/float(len(points))) * learning_rate
  40. return slope, intercept
  41.  
  42.  
  43. def run():
  44. x_and_y = plot_points()
  45. check_values = 1
  46. m = 1
  47. c = 0
  48. for i in range(100000):
  49. mse_error = mse(m, c, x_and_y)
  50. if i == check_values:
  51. print('slope=', round(m, 3), 'intercept=', round(c, 3), 'mse=', round(mse_error, 3))
  52. check_values *= 10
  53. m, c = update_weights(m, c, 0.001, x_and_y)
  54.  
  55.  
  56. if __name__ == '__main__':
  57. run()
Add Comment
Please, Sign In to add comment