AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
∿Classical Machine Learning
  1. Linear regression
  2. Gradient descent
  3. Classification: logistic regression, kNN, SVM
  4. Decision trees and ensembles
  5. Clustering and PCA
  6. Overfitting and the bias-variance trade-off
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Classical Machine Learning

Gradient descent

The optimisation engine behind almost all of ML: the update rule, a worked example of how the learning rate decides between crawling, converging and diverging, batch vs mini-batch vs stochastic, and local minima — on a rotatable 3D loss surface.

Beginner~24 min·5 references
Key terms
Gradient descentGradientDerivativeLoss functionLearning rateBatch sizeEpochIteration (training step)SGD (Stochastic Gradient Descent)

Training a model means finding parameters that make the loss small. For linear regression there is a formula, but for logistic regression, neural networks and LLMs there is not. Instead, almost every model is trained with some form of [[gradient-descent|gradient descent]]: repeatedly compute which direction makes the loss go up fastest, and take a small step the other way[1][2].

≈
Walking down a foggy mountain
You are on a mountainside in thick fog and want to reach the valley. You cannot see the valley, but you can feel the slope under your feet. So you take a step in the steepest downhill direction, feel again, step again. The slope is the gradient; the length of your step is the learning rate. Tiny steps: you arrive, eventually. Huge steps: you leap over the valley onto the opposite slope — and maybe higher than you started.

The update rule

θ ← θ − η · ∇L(θ) (one parameter: w ← w − η · ∂L/∂w)
The gradient descent update rule, applied once per step (iteration).
In words: “New parameters = old parameters minus a small step in the direction where the loss increases fastest.” Because we subtract the gradient, we move downhill. The arrow ← means “replace with”: it is an assignment repeated every step, not an equation to solve.
Symbols(hover a symbol in the formula)
θ
theta — all trainable parameters of the model (weights and biases), as one vector
←
assignment: overwrite the left side with the value on the right
η
eta — the Learning rate: how big each step is (e.g. 0.1, 0.001)
∇L(θ)
nabla L — the Gradient: vector of partial derivatives of the loss w.r.t. every parameter; points uphill
L
the Loss function, e.g. MSE: one number measuring how wrong the model is
∂L/∂w
partial derivative: how much the loss changes when only w changes a tiny bit (the slope along w)
w
a single weight (one component of θ)
▸Worked example
Loss L(w) = (w − 3)², start w = 0, η = 0.1 Step 1: ∂L/∂w = 2(w − 3) = 2(0 − 3) = −6 w ← 0 − 0.1 · (−6) = 0.6 L = (0.6 − 3)² = 5.76 Step 2: ∂L/∂w = 2(0.6 − 3) = −4.8 w ← 0.6 − 0.1 · (−4.8) = 1.08 L = 3.69 Step 3: w ← 1.08 + 0.384 = 1.464 L = 2.36 …each step closes 20% of the remaining gap to the minimum w = 3. With η = 1.1 instead: w → 6.6 → −1.32 → 8.18 … the steps overshoot and diverge.

The Gradient points uphill, so we subtract it. Where the slope is steep the step is big; near the bottom the gradient shrinks and steps get smaller automatically. The [[learning-rate|learning rate]] η scales every step and is the single most important Hyperparameter in deep learning.

Worked example: L(w) = (w − 3)²

The minimum is at w = 3. The Derivative is L′(w) = 2(w − 3). Start at w = 0 with η = 0.1: step 1 gives w = 0 − 0.1·(−6) = 0.6; step 2 gives w = 0.6 − 0.1·(−4.8) = 1.08; then 1.46, 1.77, … approaching 3. In fact the distance to the optimum e = w − 3 is multiplied by (1 − 2η) every step, which explains everything that can happen:

