Skip to content

Intermediate: machine learning · The ML workflow, regression and classification · topic 25 of 62 · 35 min

Gradient descent: learning step by step

Explanation

Most models cannot be solved with a neat formula, so they learn by gradient descent: start with a guess, measure the error (the loss), work out which direction makes the loss smaller (the gradient), take a small step that way, and repeat. The learning rate sets the step size.

Why we need it

Linear regression with one feature has an exact formula. Most models, including neural networks with millions of weights, do not. Gradient descent is the general method that trains almost all of them. If you understand it on one weight, you understand the core of deep learning.

The loss function

A loss function turns "how wrong is the model?" into one number. For regression, a common choice is the mean squared error. Training means finding the weights that make the loss as small as possible. Picture the loss as a valley: each possible weight is a position, and the height is the loss. We want the lowest point.

Think of it like this: Imagine walking down a hill in thick fog. You cannot see the bottom, but you can feel which way the ground slopes under your feet. You take a step downhill, feel again, and step again. Gradient descent does exactly this. The slope you feel is the gradient; the length of your step is the learning rate.

The gradient

The gradient is the slope of the loss at the current weight: how fast the loss rises if the weight increases a little. If the gradient is positive, increasing the weight makes things worse, so we decrease it. If it is negative, we increase it. The update rule is always: new weight = old weight − learning rate × gradient.

A tiny worked example

Take the loss f(w) = (w − 3)². Its lowest point is at w = 3. Its gradient is 2(w − 3). Start at w = 0 with a learning rate of 0.1. The gradient is 2 × (0 − 3) = −6, so the new w is 0 − 0.1 × (−6) = 0.6. Next, the gradient is 2 × (0.6 − 3) = −4.8, and w becomes 1.08. Each step moves closer to 3, and the steps get smaller as the slope flattens.

python
w = 0.0
lr = 0.1
for step in range(5):
    grad = 2 * (w - 3)
    w = w - lr * grad
    print(step + 1, round(w, 4))
Shows 1 0.6, 2 1.08, 3 1.464, 4 1.7712, 5 2.017. After about 50 steps w is almost exactly 3.

The learning rate

  • Too small: training is very slow, and may stop before reaching the bottom.
  • Too large: steps jump over the valley, the loss bounces around or even grows to infinity (it "diverges"). For f(w) = (w − 3)², any learning rate above 1.0 diverges.
  • Just right: the loss drops quickly and settles. In practice people try values like 0.1, 0.01 and 0.001.

Batch, stochastic and mini-batch

An epoch is one full pass over the training data. Batch gradient descent computes the gradient on all examples before each step: accurate but slow for big data. Stochastic gradient descent (SGD) uses one example per step: fast but noisy. Mini-batch gradient descent uses small groups, like 32 or 256 examples, and is what almost every deep learning library uses.

Common mistakes

  • Features on very different scales (area in thousands, rooms in single digits) make the valley long and thin, so descent zig-zags. Fix: scale features (module 8).
  • Watching only the final loss. Fix: plot the loss after every epoch; it should go down and level off.
  • Forgetting the minus sign and climbing uphill. The update subtracts the gradient.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Gradient descent: learning step by step · 1/7

Gradient descent

Gradient descent is how most models learn. Let us see it on one weight.

Prefer a video by a teacher? Find free videos on “gradient descent explained learning rate simple example” on YouTube ↗

In real life: How recommendation models are trained

A video app's recommendation model may have millions of weights. Engineers never solve for them with a formula. Instead, every few hours the training job runs mini-batch gradient descent over the latest viewing data, nudging every weight a tiny step in the direction that reduces the loss. The same simple update rule from this lesson, repeated billions of times on GPUs, is what "training" means.

Practice (0/2 done)

Task 1 · Code · Python

Write minimise(lr, steps) that runs gradient descent on f(w) = (w − 3)², starting from w = 0. Each step: grad = 2 × (w − 3); w = w − lr × grad. Return w rounded to 4 decimal places.

Task 2 · Code · Python

Fit y ≈ w·x (no intercept) by gradient descent on the mean squared error. Write fit_slope(xs, ys, lr, epochs): start with w = 0.0; in every epoch compute grad = (2 / n) × Σ (w·x − y)·x over all examples, then w = w − lr × grad. Return w rounded to 3 decimal places.

Quick quiz

Question 1

1.At the current weight the gradient of the loss is positive. What should gradient descent do?

Question 2

2.The loss jumps around and grows larger every epoch. The most likely cause is…

Question 3

3.What is an epoch?

Question 4

4.Which variant updates the weights after each small group of examples, such as 64?

Question 5

5.What is the update rule of gradient descent?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

At the current weight the gradient of the loss is positive. What should gradient descent do?

Answer: Decrease the weight

Positive slope means the loss rises as w rises, so step the other way.

The loss jumps around and grows larger every epoch. The most likely cause is…

Answer: The learning rate is too large

Large steps overshoot the valley and can diverge.

What is an epoch?

Answer: One full pass over the training data

In one epoch the model sees every training example once.

Which variant updates the weights after each small group of examples, such as 64?

Answer: Mini-batch gradient descent

Mini-batch is the standard in deep learning.

What is the update rule of gradient descent?

Answer: w = w − lr × gradient

Move against the gradient by a step of size lr.

Training loss keeps falling but validation loss starts rising. What is happening?Related

Answer: Overfitting

The network is memorising the training data; consider early stopping.

From Training: loss, backpropagation and optimisers

What does each new tree learn in gradient boosting for regression?Related

Answer: The residuals (errors) of the current model

Residuals are what is still wrong.

From Gradient boosting

Which prediction gives the LARGEST log loss when the true label is 1?Related

Answer: p = 0.02

A confident wrong answer (p near 0 for a true 1) is punished most.

From Logistic regression and classification

In scikit-learn, where are the learned weights of a LinearRegression model?Related

Answer: model.coef_ and model.intercept_

Fitted attributes end with an underscore: coef_ and intercept_.

From Linear regression and least squares

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “The ML workflow, regression and classification” before its exam: Logistic regression and classification.
  2. Module 5 exam: The ML workflow, regression and classification · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Evaluating models. 62 topics left in the course before the final exam.

← Previous: Linear regression and least squares