Skip to content

Instantly share code, notes, and snippets.

@MyRibbonApps
Last active Sep 22, 2021
Embed
What would you like to do?
final_file
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
data = pd.read_csv('data.csv')
# print(data)
def cost_function(m, b, points):
the_total_error = 0
sum_error = 0
for i in range(len(points)):
x = points.iloc[i].weight
y = points.iloc[i].height
the_total_error += (y - (m * x + b)) ** 2
sum_error += the_total_error
print(sum_error)
return sum_error
def gradient_descent(m_now, b_now, points, L):
the_slope_of_thecost_depending_on_m = 0
the_slope_of_thecost_depending_on_b = 0
n = len(points)
for i in range(n):
x = points.iloc[i].weight
y = points.iloc[i].height
the_slope_of_thecost_depending_on_m += - (2/n) * x * (y - (m_now * x + b_now))
the_slope_of_thecost_depending_on_b += - (2/n) * (y - (m_now * x + b_now))
m = m_now - L * the_slope_of_thecost_depending_on_m
b = b_now - the_slope_of_thecost_depending_on_b * L
return m, b
m = 0
b = 0
Learning_rate = 0.001
times_to_iterate = 10000
#Here we calculate the cost, but it's not needed becuase the gradient descent do that basically for us.
# for i in range(-2, 2):
# c = cost_function(i, i, data)
# print("The Error")
# print(c)
for i in range(times_to_iterate):
m, b = gradient_descent(m, b, data, Learning_rate)
print(f"m AND b: {m, b}")
plt.scatter(data['weight'], data['height'])
plt.plot(list(range(0, 5)), [m * x + b for x in range(0 , 5)], color="red")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment