Simple Algorithm
Machine Learning · Initialization · 17 min

Optimization: How Models Learn

Gradient descent and its relatives: turning a loss into parameters.

Every model in this course, from a straight line to a neural network with millions of weights, is trained the same way: measure how wrong its predictions are, then nudge its parameters to make them a little less wrong, over and over. This lesson shows you that loop, the one knob that makes or breaks it, and the noisy shortcut that makes it fast enough for huge datasets.

What you’ll learn

  • Explain training as minimizing a loss over a model's parameters, and read a loss landscape.
  • Take gradient descent steps by hand, and predict how the learning rate changes what happens.
  • Recognize local minima and saddle points, and tell a convex landscape from a nonconvex one.
  • Explain why stochastic gradient descent uses small random batches, and what its noise does.
  • Describe what momentum and Adam add to plain gradient descent.

Learning means minimizing

A model has knobs called parameters. To predict a house's price from its floor area xx with a straight line y^=wx+b\hat y = wx + b, the knobs are the slope ww and the intercept bb. Each setting of the knobs gives different predictions, some good and some bad.

To compare settings you need a single number that says how bad the predictions are on the training set: the loss. For predicting numbers, the usual choice is the average squared error:

L(w,b)=1n∑i=1n(yi−(wxi+b))2L(w, b) = \frac{1}{n}\sum_{i=1}^{n}\big(y_i - (w x_i + b)\big)^2
yiy_i is the true price of house ii and wxi+bwx_i + b the line's prediction. Every pair (w,b)(w, b) gets one number, and lower is better.

Now picture every possible pair (w,b)(w, b) as a point on a map, and the loss as the height of the ground at that point. This surface is the loss landscape, and training means finding its lowest point. Finding the lowest point of a function is called optimization.

Downhill in the fog

Imagine a hiker on a mountain in thick fog, trying to reach the valley. She cannot see the valley, but she can feel which way the ground tilts under her feet. A sensible plan: take a step in the steepest downhill direction, feel the slope again, and repeat.

That plan is gradient descent. For each parameter, the slope says how fast the loss changes when you nudge that parameter alone. The list of all these slopes is the gradient, written ∇L\nabla L. It points in the direction of steepest uphill, so gradient descent steps the opposite way:

θnew=θ−η ∇L(θ)\boldsymbol\theta_{\text{new}} = \boldsymbol\theta - \eta\,\nabla L(\boldsymbol\theta)
θ\boldsymbol\theta is the list of all parameters, such as (w,b)(w, b). The learning rate η\eta ("eta") sets how far to step for a given slope.

Try it on the simplest landscape, L(x)=x2L(x) = x^2, whose slope at xx is 2x2x. Start at x=3x = 3 with η=0.1\eta = 0.1:

  1. The slope is 2×3=62 \times 3 = 6, so step by 0.1×6=0.60.1 \times 6 = 0.6: the new xx is 2.42.4.
  2. The slope is now 4.84.8, the step 0.480.48, the new xx 1.921.92.
  3. Then 1.5361.536, 1.2291.229, … Each step multiplies xx by 0.80.8.

Notice that the steps shrink on their own: near the bottom the ground is nearly flat, so the slope, and with it the step, is small.

Predict before you look

Same landscape L(x)=x2L(x) = x^2 and the same start x=3x = 3, but now the learning rate is η=0.5\eta = 0.5. Where are you after one step?

Show the answer

0

The slope at 33 is 66, so the step is 0.5×6=30.5 \times 6 = 3 and you land at x=0x = 0: the very bottom, in one step. On this bowl η=0.5\eta = 0.5 happens to be perfect. Real landscapes have no single perfect step, but there is always a range of sensible ones, as the next step shows.

The learning rate: too small, too large

The learning rate is the most important setting in training. Too small and you crawl; too large and you overshoot the valley, land higher on the opposite wall, and can be flung further out with every step. On the round bowl L(x,y)=x2+y2L(x, y) = x^2 + y^2 each step multiplies the distance to the bottom by ∣1−2η∣|1 - 2\eta|, so you can predict exactly what will happen.

Check your understanding

On the bowl L(x,y)=x2+y2L(x, y) = x^2 + y^2, which learning rate makes gradient descent bounce between two points forever, never getting closer to the bottom?

  1. η=0.5\eta = 0.5
  2. η=0.9\eta = 0.9
  3. η=1\eta = 1
  4. η=2\eta = 2
Show the answer

C. η=1\eta = 1