eₜ₊₁ = (1 − 2η) · eₜ
In words: “the distance to the minimum after the next step = the current distance times a fixed factor”. It comes from plugging the gradient 2(w − 3) into the update rule. If the factor is between −1 and 1 the distance shrinks every step (convergence); if its size exceeds 1 the distance grows every step (divergence); a negative factor means the step jumps over the minimum to the other side.
Symbols(hover a symbol in the formula)
eₜ
error at step t: the distance wₜ − 3 between the current weight and the minimum
eₜ₊₁
the same distance one step later (subscript t+1)
(1 − 2η)
the shrink factor per step; the 2 comes from the slope of (w − 3)²
η
eta — the Learning rate
·
multiplication
▸Worked example
Derivation: w ← w − η·2(w − 3). Subtract 3 on both sides: e ← e − 2η·e = (1 − 2η)·e η = 0.1 → factor 0.8, start w = 0 so e₀ = −3 e₁ = 0.8 · (−3) = −2.4 (w = 0.6) e₂ = 0.8 · (−2.4) = −1.92 (w = 1.08) e₁₀ = −3 · 0.8¹⁰ ≈ −0.32 η = 0.01 → factor 0.98: after 100 steps 0.98¹⁰⁰ ≈ 0.13 of the gap is left η = 1.1 → factor −1.2: e = −3 → 3.6 → −4.32 (w = 6.6 → −1.32): diverges
Learning rate ηFactor (1 − 2η)Behaviour
0.010.98Crawls: after 100 steps still ~13% of the original distance away
0.10.8Smooth, fast convergence
0.50Lands exactly on the minimum in one step (lucky for this bowl)
0.9−0.8Overshoots, zig-zags across the minimum, but still converges
1.0−1Bounces between 0 and 6 forever
1.1−1.2Diverges: every step lands farther away; the loss explodes to infinity / NaN

Gradients for linear regression

For ŷ = w·x + b with MSE loss, the partial derivatives are averages over the examples of ‘error × input’. If predictions are too low on average (positive residuals), ∂L/∂b is negative, so b increases. That is the whole learning signal.

∂L/∂w = −(2/n) · Σᵢ xᵢ (yᵢ − ŷᵢ) ∂L/∂b = −(2/n) · Σᵢ (yᵢ − ŷᵢ)
In words: Read ∂L/∂w as “−2 × the average of (error × input)” and ∂L/∂b as “−2 × the average error”. If the model predicts too low (positive errors), both gradients are negative, so the update w ← w − η·∂L/∂w increases w and b and pushes predictions up. Examples with bigger inputs xᵢ have more say in how w moves.
Symbols(hover a symbol in the formula)
∂L/∂w
partial derivative of the MSE loss with respect to the weight w
∂L/∂b
partial derivative of the loss with respect to the bias b
(2/n)
the 2 comes from differentiating the square; 1/n from averaging over n examples. The leading minus comes from ŷ entering the error with a minus sign
Σᵢ
sum over all examples i (or over the mini-batch)
xᵢ
input of example i: scales how much that example's error affects w
yᵢ
true target of example i
ŷᵢ
current prediction w·xᵢ + b
▸Worked example
Data (x, y): (1, 2), (2, 4); start w = 1, b = 0, n = 2 Predictions ŷ = [1, 2] → errors y − ŷ = [1, 2] MSE = (1 + 4)/2 = 2.5 ∂L/∂w = −(2/2) · (1·1 + 2·2) = −5 ∂L/∂b = −(2/2) · (1 + 2) = −3 Update with η = 0.1: w ← 1 − 0.1·(−5) = 1.5 b ← 0 − 0.1·(−3) = 0.3 New predictions [1.8, 3.3] → errors [0.2, 0.7] → MSE = 0.265 (was 2.5)
Loading interactive…
Drag to rotate the loss surface. Pick a surface, a start point (click the contour inset) and a learning rate, then watch the ball descend.
  • Convex bowl, learning rate 0.01: the ball creeps; the loss-per-step chart is a long slow slope. Raise it to ~0.1: it converges in a few dozen steps.
  • Push the learning rate above ~1: the path zig-zags across the bowl and the loss chart oscillates or shoots upward — divergence.
  • Elongated ravine: the ball bounces between the steep walls while barely moving along the gentle valley floor. A learning rate small enough for the steep direction is too slow for the flat one — this is why feature scaling and optimisers like momentum/Adam help.
  • Two minima: start on different sides of the hill and the ball ends in different valleys. Gradient descent only finds a *local* minimum near where it starts.

