Skip to content

Gradient descent: how models learn

Follow the downhill direction of the loss. See why the learning rate decides whether training works at all, why scaling helps, and which learners use this idea.

Applied ~12 min9 steps

What runs in CodeSplash

You will be able to

  • Write the gradient descent update and name each term
  • Explain why the stable learning rate depends on the surface's shape
  • Say what momentum, Adam and mini-batches change

Read first

01

Walk downhill

Read

Training picks the parameters θ\theta that lower a loss L(θ)L(\theta). For a big model you can't solve that directly, so you start somewhere and repeat one step:

θ←θ−η ∇L(θ)\theta \leftarrow \theta - \eta\,\nabla L(\theta)

∇L\nabla L points uphill, so you step the opposite way. η\eta is the learning rateLearning rateHow big a step each boosting round (or gradient update) takes; smaller is steadier but needs more rounds.: how far each step goes.

That's nearly all of gradient descentGradient descentTraining by repeatedly stepping parameters against the gradient of the loss, with a step size set by the learning rate.. Everything else is about making it safer and faster.

02

Too fast

Explore

On the Stretched bowl, raise Learning rate until the path shoots off, then lower it until it creeps. Read Stable below. Now change Stretch of the bowl.

DExplorable · Gradient descent on a loss surface

Why does the learning rate decide whether training works at all?

With this learning rate and this surface, what will the path do?

How sure?

Surface

Optimizer

0.050
60
20
0.0

Orange dot: the start. Blue dot: where the path has reached. Darker shading is higher loss.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Then try Momentum and Adam with the check: reach the minimum of a heavily stretched bowl in at most 60 steps.

03

What sets the limit?

Predict

Predict first

On this bowl, gradient descent is stable for learning rates below 2÷2 \div stretch. You stretch the bowl from 20 to 100. What happens to the largest stable learning rate?

It stays the sameIt's higherIt's lower
Reveal

It's lower: from 2/202/20 to 2/1002/100. Steep walls demand small steps, and those small steps crawl along the flat floor. That's why stretched surfaces train slowly.

04

Scaling reshapes the surface

Read

Unscaled features stretch the loss surface. A column in the thousands next to one near zero gives a long, narrow ravine.

Standardizing makes the bowl rounder, so a single learning rate suits all directions. That's one reason neural network and linear model cards in the gallery say standardizes inputs.

05

Faster variations

Explore
  • Mini-batches: estimate the gradient from a sample of rows. Noisy, cheap, and the noise can help on rough surfaces.
  • Momentum: keep part of the last step, to roll through ravines.
  • Adam: adapt the step size for each parameter from its recent gradients.

DExplorable · Gradient descent on a loss surface

Why does the learning rate decide whether training works at all?

With this learning rate and this surface, what will the path do?

How sure?

Surface

Optimizer

0.050
60
20
1.0

Orange dot: the start. Blue dot: where the path has reached. Darker shading is higher loss.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Switch Optimizer, then raise and lower Gradient noise (mini-batches) and Learning rate. A smaller rate cuts the jitter near the end.

06

Who uses it?

Read
LearnerHow it trains
Linear / logistic regressionExact solution or Newton steps, no learning rate
Neural network (MLP)Quasi-Newton steps; a small network with an L2 penalty
Deep neural networkAdam with mini-batches
BoostingEach tree is a downhill step, shrunk by Learning rate

On Pima, cross-validated AUC is 0.856 for the small network, 0.837 for the Adam-trained one on 3 folds, and 0.843 for boosting.

07

Check your understanding

Checkpoint

Check yourself

Why is there a minus sign in the update?

Show the answer

Answer: a

Stepping along the negative gradient is the steepest local descent.

Check yourself

On the explorable's bowl, the stable limit for gradient descent is 2÷2 \div stretch. What's the limit when the stretch is 50?

Show the answer

Answer: 0.04

2/50=0.042/50 = 0.04. Above it, each step overshoots further than the last.

Check yourself

Training loss goes up and then to infinity. What's the first thing to try?

Show the answer

Answer: b

Exploding loss is the signature of a learning rate past the stable limit. More epochs only explode further.

08

Where you'll meet it

In the app

In the Learners step, select Deep neural network (torch MLP) and open Hyperparameters. Learning rate, Batch size and Epochs are there. Boosters show their own Learning rate. When the loss is well behaved, try Tune… rather than hand-picking.

Python
import numpy as np
import pandas as pd

df = pd.read_csv("pima.csv")
X = df.drop(columns="diabetic").to_numpy(float)
X = (X - X.mean(0)) / X.std(0)
X = np.c_[np.ones(len(X)), X]
y = df["diabetic"].to_numpy(float)
beta = np.zeros(X.shape[1])
for step in range(1, 501):
    p = 1 / (1 + np.exp(-X @ beta))
    beta -= 0.5 * X.T @ (p - y) / len(y)
    if step in (1, 10, 100, 500):
        loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
        print(step, round(loss, 4))
R
df <- rbind(MASS::Pima.tr, MASS::Pima.te)
X <- cbind(1, scale(as.matrix(df[, setdiff(names(df), "type")])))
y <- as.numeric(df$type == "Yes")
beta <- rep(0, ncol(X))
for (step in 1:500) {
  p <- as.vector(1 / (1 + exp(-X %*% beta)))
  beta <- beta - 0.5 * as.vector(t(X) %*% (p - y)) / length(y)
  if (step %in% c(1, 10, 100, 500)) {
    cat(step, round(-mean(y * log(p) + (1 - y) * log(1 - p)), 4), "\n")
  }
}
09

Recap

Recap
  • Gradient descent repeatedly steps against the gradient of the loss.
  • The learning rate must suit the surface's steepest direction, and scaling makes that easier.
  • Momentum, Adam and mini-batches are refinements of the same idea.

Concepts in this lesson