Skip to content

Gradient Descent

Follow the slope downhill, then find out why the step size decides whether the walk arrives

Quick recap
  • Training starts with a way to measure being wrong: the loss.
  • The gradient points uphill, so the update steps the other way.
  • The learning rate α sets how far each step goes.

This lesson starts from loss, so it works on its own. For the fuller setup, read Linear Regression & Loss first. For the math behind the symbols, review multivariable calculus (gradients) and numerical methods (iterative algorithms).

1. A wrong guess needs a number

Imagine you are on a hillside in thick fog. You cannot see the valley. You can feel the slope under your feet. Which way do you step, and how big should the step be?

Training a model is that loop. A model has settings called parameters. For now, call the single setting w. At each setting the model makes predictions, and a loss function scores how wrong those predictions are. That score is the loss: one number for “how wrong.”

With one parameter you can draw every setting on a horizontal axis and its loss on a vertical axis. The result is a curve. Training means walking down that curve. This lesson uses a deliberately small curve so every number can be checked by hand. Its bottom sits at w = 3, where the loss is 1. At w = 0, the loss is 10. Here it is:

Our small loss

Read the symbols. w is the dial. L(w) is the loss at that setting. The squared term makes the curve a bowl. The +1 is a floor: even the best setting leaves a loss of 1. That floor stands for noise or irreducible error that no setting of this one dial can remove.

The goal is to get close to the bottom without knowing the whole curve in advance. In a real model you cannot plot the loss; you can only evaluate it at the current setting.

At the starting point

A common loss in practice is mean squared error. Start with one example. If the model predicts 7 and the target is 5, the error is , so the squared miss is 4. Compare every prediction with its target, square the misses, and average them:

Mean squared error

Squaring makes a miss of +2 and a miss of −2 count the same. This curve is a one-parameter stand-in for that idea. Its shape is what matters here.

2. The slope points the way

At w = 0 the curve falls to the right: a small increase in w lowers the loss. At w = 4 the curve rises to the right: a small increase raises the loss. The local slope is the derivative, written L′(w).

Slope of our curve

Check it at the points that matter. At w = 0, the slope is −6. At w = 3, it is 0. At w = 4, it is +2.

Slope at the start

A negative slope means “increase w to go down.” A positive slope means “decrease w to go down.” At the bottom the slope is zero, so the curve is flat.

Try it

At w = 0 the slope is −6. To lower the loss, should the next w be larger or smaller? What if the slope were +6 instead?

3. One step, by hand

Now turn the slope into an action. At w = 0 the slope is −6. With α = 0.2, we want the next w to be 1.2. The rule that produces that move multiplies the slope by a small number and subtracts it from the current setting:

Gradient descent in one dimension

α (alpha) is the learning rate: the size of the step. The subscript t counts steps. L′(w_t) is the slope at the current setting. In one dimension the gradient is the derivative, so ∇L(w) and L′(w) mean the same thing. The rule uses that slope, then moves. It does not jump to the bottom in one step.

Start at w₀ = 0 and choose α = 0.2. The slope at 0 is −6, so:

First step

The new loss is:

Loss after one step

Worked example: four steps by hand

Every row uses the same two lines: compute the slope at the current w, then subtract α times that slope. The table is generated from the same functions the playground uses.

step twslope L′(w)loss L(w)
00.0000-6.000010.0000
11.2000-3.60004.2400
21.9200-2.16002.1664
32.3520-1.29601.4199
42.6112-0.77761.1512

The first step is large because the slope is steep. The learning rate stays at 0.2; the step length does not. As the curve flattens, the same learning rate produces a smaller change.

Notice that the loss never goes below 1. The walk approaches the floor but cannot remove it. That is why the best possible loss here is 1, not 0.

4. The step size can save or wreck the walk

This curve has one bottom and one slope rule. Change α and the same walk behaves completely differently. Scrub the story: the first scene crawls, the second arrives, and the third overshoots.

For a quadratic, one step multiplies the distance from the bottom by the same factor every time:

Contraction factor

Here a is the curvature (1 for our curve), and α is the learning rate. If r is between −1 and 1, the distance shrinks. If r is exactly −1, the distance stays the same but the side flips. If |r| is larger than 1, the distance grows.

One-dimensional convergence

For this curve a = 1, so the condition becomes:

Condition for this curve

At α = 1, the factor is −1. Starting at 0 sends the point to 6, then back to 0, forever. It never settles:

The edge case

At α = 1.05, the factor is −1.1. The distance grows by 10% each step and the side flips, so the loss climbs. At α = 0.002, the factor is 0.996: the walk is stable but slow.

A small step is not automatically better. It can be safe and still fail to reach the valley within the training budget. The useful step size depends on the curve and on how much time you have.

Try it

For the curve L(w) = (w − 3)² + 1, which of these learning rates converge: 0.4, 1, or 1.2?

5. Two knobs, one gradient

Real models have many parameters. The idea does not change: measure the slope in every direction, collect the slopes into a vector, and step the other way. Start with two dials, w₁ and w₂. At the point (2, 1), this surface gives a loss of 8:

