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.
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].
The update rule
- θ
- 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
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ₜ
- 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
| Learning rate η | Factor (1 − 2η) | Behaviour |
|---|---|---|
| 0.01 | 0.98 | Crawls: after 100 steps still ~13% of the original distance away |
| 0.1 | 0.8 | Smooth, fast convergence |
| 0.5 | 0 | Lands exactly on the minimum in one step (lucky for this bowl) |
| 0.9 | −0.8 | Overshoots, zig-zags across the minimum, but still converges |
| 1.0 | −1 | Bounces between 0 and 6 forever |
| 1.1 | −1.2 | Diverges: 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
- 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
- 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
- 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
| Variant | Examples per update | Pros | Cons |
|---|---|---|---|
| Batch (full) GD | N | exact gradient, smooth path | slow per step, memory-hungry |
| Mini-batch SGD | 16–1024 | GPU-friendly, good noise/speed balance — the default | one more hyperparameter |
| Stochastic GD | 1 | very cheap steps, noise can escape shallow minima | very noisy, poor hardware use |
- 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).
- 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.
- 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
SGDRegressordefaults tomax_iter=1000epochs 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].
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_)▸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
References
- [1]Machine Learning Crash Course — Linear regression: gradient descent & hyperparametersCourseGoogledevelopers.google.com
- [2]Deep Learning — Chapter 4: Numerical Computation (gradient-based optimisation)BookGoodfellow, Bengio & Courville2016deeplearningbook.org
- [3]scikit-learn User Guide — Stochastic Gradient DescentDocsscikit-learn developersscikit-learn.org
- [4]An overview of gradient descent optimization algorithmsPaperRuder2016arxiv.org
- [5]Dive into Deep Learning — 12.3 Gradient DescentBookZhang, Lipton, Li & Smolad2l.ai