internalsGet Pro

Module 04 · Lesson 4 of 11Free

Gradient descent: walking downhill to a better model

Level
Beginner
Topic
Calculus and optimization for machine learning
Reading time
14 min

When you finish this page you can

  1. Apply the update rule w ← w − η∇L by hand for a few steps, and explain why each step lowers the loss.
  2. Write a gradient descent loop in NumPy with a stopping rule and a step cap, and check its weights against least squares.
  3. Read a loss curve and tell a healthy run from one that is stuck or blowing up.
  4. Choose between a closed-form solver and gradient descent: few weights and squared error, or many weights and any loss.
  1. Least squares: the best-fitting line17 min
  2. Derivatives: how outputs change with inputs13 min
  3. Gradients: derivatives with many inputs14 min
0:00 / 5:06
Show transcript

0:00 Kartly is our example online store. Farah, an ML engineer there, predicts how many orders each customer will place next month, so Joseph’s growth team can plan vouchers. Her model has one weight. A weight is a number the model learns. The loss is one number for how wrong the model is. At a weight of 1, the slope of the loss is minus 4. So the weight should go up. Joseph asks, up to what? The slope says which way to go. It does not say how far. Here, the bottom is easy to find by hand. But next quarter’s model will have thousands of weights, and nobody can solve that loss on paper. So here is the question. How do you turn a slope into a better weight, again and again, and know when to stop? The answer is called gradient descent.

0:38 Take a small step in the direction that lowers the loss. Then look again. The slope gives the direction. It also sets the size of the step: big where the curve is steep, small near the bottom. So the rule is simple. Move the weight against the slope, scaled by one small number. That number is the learning rate. Farah picks 0.1. A negative slope pushes the weight up. A positive slope pushes it down. That is what the minus sign in the rule does. Farah starts at 1. The slope there is minus 4, so the first step goes up. The first step is 0.4. The weight lands at 1.4. The loss falls, and it must fall. A small step against the slope always goes downhill. Now the next step. The slope is smaller, so the step is smaller. Steps shrink on their own as the curve flattens, even though the learning rate never changes. After 4 steps, the weight sits next to 1.5. That is the answer Farah found by hand.

1:30 One weight is the easy case. A real model has many. With many weights, the slope becomes the gradient. That is one slope for each weight, listed together. The rule stays the same. Move every weight against its own slope, all at once, with the same small learning rate. Repeating that rule is a loop with four parts. Predict: compute predictions from the current weights. Measure: compute the loss and the gradient over all 200,000 customers. Check: is the gradient small enough, or has the loop run long enough? If yes, stop and return the weights. If no, step: move the weights, and go round again.

2:01 Now a real test. Earlier, Farah fitted Joseph’s risk score with one call to a least squares solver. Gradient descent should land on the same weights. One problem first. Gap runs up to 90, and orders only up to 5. One learning rate can’t suit both. So she rescales each feature to the same spread. That is called standardization. She starts every weight at zero and keeps the same learning rate. The loss drops fast, then flattens. The loop stops after about 75 steps. The one-weight loss needed only 4. This loss curves less steeply, so it takes longer. The weights agree with least squares to about six decimal places. The final loss is about 0.085. That is the rounding in the scores, which no line can fit. So walking downhill and solving directly give the same answer.

2:46 At the bottom, the gradient is zero. But the loop only gets closer each step. So it needs a rule for close enough. One rule: stop when the gradient is tiny. Another: stop when the loss barely improves. That one can stop too early, on a slow, flat stretch. So Farah adds a guard: a step cap. Stop after a fixed number of steps, whatever happens. A cap is never optional. A bug can keep the gradient large forever. Libraries work the same way. If the cap stops a solver first, it prints a warning. Read that warning as: these weights are unfinished. It is not noise.

3:16 Draw the loss after each step as a line. That is the loss curve. Look at it after every training run. Steep, then flat, is healthy. A flat line from the start means the weights are not moving. Usually the update never reached them. A rising line means every step goes uphill. Here is how one flipped sign does it. A teammate writes a plus where the minus belongs. No error is raised. The loss goes from 2 to 4.24, and keeps climbing. Unless someone plots the curve, Joseph’s voucher plan gets predictions of negative orders. A rising curve with the right sign means the learning rate is too large. The next lesson covers that.

3:50 Least squares gave the answer in one call. Gradient descent took 75 steps and needed a rate, a stopping rule and a cap. So why use it almost everywhere? For a simple model and squared error, the direct solver wins. But most losses have no formula for their bottom. Joseph’s next model predicts which customers will stop buying, as a probability. No formula solves its loss. The only way to the bottom is to walk. There is a second reason: too many weights. A direct solver works with a table that has one entry for every pair of weights. For a model with a million weights, that table is about 8 terabytes. That is before any solving starts. Gradient descent needs only the weights and one gradient. About 16 megabytes. Each step costs a pass over the data, but memory stays small.

