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.
What runs in CodeSplash
- Deep neural network (torch MLP) Verified in Python and R
- XGBoost Verified in Python and R
- Neural network (MLP) Verified in Python and R
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
Walk downhill
ReadTraining picks the parameters that lower a loss . For a big model you can't solve that directly, so you start somewhere and repeat one step:
points uphill, so you step the opposite way. 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.
Too fast
ExploreOn 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?
Surface
Optimizer
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 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.
What sets the limit?
PredictPredict first
On this bowl, gradient descent is stable for learning rates below stretch. You stretch the bowl from 20 to 100. What happens to the largest stable learning rate?
Reveal
It's lower: from to . Steep walls demand small steps, and those small steps crawl along the flat floor. That's why stretched surfaces train slowly.
Scaling reshapes the surface
ReadUnscaled 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.
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?
Surface
Optimizer
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 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.
Who uses it?
Read| Learner | How it trains |
|---|---|
| Linear / logistic regression | Exact solution or Newton steps, no learning rate |
| Neural network (MLP) | Quasi-Newton steps; a small network with an L2 penalty |
| Deep neural network | Adam with mini-batches |
| Boosting | Each 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.
Check your understanding
CheckpointCheck 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 stretch. What's the limit when the stretch is 50?
Show the answer
Answer: 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.
Where you'll meet it
In the appIn 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.
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))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")
}
}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