Gradient Descent

Updated · 7 min read
hardPython 3.13aideep-learninggradient-descentlearning-rateoptimization

Gradient descent is the method almost every neural network uses to learn. It starts with some weights, measures the loss (how wrong the predictions are), computes the gradient (which direction makes the loss grow fastest), and takes a small step the opposite way. Repeating this walks the weights downhill until the loss stops falling.

The size of each step is the learning rate, the single most important setting in training. This lesson uses the derivatives from "Derivatives and Gradients".

The Update Rule

PieceDescription
LossIt is used to measure how wrong the model is; here mean squared error
GradientThe slope of the loss for each weight; it points uphill
Learning rateIt is used to set how big each step is
Updateweight = weight - learning_rate × gradient, for every weight
Step (iteration)One update of all the weights

Example: Fitting a Line Step by Step

This program fits price = w × size + b to the 200 houses by gradient descent, starting from a flat line at zero. This program uses houses.csv from "Linear Regression".

Python
import numpy as np
import pandas as pd
 
houses = pd.read_csv("houses.csv")
x, y = houses["size"].to_numpy(), houses["price"].to_numpy()   # thousands of sq ft, thousands of dollars
 
w, b = 0.0, 0.0                       # start with a flat line at zero
learning_rate = 0.1
for step in range(1, 1001):
    error = (w * x + b) - y
    loss = np.mean(error ** 2)        # mean squared error
    grad_w = np.mean(2 * error * x)   # slope of the loss with respect to w
    grad_b = np.mean(2 * error)       # slope of the loss with respect to b
    w -= learning_rate * grad_w       # step downhill
    b -= learning_rate * grad_b
    if step in (1, 10, 100, 1000):
        print(f"step {step:4}: loss {loss:9.1f}  w {w:6.1f}  b {b:6.1f}")
 
print("Exact best fit (np.polyfit):", np.polyfit(x, y, 1).round(1))
Output
step    1: loss  155850.3  w  186.2  b   76.0
step   10: loss    1325.7  w  141.6  b   59.6
step  100: loss    1317.3  w  138.6  b   66.9
step 1000: loss    1316.8  w  137.7  b   69.1
Exact best fit (np.polyfit): [137.7  69.1]
Step downhill on the loss; the learning rate sets the stride

Explanation:

  • The gradients are the derivatives of the mean squared error: mean(2 × error × x) for w and mean(2 × error) for b. A positive gradient means "increasing this weight increases the loss", so the update subtracts it.
  • Step 1 has a huge loss (155,850) because a line at zero predicts every house costs $0. The first step jumps w to 186.2, overshooting a little.
  • By step 10 the loss has fallen to 1,325.7, and the remaining steps fine-tune.
  • After 1,000 steps, w = 137.7 and b = 69.1, exactly what np.polyfit computes directly. Gradient descent found the best line without being told the formula.

For a straight line there's a direct formula, so gradient descent isn't needed. Neural networks have no such formula, and gradient descent is how they're trained.

Example: Choosing the Learning Rate

This program runs 100 steps with four learning rates. This program uses houses.csv from "Linear Regression".

Python
import numpy as np
import pandas as pd
 
houses = pd.read_csv("houses.csv")
x, y = houses["size"].to_numpy(), houses["price"].to_numpy()
 
def train(learning_rate, steps=100):
    w, b = 0.0, 0.0
    for _ in range(steps):
        error = (w * x + b) - y
        w -= learning_rate * np.mean(2 * error * x)
        b -= learning_rate * np.mean(2 * error)
    return np.mean(((w * x + b) - y) ** 2)
 
for learning_rate in [0.001, 0.01, 0.1, 0.2]:
    loss = train(learning_rate)
    print(f"learning rate {learning_rate:<5}: loss after 100 steps", f"{loss:,.1f}" if loss < 1e6 else f"{loss:.1e} (blew up)")
Output
learning rate 0.001: loss after 100 steps 12,399.0
learning rate 0.01 : loss after 100 steps 1,325.4
learning rate 0.1  : loss after 100 steps 1,317.3
learning rate 0.2  : loss after 100 steps 1.1e+47 (blew up)

Explanation:

Learning rateWhat happenedWhy
0.001Loss still 12,399 after 100 stepsSteps too small: correct direction, far too slow
0.011,325.4, close to the bestGood, a little slower
0.11,317.3, the best possible after 100 stepsWell chosen
0.2Blew up to 1.1 × 10⁴⁷Steps too big: each one overshoots the valley further than the last

The gap between 0.1 working and 0.2 exploding is small, which is typical. Too big is worse than too small, so when training fails with a loss that grows or becomes nan, lower the learning rate first.

Kinds of Gradient Descent

KindGradient computed fromTrade-off
BatchAll the training dataAccurate steps, but slow on big data; used in this lesson
Stochastic (SGD)One exampleFast, noisy steps
Mini-batchA batch of, say, 32 examplesThe usual choice for neural networks
Adam and other optimizersMini-batches, with adaptive step sizes per weightOften trains faster with less tuning (see "Training a Network in PyTorch")

Common Mistakes

Learning rate too high. The loss grows or becomes nan; lower it.

Learning rate too low. The loss falls painfully slowly; raise it.

Stopping too early. Watch the loss curve and stop when it levels off, or when the validation loss starts rising.

Unscaled features. Features on very different scales make one learning rate too big for some weights and too small for others; scale them first.

Interview Corner

How does gradient descent work?

It repeatedly computes the gradient of the loss with respect to each parameter and moves each parameter a small step in the opposite direction, scaled by the learning rate, until the loss stops improving.

What happens if the learning rate is too large or too small?

Too large and training overshoots, oscillates or diverges; too small and it converges very slowly or stalls.

Practice

Exercise: count the steps. Change the first program to stop when the loss improves by less than 0.01 between steps. How many steps does learning rate 0.1 need? And 0.01?

Check your understanding:

  1. Why does the update subtract the gradient?
  2. Why was the loss so large at step 1?
  3. What happened with learning rate 0.2, and why?

Quick check: gradient descent

4 questions
1What does the gradient point toward?
2Where did gradient descent end up after 1,000 steps?
3What did learning rate 0.001 do?
4What's the first thing to try when the loss becomes nan?

Key Takeaways

Quick reference

NeedCode
Loss (mean squared error)np.mean((predictions - y) ** 2)
Gradient for a slopenp.mean(2 * error * x)
Updatew -= learning_rate * grad_w

Was this tutorial helpful?

Lesson 135 of 186