Each step multiplies the position by 1−2η1 - 2\eta. At η=1\eta = 1 that factor is −1-1: the point jumps to the mirror-image spot on the other side of the bowl, then back again, forever.

Valleys, saddles and false bottoms

Gradient descent stops wherever the slope is zero, at a stationary point. On the bowl there is only one, the bottom. Real landscapes have several kinds:

  • a global minimum, the lowest point of all;
  • a local minimum, lower than everything nearby but not the lowest: a false bottom;
  • a saddle point, flat but downhill in some directions and uphill in others, like a mountain pass.
PropertyConvex landscapeNonconvex landscape
ShapeOne bowl: the straight segment between any two points of the graph lies on or above itHills, valleys, ridges and saddles
Stationary pointsEvery local minimum is a global minimumCan have false bottoms and saddles
What gradient descent findsThe lowest value, with a small enough learning rateSome stationary point, depending on where it starts
ExamplesLeast squares for a line; logistic regressionNeural networks; clustering with k-means
Convexity is the property that makes optimization easy. The landscape in step 1 was a convex bowl, which is why every start led to the same line.
Think first A neural network's loss is wildly nonconvex, with countless stationary points. Yet gradient descent trains such networks well again and again. How can that be?

It is only partly understood, as of the mid-2020s. One argument: in very high dimensions, a flat point is far more likely to have some downhill direction (a saddle) than none, and gradient descent, nudged by a little noise, slides off saddles. Large networks also seem to have many low-loss solutions, so landing in a good valley is enough. The Convergence lesson on nonconvex optimization proves when gradient descent escapes saddles, and shows nonconvex problems that provably have no false bottoms at all.

Stochastic gradient descent

The loss is an average over all nn training examples, so its gradient is an average too: one exact step means computing the slope contributed by every example. With ten million images, that is ten million gradient computations for a single step.

Stochastic gradient descent (SGD) cheats, cleverly. It picks a small random mini-batch of BB examples (typically a few dozen to a few thousand), averages their gradients, takes the step, and picks another batch. One pass through the whole training set is an epoch. Each step is far cheaper, and because the batch is random, the estimated gradient is right on average.

Predict before you look

A mini-batch of 100 examples gives a noisy gradient. How many examples per batch do you need to cut the typical size of the noise in half?

Show the answer

400 examples

The noise shrinks like 1/B1/\sqrt{B}, so halving it takes 4×4\times the batch: 400 examples, and four times the computation per step. Doubling the batch to 200 cuts the noise only by a factor 2≈1.4\sqrt2 \approx 1.4. These diminishing returns are why many cheap, noisy steps usually beat a few expensive, accurate ones.

Check your understanding

Why can SGD with batches of 100 train much faster than exact gradient descent on a dataset of ten million examples?

  1. Each SGD step points exactly downhill, so fewer steps are needed
  2. SGD needs to see each example only once in total
  3. SGD always uses a larger learning rate than gradient descent
  4. Each step costs 100 gradient computations instead of ten million, and the noisy direction is still right on average
Show the answer

D. Each step costs 100 gradient computations instead of ten million, and the noisy direction is still right on average

In the time gradient descent takes one exact step, SGD takes up to 100,000 cheap ones, each pointing downhill on average. Far from the minimum, many rough steps make much more progress than one precise one.

Momentum and Adam

Many landscapes contain long, narrow ravines: steep across, nearly flat along the floor. There the gradient points mostly across the ravine, so gradient descent zig-zags from wall to wall while crawling along the floor.

Momentum keeps a running velocity: each step adds the new gradient to a decaying memory of the previous ones, like a heavy ball rolling downhill. The back-and-forth components cancel out, while the steady push along the floor builds up speed. Adam (Kingma & Ba, 2015) also tracks the typical size of each parameter's recent gradients and divides each parameter's step by it, so steep and flat directions both make progress. Adam and its variant AdamW are, as of the mid-2020s, the usual default for training large neural networks.

MethodEach step usesWhat it fixes
Gradient descentthe exact gradient over all the datathe baseline: reliable but expensive per step
SGDa mini-batch estimate of the gradientcost: steps no longer grow with the dataset
SGD with momentuma running average of recent gradientszig-zagging in ravines; noise is averaged too
Adamrunning averages of gradients and of their squaresdirections with very different steepness

The road ahead

Every method in this lesson is a variation on one loop: measure the slope, step downhill, repeat. What changes is how the slope is estimated (all the data or a batch), how far to step (the learning rate and its schedule) and what to remember between steps (momentum, squared gradients).

