Lessons › Projects
Gradient descent from scratch
Your own training loop in plain NumPy that finds the best straight line, plus a chart comparing learning rates.
No setup needed. Run every step in your browser on Gradient Lab, or download it.
Open the notebookLevel: Beginner · Time: 30 min · You’ll practise: loss functions, gradients, learning rate, divergence
Steps
1. Make some data: price = 3 x size + 4, plus noise
Generate 50 points from a known rule (price = 3 × size + 4) plus random noise, so you can check whether training finds the truth.
rng = np.random.default_rng(0) x = rng.uniform(0, 10, 50) y = 3 * x + 4 + rng.normal(0, 2, 50)
2. The model, the loss and the gradient
Write the model (a line), the loss (mean squared error) and the gradient: how the loss changes if you nudge w or b.
def predict(w, b, x):
return w * x + b
def mse(w, b):
return np.mean((y - predict(w, b, x)) ** 2)
def gradients(w, b):
error = predict(w, b, x) - y
dw = 2 * np.mean(error * x) # slope of the loss with respect to w
db = 2 * np.mean(error) # slope of the loss with respect to b
return dw, db3. Walk downhill
The training loop: compute the gradient, step against it, repeat. This is the exact loop from the Gradient descent lesson.
def train(learning_rate, steps=2000):
w, b, history = 0.0, 0.0, []
for step in range(steps):
dw, db = gradients(w, b)
w -= learning_rate * dw
b -= learning_rate * db
history.append(mse(w, b))
return w, b, history
w, b, history = train(learning_rate=0.01)
print(f"Learned: price = {w:.2f} x size + {b:.2f} (truth: 3 x size + 4)")
print(f"Loss went from {history[0]:.1f} to {history[-1]:.2f}")4. Try different learning rates
Train with three learning rates and plot the loss curves on one chart.
plt.figure(figsize=(7, 4))
for lr in [0.001, 0.005, 0.02]:
_, _, h = train(lr)
plt.plot(h, label=f"learning rate {lr}")
print(f"learning rate {lr:<6} final loss {h[-1]:.2f}")
plt.yscale("log"); plt.xlabel("step"); plt.ylabel("loss (MSE)"); plt.legend(); plt.title("Gradient descent")
plt.tight_layout(); plt.savefig("loss_curves.png")
print("Saved loss_curves.png")5. What happens if the learning rate is too big?
Push the learning rate too high and watch the loss explode instead of shrinking.
_, _, h = train(0.04, steps=20)
print("learning rate 0.04, first 5 losses:", [round(v) for v in h[:5]], "... it blows up!")Expected output
$ python gradient_descent.py Learned: price = 3.10 x size + 3.51 (truth: 3 x size + 4) Loss went from 38.0 to 3.97 learning rate 0.001 final loss 4.31 learning rate 0.005 final loss 3.97 learning rate 0.02 final loss 3.97 Saved loss_curves.png learning rate 0.04, first 5 losses: [1832, 7034, 27052, 104082, 400499] ... it blows up!
Stretch goals
- Add momentum to the update and compare how fast it converges.
- Fit a curve instead: add a w2 × x² term and its gradient.
- Plot the line on top of the data points after every 100 steps to watch it settle.