Intermediate: machine learning · The ML workflow, regression and classification · topic 25 of 62 · 35 min
Gradient descent: learning step by step
Explanation
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.
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.
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))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 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)
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Logistic regression and classificationThe ML workflow, regression and classification · same module
- Training: loss, backpropagation and optimisersNeural networks and deep learning
- Gradient boostingk-NN, decision trees and ensembles
- Deep learning tools and hardwareNeural networks and deep learning
- Scaling and transforming numbersClustering, dimensionality reduction and feature engineering
- Core DevOps practices and the DORA metricsDevOps: Git, Docker, Kubernetes and CI/CD · DevOps culture and the SDLC
Questions people ask about this
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.
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.
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_.
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 more topic in “The ML workflow, regression and classification” before its exam: Logistic regression and classification.
- Module 5 exam: The ML workflow, regression and classification · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Evaluating models. 62 topics left in the course before the final exam.