4:31 Let’s recap. One: gradient descent steps against the slope, again and again, scaled by the learning rate. Two: steps shrink by themselves near the bottom, because the slope shrinks. Three: stop when the gradient is tiny, with a step cap as a guard. Four: plot the loss curve. Steep then flat is healthy. Flat means the weights are not moving. Rising means a wrong sign or too big a step. Five: on a simple model it reaches the same weights as least squares, and it keeps working where no formula exists. Farah used a learning rate of 0.1 throughout, and never asked why. What if it were bigger, and the steps started overshooting the bottom? See you in Learning rate.

The slope says which way, not how far

is our example online store. Farah, an ML engineer, is predicting how many orders each customer will place next month, so Joseph’s growth team can plan vouchers. Her model has one weight: predicted orders = w × orders this month.

In Derivatives, she wrote the over her 200,000-customer sample as L(w) = 4w² − 12w + 10. At w = 1.0 the loss is 2.0 and the slope is −4. So w should go up.

Joseph asks: “Up to what?” Here the bottom is easy to find by hand: the slope 8w − 12 is 0 at w = 1.5. Next quarter’s model will have thousands of weights and a loss nobody can solve on paper.

This lesson answers one question: how do you turn a slope into a better weight, again and again, and know when to stop?

Step against the slope, a little at a time

Take a small step in the direction that lowers the loss, then look again. The slope gives the direction, and its size sets the step: big where the curve is steep, small near the bottom.

That is the update rule of descent:

wnew=w−η L′(w)w_{\text{new}} = w - \eta \, L'(w)
  • ww: the current weight.
  • L′(w)L'(w): the slope of the loss at w.
  • η\eta (eta): the , a small fixed number that scales every step.
  • The minus sign: a negative slope pushes w up, a positive slope pushes it down.

Farah uses η = 0.1. At w = 1, the step is −0.1 × (−4) = +0.4, so w becomes 1.4. The loss falls from 2.0 to 1.04.

Why must the loss fall? For a small step h, Derivatives gave L(w + h) ≈ L(w) + L′(w)·h. With h = −η L′(w), the change is about −η L′(w)², which is never positive. The real drop, 0.96, is below this estimate of 1.6 because the step is not tiny.

Check yourselfAnswer in your head first, then reveal
Farah keeps η = 0.1 for every step. Predict how far the second step moves w, starting from 1.4.Show answerHide answer
0.08, not 0.4. The step is η times the slope, and at w = 1.4 the slope is only −0.8. Steps shrink on their own as the curve flattens, even though η never changes.
Step w Slope 8w − 12 Move −0.1 × slope Loss L(w)
0 1.0 −4 +0.4 2.0
1 1.4 −0.8 +0.08 1.04
2 1.48 −0.16 +0.016 1.0016
3 1.496 −0.032 +0.0032 1.000064
4 1.4992 −0.0064 +0.00064 about 1.0000026

The distance to the bottom, 1.5, shrinks five times each step: 0.5, 0.1, 0.02, 0.004. After four steps w is within 0.001 of the answer Farah found by hand.

Each step moves against the slope. Near the bottom the slope is small, so the steps shrink without changing η.

Start anywhere and the same rule walks downhill to w = 1.5:

One weight is the easy case. A real model has many.

The same loop moves every weight at once

With many weights, the slope becomes the gradient: one partial derivative per weight, as Gradients showed. The rule is the same, applied to every weight together:

w←w−η ∇L(w)\mathbf{w} \leftarrow \mathbf{w} - \eta \, \nabla L(\mathbf{w})
  • w\mathbf{w}: the vector of all weights.
  • ∇L(w)\nabla L(\mathbf{w}): the gradient, the vector of slopes, one per weight.
  • ←\leftarrow: replace the old weights with the new ones.

Repeating that rule is a loop with four parts. The training loop builds it out for real models; here is its core.

Gradient descent repeats predict, measure, check, step. The check decides when the loop ends.

Walking to the least-squares answer

In Least squares, Farah fitted Joseph’s risk score from gap and orders on 200,000 customers with one call to np.linalg.lstsq. Gradient descent should land on the same weights. That makes it a good test.

For the mean squared error, Gradients gave the gradient as:

∇L(w)=2nA⊤(Aw−b)\nabla L(\mathbf{w}) = \frac{2}{n} A^{\top}(A\mathbf{w} - \mathbf{b})
  • AA: the feature table, one row per customer, with a column of 1s.
  • b\mathbf{b}: the scores.
  • Aw−bA\mathbf{w} - \mathbf{b}: each customer’s miss.
  • nn: the number of customers, 200,000.