Descent lessonWhat you will do there
Gradient DescentDerive the update from a Taylor expansion, prove it decreases the loss for a safe step size, see how the condition number controls the speed, and choose steps by line search.
Stochastic Gradient DescentShow that mini-batch gradients are unbiased with variance shrinking like 1/B1/B, derive the noise ball of constant steps, and turn it into practical learning-rate schedules.
Convexity & DualityLearn why convex problems are tractable, handle non-differentiable losses with subgradients, and use dual problems and Lagrange multipliers.
Adaptive & Second-Order MethodsTake apart AdaGrad, RMSProp and Adam, and use curvature directly with Newton's and quasi-Newton methods.
In the Descent lessons each idea gets its math and its algorithm. The Convergence lessons go further: convergence-rate proofs, Nesterov's acceleration, escaping saddle points, variance reduction and the theory of batch size.

Key takeaways

  • Training a model means minimizing a loss over its parameters. The loss landscape is the loss drawn as height above parameter space.
  • Gradient descent repeats θ←θ−η∇L(θ)\boldsymbol\theta \leftarrow \boldsymbol\theta - \eta\nabla L(\boldsymbol\theta). The gradient points steepest uphill, and the steps shrink as the ground flattens.
  • The learning rate η\eta makes or breaks training: too small crawls, too large overshoots and can blow up. On the bowl x2+y2x^2 + y^2, steps are stable exactly when η<1\eta < 1.
  • Gradient descent stops at any stationary point, including local minima and saddles. Convex losses have no false bottoms; neural networks' losses are nonconvex.
  • SGD estimates the gradient from a random mini-batch: cheap, noisy and right on average. A constant learning rate leaves it jittering in a noise ball; decaying the rate lets it settle.
  • Momentum averages away zig-zags in ravines, and Adam gives each parameter its own effective step size.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

At the current parameters, the gradient of the loss points…

  1. straight toward the global minimum
  2. in the direction in which the loss increases fastest
  3. in the direction in which the loss decreases fastest
  4. along a contour line, where the loss stays constant
Show the answer

B. in the direction in which the loss increases fastest

The gradient collects the slopes along every parameter and points steepest uphill. That is why gradient descent subtracts it: θ−η∇L(θ)\boldsymbol\theta - \eta\nabla L(\boldsymbol\theta) moves steepest downhill.

Question 2

Your training loss falls for two steps, then jumps up, and a few steps later it is astronomically large. What is the most likely fix?

  1. Lower the learning rate
  2. Raise the learning rate so it escapes faster
  3. Train for more epochs
  4. Use a model with fewer parameters
Show the answer

A. Lower the learning rate

A loss that grows without bound is the signature of steps that overshoot: each one lands higher on the far wall of the valley than where it started. A smaller learning rate shortens every step.

Question 3

Gradient descent has stopped moving: the gradient is essentially zero. What can you conclude?

  1. The parameters are at the global minimum of the loss
  2. The learning rate has dropped to zero
  3. The parameters are at a stationary point: a minimum, possibly only a local one, or a saddle
  4. The model has memorized the training set
Show the answer

C. The parameters are at a stationary point: a minimum, possibly only a local one, or a saddle

A zero gradient means the ground is flat, which happens at global minima, local minima and saddle points alike. Only for a convex loss does it guarantee the global minimum.

Question 4

With a constant learning rate, SGD's training loss stops improving and fluctuates above the minimum. Which change helps it settle closer?

  1. Raise the learning rate
  2. Reshuffle the data less often
  3. Use smaller mini-batches
  4. Lower the learning rate gradually as training goes on
Show the answer

D. Lower the learning rate gradually as training goes on

The fluctuations come from gradient noise multiplied by the step size. Shrinking the step over time (a decaying schedule) shrinks the jitter, which is the Robbins–Monro idea; larger batches also help, by reducing the noise itself.

Question 5

Which statement about a convex loss is true?

  1. Gradient descent converges on it for every learning rate
  2. Every local minimum is also a global minimum
  3. Neural networks are trained on convex losses
  4. It cannot have any flat regions
Show the answer

B. Every local minimum is also a global minimum

A convex landscape is a single bowl, so any point lower than all its neighbors is the lowest overall: gradient descent cannot be trapped in a false bottom. It still needs a sensible learning rate, as the bowl showed.

Go deeper

Further reading

  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (MIT Press, 2016), chapters 4 and 8.
  • L. Bottou, F. E. Curtis & J. Nocedal, "Optimization methods for large-scale machine learning," SIAM Review 60(2), 223–311 (2018).