A two-parameter loss

The ellipses in the next animation are level sets: every point on one ellipse has the same loss. The centre is the minimum at (0, 0).

The gradient collects the partial derivatives. Each component says how fast the loss changes when you move that one dial:

Gradient vector

At the start, the first component is 4 and the second is 8. The second direction is twice as steep:

Gradient at the start

The update rule is the same one, written with vectors:

Gradient descent in two dimensions

With α = 0.2, the first step is:

First step in the valley

The new loss is:

Loss after the first step

Worked example: the narrow-valley walk

The second component overshoots the valley floor and lands on the other side. The first component moves more gently. The same α is applied to both directions, but their curvatures differ.

step tw₁w₂loss
02.00001.00008.0000
11.2000-0.60002.8800
20.72000.36001.0368
30.4320-0.21600.3732
40.25920.12960.1344

The path zigzags: the steep direction flips sides while the gentle direction creeps toward the centre. The playground lets you keep going and watch the loss curve.

6. Where gradient descent struggles

Gradient descent is local. It follows the slope under its feet, not a map of the whole surface. That is enough for a smooth bowl and not enough for every problem.

A stationary point is a place where the gradient is zero:

Stationary point

A stationary point can be a minimum, a maximum, or a saddle (higher in one direction, lower in another). The two-minima playground has a saddle at (0, 0). Start exactly there and the gradient is zero, so the walk stays put. Start slightly to one side and it rolls into one of the two valleys. On a non-convex surface (a surface with more than one valley or with saddles), the starting point can decide the answer.

Noisy gradients. In practice the gradient is often estimated from a mini-batch of examples rather than the whole dataset. The estimate is noisy, so the loss curve is jagged. Noise can shake the walk out of a shallow trap, but it also makes every step less precise.

Ill-conditioning (a landscape much steeper in one direction than another). A narrow valley has very different curvature in different directions. One step size that is safe for the steep wall is tiny for the gentle floor. The zigzag in the last animation is this mismatch. Momentum and adaptive methods exist to address it.

Non-smooth losses. Some losses have corners where the derivative does not exist. Gradient descent needs a slope, so those problems need a different tool or a subgradient (a slope-like substitute at a corner). That is outside this lesson.

Step size. Too large and the loss can rise or diverge. Too small and the walk can run out of time. A fixed learning rate is a compromise, not a universal answer.

The next question is natural: can the walk use information from previous steps to move faster through a narrow valley? That is the idea behind momentum, and the playground lets you try it.

7. Going deeper

The factor r is not a coincidence. Write a quadratic loss with curvature a, bottom at w*, and floor b:

General quadratic

One gradient step gives a recurrence for the distance from the bottom:

Error recurrence

Unroll it from the starting point:

Closed form

So the distance shrinks when |r| < 1, keeps its size when |r| = 1, and grows when |r| > 1. That is the exact reason behind the three scenes in the previous animation.

In two dimensions the same idea holds direction by direction. Near a minimum, the Hessian matrix describes the curvature. For the narrow valley, it is diagonal:

Hessian of the valley

The curvatures are 2 and 8. Each direction has its own factor, 1 − αλ. Every direction has to satisfy the convergence condition, so the largest curvature sets the limit:

Two-dimensional condition

At α = 0.2 the factors are 0.6 and −0.6. Both errors shrink by 40% per step, but the second direction flips sides every step, so the path zigzags because one α is doing two jobs.

Momentum adds a velocity that remembers previous steps. With μ = 0.9, 90% of the previous velocity carries into the next step:

Momentum, first line
Momentum, second line

μ is the momentum coefficient. When many steps point the same way, the velocity builds up and the walk moves faster. Momentum can also overshoot, especially with a large μ or a large learning rate. The playground exposes both knobs.

Stochastic gradient descent replaces the full gradient with an average over a mini-batch B. A batch of 32 examples, for instance, averages 32 per-example gradients. Here ℓᵢ is the loss on one example i:

Mini-batch gradient

The update is the same; only the gradient estimate changes. This is how training scales to datasets that are too large to scan for every step. The loss curve becomes noisier, and the step size often needs a schedule.

These derivations assume a smooth quadratic. Real losses are not quadratic. The intuition carries over; the exact constants do not.

8. Practice

Try it

For , compute the first two steps and their losses.

Try it

For , which learning rates converge: 0.4, 1, or 1.2?

Try it

A model reaches a training loss of 0.01 and a validation loss of 0.90. What can you conclude?

9. Resources

Watch the 3Blue1Brown chapter for a visual pass, then read the MIT notes for the formal update and stopping rules. Both links were opened and checked for this lesson.

Continue the track

Open the playground for this topic

Gradient Descent Playground →

Drag the starting point, pick a landscape, and watch the path and loss curve respond to the learning rate and momentum.

The mathematics behind this topic: Multivariable calculus · Numerical methods.

All Machine Learning lessons

Site soundtrack