Stop 07 · Supervised Learning: RegressionTopics · 4/8

Gradient Descent From Scratch

Part of the Machine Learning Roadmap

In short

Almost every model, from linear regression to giant neural networks, learns the same way: guess, measure the error, nudge the weights downhill, repeat. Writing gradient descent yourself once makes that loop crystal clear.

Implementing gradient descent yourself for linear regression shows exactly how models learn: predict, measure the error, compute gradients, nudge the weights and repeat. Batch, stochastic and mini-batch versions trade accuracy of each step against speed.

The jaadu carefully steps down a misty green hillside, feeling the slope with one foot while a valley lake glows faintly below.

Think of it like this

Walking down a foggy hill

You're on a hill near Lonavala in thick monsoon fog and want to reach the valley. You can't see the bottom, but you can feel which way the ground slopes under your feet. So you take a step downhill, feel again, step again. The slope is the gradient, the size of your step is the learning rate, and the valley is the lowest error.

Watch it happen

One step of gradient descent

Predict
Error
Gradient
Update
Repeat

1/5Use the current weight and bias to predict y for every row: y_hat = w·x + b.

The big ideas

What you need to know

The gradient points uphill

It's the direction where the loss grows fastest. Subtracting it moves you downhill towards lower loss.

Learning rate is the step size

Too small and training crawls. Too big and you overshoot the valley and the loss grows or bounces.

Batch, stochastic, mini-batch

Batch uses all rows per step (smooth but slow), stochastic uses one row (fast but noisy), mini-batch uses, say, 32. Mini-batch is the usual choice.

Scale features first

If one feature is in lakhs and another in single digits, the loss surface is a long narrow valley and descent zig-zags.

See it in code

Walk through the code

python
1import numpy as np2 3rng = np.random.default_rng(0)4x = rng.uniform(0, 10, 200)                    # e.g. years of experience5y = 3.0 * x + 5.0 + rng.normal(0, 1, 200)      # true w = 3, b = 56 7w, b = 0.0, 0.08lr = 0.019 10for epoch in range(2000):11    y_hat = w * x + b12    error = y_hat - y13    loss = np.mean(error ** 2)14 15    dw = 2 * np.mean(error * x)16    db = 2 * np.mean(error)17 18    w -= lr * dw19    b -= lr * db20 21    if epoch % 500 == 0:22        print(epoch, round(loss, 3))23 24print(round(w, 2), round(b, 2))                # close to 3 and 5

1/6Fake data with a known answer, so we can check the result.

Batch gradient descent for simple linear regression, with nothing but NumPy.

Save yourself the pain

Common mistakes

Oops

Picking a large learning rate and seeing the loss turn into nan.

Do this instead

Start around 0.01 or 0.001, plot the loss per epoch, and only increase if it falls smoothly but slowly.

Oops

Updating w, then using the new w to compute b's gradient in the same step.

Do this instead

Compute all gradients from the same predictions first, then update every parameter together.

Your mission

Make it mini-batch

~30 min

Quick check

Your loss gets bigger every epoch and soon becomes nan. What is the most likely fix?

Go deeper

  1. 1Write gradient descent for a one-feature linear regression in NumPy in under 25 lines.
  2. 2Plot the loss over iterations for three different learning rates.
  3. 3Check your final weights against scikit-learn's LinearRegression.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge