Python ML Gradient Descent from Scratch
Gradient descent finds the best line by walking downhill. It starts with a bad guess and takes small steps toward smaller errors.
One downhill step
The errors point the way. The slope moves against the average error times x.
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([1.0, 3.0, 5.0, 7.0, 9.0])
slope = 0.0
intercept = 0.0
error = slope * x + intercept - y
slope = slope - 0.1 * np.mean(error * x) * 2
intercept = intercept - 0.1 * np.mean(error) * 2
print(round(float(slope), 4))
print(round(float(intercept), 4))A small rate crawls
Ten steps at a rate of 0.01 barely move the slope. The loss is still far from zero.
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([1.0, 3.0, 5.0, 7.0, 9.0])
slope = 0.0
intercept = 0.0
for _ in range(10):
error = slope * x + intercept - y
slope = slope - 0.01 * np.mean(error * x) * 2
intercept = intercept - 0.01 * np.mean(error) * 2
print(round(float(slope), 4))
print(round(float(np.mean((slope * x + intercept - y) ** 2)), 4))A big rate explodes
Ten steps at a rate of 0.5 throw the slope far past the answer. The numbers blow up.
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([1.0, 3.0, 5.0, 7.0, 9.0])
slope = 0.0
intercept = 0.0
for _ in range(10):
error = slope * x + intercept - y
slope = slope - 0.5 * np.mean(error * x) * 2
intercept = intercept - 0.5 * np.mean(error) * 2
print(f"{float(slope):.6g}")Example
import numpy as np
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([1.0, 3.0, 5.0, 7.0, 9.0])
def run(rate, steps=100):
slope = 0.0
intercept = 0.0
for _ in range(steps):
error = slope * x + intercept - y
slope = slope - rate * np.mean(error * x) * 2
intercept = intercept - rate * np.mean(error) * 2
loss = np.mean((slope * x + intercept - y) ** 2)
return slope, intercept, loss
for rate in [0.01, 0.1, 0.5]:
slope, intercept, loss = run(rate)
print("Rate:", rate, "Slope:", round(float(slope), 4), "Intercept:", round(float(intercept), 4), "Loss:", f"{float(loss):.6g}")Key points
- Gradient descent: a loop that improves the slope and intercept step by step
- Loss: one number that says how wrong the current line is
- Gradient: the direction and size of the next step, read from the errors
- Learning rate: how big each step is
- Use a small learning rate to walk downhill slowly and safely
- A learning rate that is too big jumps past the bottom and diverges
- A learning rate that is too small crawls and needs many steps
In this example, five points sit on the line y equals 2x plus 1. The run() helper starts the slope and intercept at zero and takes 100 downhill steps. A rate of 0.01 crawls to a loss of 0.00714777, still far from the answer. A rate of 0.1 lands almost exactly on slope 2 and intercept 1, with a loss near zero. A rate of 0.5 diverges, and the slope flies off to a huge negative number. The right rate walks downhill. The wrong rate either crawls or explodes.
Note
The points in this lesson sit exactly on the line y equals 2x plus 1, so the true slope is 2 and the true intercept is 1.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What happens when the learning rate is far too big?