Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- __author__ = "Bharat Kul Ratan"
- import random
- import matplotlib.pyplot as plt
- import seaborn as sns
- import pandas as pd
- def plot_points():
- x_coordinates = pd.Series(random.sample(range(1, 20), 10), name='x_axis')
- y_coordinates = list(map(lambda x: 2*x+3, x_coordinates))
- # Add a random value, so that y values does not lie on the equation exactly
- y_coordinates = pd.Series([y + random.randint(-5, 5) for y in y_coordinates], name='y_axis')
- x_and_y = [{'x': item[0], 'y': item[1]} for item in zip(x_coordinates, y_coordinates)]
- sns.regplot(x=x_coordinates, y=y_coordinates, fit_reg=False)
- plt.show()
- return x_and_y
- def mse(slope, intercept, points):
- error = 0
- for item in points:
- predicted = item['x'] * slope + intercept
- output = item['y']
- error += ((predicted - output) ** 2)
- error /= len(points)
- return error
- def update_weights(slope, intercept, learning_rate, points):
- m_update = 0
- c_update = 0
- for item in points:
- m_update += -2 * item['x'] * (item['y'] - (slope * item['x'] + intercept))
- c_update += -2 * (item['y'] - (slope * item['x'] + intercept))
- slope -= (m_update/float(len(points))) * learning_rate
- intercept -= (c_update/float(len(points))) * learning_rate
- return slope, intercept
- def run():
- x_and_y = plot_points()
- check_values = 1
- m = 1
- c = 0
- for i in range(100000):
- mse_error = mse(m, c, x_and_y)
- if i == check_values:
- print('slope=', round(m, 3), 'intercept=', round(c, 3), 'mse=', round(mse_error, 3))
- check_values *= 10
- m, c = update_weights(m, c, 0.001, x_and_y)
- if __name__ == '__main__':
- run()
Add Comment
Please, Sign In to add comment