Lesson 4 of 7 · 2 min
Implementation From Scratch
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.array([5, 7, 9, 11, 13])
def gradient_descent(x, y):
m_curr = b_curr = 0
learning_rate = 0.08
iterations = 10000
n = len(x)
for i in range(iterations):
y_predicted = m_curr * x + b_curr
cost = (1/n) * sum((y - y_predicted)**2)
md = -(2/n) * sum(x * (y - y_predicted))
bd = -(2/n) * sum(y - y_predicted)
m_curr = m_curr - learning_rate * md
b_curr = b_curr - learning_rate * bd
if i % 1000 == 0:
print(f"i={i}: m={m_curr:.4f}, b={b_curr:.4f}, cost={cost:.6f}")
gradient_descent(x, y)
# Output: # i=0: m=4.9600, b=1.4400, cost=89.000000 # i=1000: m=1.9981, b=3.0054, cost=0.000019 # i=2000: m=2.0000, b=3.0000, cost=0.000000 # i=9000: m=2.0000, b=3.0000, cost=0.000000