One problem first. Gap runs from 0 to 90 and orders from 0 to 5. One fixed η cannot suit both columns; Learning rate shows why. So Farah rescales each feature to mean 0 and spread 1, called standardization, which Scaling and normalizing features covers. Afterwards she converts the weights back.

Run this in a free Colab or Kaggle , on a CPU. The data is made up and takes tens of MB.

Python
import numpy as np

rng = np.random.default_rng(42)
n = 200_000

# The same made-up Kartly sample as in Least squares
gap = rng.integers(0, 91, size=n).astype(float)
orders = rng.integers(0, 6, size=n).astype(float)
score = np.round(0.1 * gap - orders + 4)

X = np.column_stack([gap, orders])
mu, sigma = X.mean(axis=0), X.std(axis=0)
A = np.column_stack([(X - mu) / sigma, np.ones(n)])  # standardized, 200,000 x 3


def loss_and_grad(w: np.ndarray) -> tuple[float, np.ndarray]:
    miss = A @ w - score
    return float(np.mean(miss**2)), (2 / n) * (A.T @ miss)


w = np.zeros(3)
lr = 0.1
history = []
for step in range(1000):                  # step cap: never loop forever
    loss, grad = loss_and_grad(w)
    history.append(loss)
    if np.linalg.norm(grad) < 1e-6:       # flat enough: stop
        break
    w = w - lr * grad

# Undo the standardization to compare with lstsq on the raw columns
w_gap, w_orders = w[:2] / sigma
intercept = w[2] - np.sum(w[:2] * mu / sigma)
print("stopped at step", step, "loss", round(history[-1], 4))
print("gradient descent:", w_gap, w_orders, intercept)

B = np.column_stack([gap, orders, np.ones(n)])
w_ls, *_ = np.linalg.lstsq(B, score)
print("lstsq:           ", w_ls)

What to look for, as one run should print it:

  • The loop stops after about 75 steps, an estimate from the arithmetic below.
  • The two sets of weights agree to about six decimal places, close to 0.1, −1 and 4.
  • The final loss is about 0.085: the rounding in the scores, which no line can fit.
Step Loss (estimate)
0 45.9
1 29.4
5 5.0
10 0.61
20 0.091
30 onwards 0.085

Estimates, not a run. Standardized, the three columns barely overlap, so each step keeps 80% of the remaining error in the weights and 64% of the extra loss.

The same η needed 4 steps on the one-weight loss and about 75 here, because this loss curves less steeply. Learning rate picks this up.

In PyTorch, torch.optim.SGD performs the update line for you. With its default momentum=0, its update is the plain rule above.1 Its default learning rate is 0.001, as of November 2026, so set it yourself.1

Python
import torch

# Reuses A and score from the NumPy block
A_t, y_t = torch.from_numpy(A), torch.from_numpy(score)
w_t = torch.zeros(3, dtype=torch.float64, requires_grad=True)
opt = torch.optim.SGD([w_t], lr=0.1)

for step in range(1000):
    opt.zero_grad()
    loss = torch.mean((A_t @ w_t - y_t) ** 2)
    loss.backward()                       # autograd fills w_t.grad
    if w_t.grad.norm() < 1e-6:
        break
    opt.step()                            # w_t = w_t - 0.1 * w_t.grad

print(step, loss.item(), w_t.detach())

Stop when the gradient is nearly zero

At the bottom the gradient is zero, but the loop only gets closer each step. So you need a rule for “close enough”.

Stopping rule How it works Where it goes wrong
Gradient small Stop when the gradient’s length is below a tolerance, such as 10⁻⁶ The right tolerance depends on the loss’s units
Loss stopped improving Stop when the loss falls by less than a tolerance between checks Stops early on a slow, flat stretch
Step cap Stop after a fixed number of steps Says nothing about whether the weights are good
Validation loss rises Stop when the loss on held-out data starts to climb Needs a held-out set; covered in Regularization

Farah uses the first rule with the third as a guard. A cap is never optional: a bug can keep the gradient large forever.

Libraries work the same way. scikit-learn’s LogisticRegression gives its solver a default cap of 100 iterations. When the cap stops it before its tolerance is met, it warns that it did not converge. Read that warning as “these weights are unfinished”, not as noise.

A gradient of zero means a flat point. On this loss there is only one, so it is the best answer. Convex and non-convex problems covers losses with several.

The loss curve tells you how training went

The loss after each step, drawn as a line, is the loss curve. It is the first thing to look at after any training run.

Three shapes to recognise. Only the first means the loop is doing its job.

A flat curve usually means the update never reaches the weights: a missing update line, or a gradient that is always zero. A rising curve means each step goes uphill.

One flipped sign sends the weights uphill

  1. Farah’s teammate writes the update as w = w + lr × slope, a plus where the minus belongs.
  2. From w = 1 on the one-weight loss, w moves to 0.6, then −0.12. The loss goes 2.0, 4.24, 11.5.
  3. Each step multiplies the distance from 1.5 by 1.8. By step 20 the loss is about 1.6 × 10¹⁰.
  4. No error is raised. Unless someone plots the curve, Joseph’s voucher plan gets predictions of negative orders.