Batch, mini-batch and stochastic

Computing the exact gradient needs a pass over all n examples — too slow for millions of images. In practice we estimate the gradient from a random mini-batch of examples. Each update is one [[iteration]]; one full pass over the training data is one [[epoch]]. Using a single example per step is classic [[sgd|stochastic gradient descent (SGD)]], though in deep learning ‘SGD’ usually means mini-batch SGD[3][4][5].

iterations per epoch = ⌈ N / batch_size ⌉ e.g. N = 50,000, batch = 128 → 391 iterations
In words: “how many mini-batches does it take to see every training example once?” Divide the dataset size by the batch size and round up, because the leftover examples still form one last, smaller batch. Each batch is one parameter update (Iteration (training step)); all of them together make one Epoch.
Symbols(hover a symbol in the formula)
iterations per epoch
number of iterations (updates) in one full pass over the data
⌈
ceiling: round up to the next whole number (⌈390.6⌉ = 391, ⌈4⌉ = 4)
⌉
closes the ceiling brackets
N
number of training examples
batch_size
examples per mini-batch, the Batch size hyperparameter (e.g. 32, 128)
→
“gives”
▸Worked example
N = 50,000 images, batch_size = 128 50,000 / 128 = 390.625 ⌈390.625⌉ = 391 iterations per epoch 390 full batches of 128 = 49,920 examples 1 last batch of 50,000 − 49,920 = 80 examples Training for 10 epochs = 10 · 391 = 3,910 updates. Double the batch to 256 → ⌈195.3⌉ = 196 iterations per epoch: half the updates.
VariantExamples per updateProsCons
Batch (full) GDNexact gradient, smooth pathslow per step, memory-hungry
Mini-batch SGD16–1024GPU-friendly, good noise/speed balance — the defaultone more hyperparameter
Stochastic GD1very cheap steps, noise can escape shallow minimavery noisy, poor hardware use
knoblearning rate (η)
What it is
The multiplier on the gradient in each update — the step size.
↑ If you increase it
Faster progress at first; beyond a critical value the updates overshoot, the loss oscillates, then diverges (NaN). Moderately high rates add noise that can help generalisation.
↓ If you decrease it
Stable but slow; training may look ‘stuck’ and need many more epochs. Can settle into the first sharp minimum it meets.
Typical values
Plain SGD on scaled data: 0.01–0.1. Adam for neural nets: ~1e-3; fine-tuning large pretrained models: 1e-5–5e-5. Try values on a log scale (×3 or ×10 apart).
knobbatch size
What it is
How many examples are averaged to estimate the gradient for one update.
↑ If you increase it
Less noisy gradients, better GPU utilisation, fewer updates per epoch; needs more memory, and often a larger learning rate to keep the same progress. Very large batches can generalise slightly worse.
↓ If you decrease it
Noisier updates (a mild regulariser), more updates per epoch, less memory; too small makes training erratic and slow in wall-clock time.
Typical values
32–256 for most networks (powers of two by convention). Use the largest that fits in memory if you also tune the learning rate.
knobepochs / number of steps
What it is
How many full passes over the training data (or how many update steps) to run.
↑ If you increase it
Training loss keeps falling; validation loss falls, flattens, and eventually may rise again (overfitting). Costs more compute.
↓ If you decrease it
Training stops before converging — the model underfits and both losses stay high.
Typical values
Set a generous maximum and use early stopping on validation loss. scikit-learn's SGDRegressor defaults to max_iter=1000 epochs with a tolerance-based stop.

Convex vs non-convex losses

