Understanding gradient descent from scratch
The intuition
Imagine standing on a foggy hill and wanting to reach the valley. You can’t see far, but you can feel which way the ground slopes under your feet. Gradient descent is exactly that: take a small step in the steepest downhill direction, then repeat.
The update rule
The gradient of the loss L(w) tells you the steepest way up, so we go the other way:
w ← w − η ∇L(w)
η (eta) is the learning rate — how big each step is.
In NumPy
import numpy as np
def gradient_descent(X, y, lr=0.01, epochs=1000):
n, d = X.shape
w = np.zeros(d)
for _ in range(epochs):
grad = X.T @ (X @ w - y) / n # gradient of mean squared error
w -= lr * grad
return w
Choosing the learning rate
Too small and you walk forever; too large and you overshoot the valley. Start with 0.01, plot the loss, and adjust.
The gradient tells you which way is up. Go the other way, a little at a time.
Comments