A rising curve with the right sign means η is too large; Learning rate covers that case.

Why not solve it directly?

lstsq gave Farah’s risk score in one call. Gradient descent took 75 steps and needed a rate, a tolerance and a cap. So why does ML training use it almost everywhere?

Farah has a model and a loss. Should she fit the weights with a closed-form solver or with gradient descent?

Gradient descent, the same loop as above.

Works for any loss you can take a gradient of, and needs memory only for the weights and one gradient. Costs many passes over the data, and the answer is only as good as the stopping rule.

Why this choice

For three weights and squared error, lstsq wins. Two things change the answer.

The loss has no formula for its bottom. A closed-form answer exists because setting the squared-error gradient to zero gives linear equations, the normal equations from Least squares. Next, Joseph wants a churn model that outputs a probability. Its loss, covered in Logistic regression, gives equations no formula solves. Neural networks are the same. The only way to the bottom is to walk.

There are too many weights. A closed-form solver works with a table of p × p numbers. For a model with 1 million weights:

Closed form: the p × p table

10⁶ × 10⁶ × 8 bytes = 8 × 10¹² bytes, about 8 TB

Far beyond any free notebook, before any solving starts.

Gradient descent: weights plus gradient

2 × 10⁶ × 8 bytes = 16 MB

Each step costs a pass over the data, but memory stays small.

Gradient descent is generally credited to Cauchy, in 1847.2 It lasted because it asks only for a gradient, which autograd supplies for any model.

When one pass over the data per step is too slow, estimate the gradient from a sample of rows: Stochastic and mini-batch gradient descent.

Where this shows up

Farah used η = 0.1 throughout and never asked why. The next lesson asks what happens at 0.2, or 0.3, when the steps start overshooting the bottom.

Common mistakes

  • No step cap. A bug that keeps the gradient large runs forever. Always bound the loop.
  • Summing instead of averaging. Forgetting the 1/n makes the gradient 200,000 times larger. With η = 0.1 that acts like a step of 20,000, and the loss explodes.
  • Stopping on a fixed loss change. “Stop when the loss falls by less than 0.01” means different things for a loss of 45 and a loss of 0.08.
  • Comparing standardized weights with raw ones. Undo the standardization before checking against lstsq.

Check your understanding

Check yourselfAnswer in your head first, then reveal
Farah starts the one-weight model at w = 2 instead, with η = 0.1. Where does the first step land, and does the loss fall?Show answerHide answer
The slope at 2 is 8 × 2 − 12 = 4, so w becomes 2 − 0.4 = 1.6 and the loss falls from 2.0 to 1.04. The minus sign turns a positive slope into a step down, so the rule works from either side.
Check yourselfAnswer in your head first, then reveal
On the 200,000-customer fit, a teammate stops when the loss falls by less than 0.01 in one step. About when does the loop stop, and is the model finished?Show answerHide answer
Around step 17, with a loss near 0.11, about a quarter above the best possible 0.085. Each step removes 36% of the extra loss left, so the drop falls below 0.01 while about 0.03 of extra loss remains. A gradient tolerance, or a tolerance relative to the loss, would keep going.
Check yourselfAnswer in your head first, then reveal
A loss curve stays at 45.9 for all 1,000 steps. What do you check first?Show answerHide answer
Whether the weights change at all. A flat curve at the starting loss means the update never reached the weights: a missing update line, or a gradient that is always zero. Not the learning rate first: even a tiny rate moves the loss a little.
Check yourselfAnswer in your head first, then reveal
Joseph asks why the churn model can’t use lstsq if it has only 12 weights. What do you tell him?Show answerHide answer
Size is not the problem. Its loss outputs probabilities, and setting its gradient to zero gives equations no formula solves, so the weights must be found by walking downhill. lstsq only solves squared error on a linear model.

Summary

  1. Gradient descent turns a slope into a better weight by stepping against it, w ← w − η∇L, and repeats until a stopping rule says the gradient is small enough.
  2. Steps shrink by themselves near the bottom, because the gradient shrinks; with η = 0.1, Farah’s one-weight model reached w ≈ 1.5 in four steps.
  3. Stop on a small gradient, guarded by a step cap; a convergence warning means the cap stopped the loop first.
  4. Plot the loss curve after every run: steep then flat is healthy, flat means the weights aren’t moving, rising means a wrong sign or too large a step.
  5. On a linear model with squared error, gradient descent reaches the same weights as lstsq; ML uses it anyway because most losses have no closed form and millions of weights don’t fit a p × p table.

Report a mistake

Tell us what’s wrong in this lesson and we’ll fix it.