Linear and logistic regression have convex losses — a single bowl, so any reasonable learning rate reaches the global minimum. Neural network losses are non-convex, full of local minima, plateaus and saddle points (flat in some directions, curved in others). Surprisingly, in very high dimensions most local minima turn out to be nearly as good as the global one, and the bigger practical problems are saddle points, ravines and choosing the learning rate — which is what optimisers like Momentum and Adam address (see the optimisers lesson)[2][4].

python
import numpy as np

rng = np.random.default_rng(0)
x = rng.uniform(0, 10, 100)
y = 2.5 * x + 4 + rng.normal(0, 1.5, 100)    # true w = 2.5, b = 4

w, b, lr = 0.0, 0.0, 0.01
for epoch in range(2000):
    y_hat = w * x + b
    err = y - y_hat
    grad_w = -2 * np.mean(x * err)
    grad_b = -2 * np.mean(err)
    w -= lr * grad_w
    b -= lr * grad_b
    if epoch % 500 == 0:
        print(epoch, round(np.mean(err ** 2), 3))

print("learned:", round(w, 2), round(b, 2))  # close to 2.5 and 4

# Same idea with scikit-learn (mini-batch of size 1, i.e. true SGD):
from sklearn.linear_model import SGDRegressor
sgd = SGDRegressor(learning_rate="constant", eta0=0.001, max_iter=1000, tol=1e-4)
sgd.fit(x.reshape(-1, 1), y)
print(sgd.coef_, sgd.intercept_)
Gradient descent for linear regression from scratch, then SGDRegressor. Try lr = 0.05 in the loop: x reaches 10, so the curvature is large and the loss blows up.
!
Pitfalls
Unscaled features create ravines — standardise inputs first. Loss becomes NaN/inf → learning rate too high (or a bug such as log(0)). Loss flat from the start → learning rate far too low, or gradients not flowing. Not shuffling data between epochs can bias mini-batches. Comparing runs with different batch sizes at the same learning rate is not apples to apples.
▸Go deeper: when is a learning rate ‘too big’?

For a quadratic loss with curvature (second derivative) c, the error is multiplied by (1 − η·c) each step, so gradient descent converges if and only if 0 < η < 2/c. In our example c = 2, giving η < 1 — exactly what the table shows. With many parameters, the binding constraint is the largest curvature (the steepest direction), while progress along the flattest direction is what makes training slow. The ratio of the two (the condition number) is why ravines are hard and why scaling features, momentum and adaptive optimisers help[2].

History: Augustin-Louis Cauchy described the method of steepest descent in 1847; Robbins & Monro's 1951 stochastic approximation is the ancestor of SGD. Ruder's overview covers the modern variants (momentum, Adagrad, RMSProp, Adam)[4].

Quiz

1.
In w ← w − η·∂L/∂w, why is the gradient subtracted?
2.
Your training loss suddenly becomes NaN after a few steps. Most likely cause?
3.
You have 10,000 training examples and a batch size of 100. How many iterations are in one epoch?
4.
For L(w) = (w − 3)², gradient descent with η = 1.0 starting at w = 0 will…
5.
Two runs of gradient descent on a non-convex loss start from different points and end with different losses. Why?
Score: 0/5

References

  1. [1]
    Machine Learning Crash Course — Linear regression: gradient descent & hyperparameters
    CourseGoogledevelopers.google.com
  2. [2]
    Deep Learning — Chapter 4: Numerical Computation (gradient-based optimisation)
    BookGoodfellow, Bengio & Courville2016deeplearningbook.org
  3. [3]
    scikit-learn User Guide — Stochastic Gradient Descent
    Docsscikit-learn developersscikit-learn.org
  4. [4]
    An overview of gradient descent optimization algorithms
    PaperRuder2016arxiv.org
  5. [5]
    Dive into Deep Learning — 12.3 Gradient Descent
    BookZhang, Lipton, Li & Smolad2l.ai
← Previous
Linear regression
Next →
Classification: logistic regression, kNN, SVM