Skip to content
Lambdian

Gradient descent and its variants

The optimiser behind most of machine learning: learning rates, momentum, SGD, mini-batches and Adam.

Animated explanation

The idea

Training a model means finding weights with low loss. Picture the loss as a landscape over all possible weights. You stand somewhere on it, blindfolded, and can only feel the slope under your feet. The sensible move: take a step downhill, feel again, repeat.

The gradient ∇J\nabla J points uphill, so we step along −∇J-\nabla J. The learning rate η\eta sets the step size. Too small and you crawl; too large and you overshoot and bounce, or even fly off. Almost every model in this course, from logistic regression to deep reinforcement learning, is trained by some version of this loop.

Why the learning rate is so sensitive

Near a minimum, the loss looks like a bowl 12(w−w∗)⊤H(w−w∗)\frac12(\mathbf{w}-\mathbf{w}^\ast)^\top H(\mathbf{w}-\mathbf{w}^\ast). Each step multiplies the error along the bowl's kk-th axis by (1−ηλk)(1-\eta\lambda_k), where λk\lambda_k are the eigenvalues of HH (the curvatures). Stability needs ∣1−ηλk∣<1|1-\eta\lambda_k|<1 for all kk, so η<2/λmax⁡\eta < 2/\lambda_{\max}. But progress along the flattest axis is governed by λmin⁡\lambda_{\min}.

The ratio κ=λmax⁡/λmin⁡\kappa = \lambda_{\max}/\lambda_{\min} (the condition number) therefore sets how slow plain gradient descent is. Feature scaling, momentum and adaptive methods all exist to fight bad conditioning.

Stochastic and mini-batch gradients

When the loss is an average over nn examples, the full gradient costs O(n)O(n). A random mini-batch gives an unbiased estimate for a fraction of the price. The steps are noisy, so we usually decay the learning rate over time (e.g. ηt=η0/(1+t/τ)\eta_t = \eta_0/(1+t/\tau) or a cosine schedule) and shuffle the data each epoch.

Momentum and Adam

Momentum keeps a running velocity, so consistent gradient directions accelerate while oscillating ones cancel. Adam keeps running averages of the gradient (mtm_t) and of its square (vtv_t), corrects their start-up bias, and steps by η m^t/(v^t+ϵ)\eta\,\hat m_t/(\sqrt{\hat v_t}+\epsilon): each weight gets its own effective step size. Adam with η=10−3\eta=10^{-3} is the default for neural networks; plain SGD with momentum often generalises slightly better when well tuned.

The algorithm, step by step

  1. 1
    Initialise w\mathbf{w} (zeros for convex models, small random values for networks).
  2. 2
    Repeat for each epoch: shuffle the data and split it into mini-batches.
  3. 3
    For each batch BB: compute g=1∣B∣∑i∈B∇Li(w)\mathbf{g} = \frac{1}{|B|}\sum_{i\in B}\nabla L_i(\mathbf{w}).
  4. 4
    Update: v←βv−ηg\mathbf{v} \leftarrow \beta\mathbf{v} - \eta\mathbf{g}, then w←w+v\mathbf{w} \leftarrow \mathbf{w} + \mathbf{v} (β = 0 gives plain SGD).
  5. 5
    Stop when validation loss stops improving (early stopping) or after a fixed budget.

The maths

Gradient descent

wt+1=wt−η∇J(wt)\mathbf{w}_{t+1} = \mathbf{w}_t - \eta\nabla J(\mathbf{w}_t)

Momentum

vt+1=βvt−η∇J(wt),wt+1=wt+vt+1\mathbf{v}_{t+1} = \beta\mathbf{v}_t - \eta\nabla J(\mathbf{w}_t),\qquad \mathbf{w}_{t+1} = \mathbf{w}_t + \mathbf{v}_{t+1}

Adam

mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,wt=wt−1−η mt/(1−β1t)vt/(1−β2t)+ϵm_t = \beta_1 m_{t-1} + (1-\beta_1)g_t,\quad v_t = \beta_2 v_{t-1} + (1-\beta_2)g_t^2,\quad w_t = w_{t-1} - \eta\,\frac{m_t/(1-\beta_1^t)}{\sqrt{v_t/(1-\beta_2^t)}+\epsilon}

Stability on a quadratic

0<η<2λmax⁡(H)0 < \eta < \frac{2}{\lambda_{\max}(H)}

Strengths and weaknesses

Strengths

  • Works for any differentiable loss, at any scale
  • Mini-batches make each step cheap
  • Momentum and Adam make it robust in practice

Weaknesses

  • Needs a learning rate (and schedule) to be tuned
  • Slow on badly conditioned problems without scaling
  • On non-convex losses it finds a local, not global, minimum

Reach for it when…

There is no closed-form solution, or the data is too large for one: logistic regression, neural networks, policy gradients.

Check your understanding

Question 1

Q1The loss goes up and down wildly and then becomes NaN. Most likely fix?

Question 2

Q2What does momentum mainly help with?

Question 3

Q3Why are mini-batches used instead of the full dataset?

Lambdian Lab

Three optimisers on one problem

Fit a linear regression (no bias) by minimising the MSE J(w)=1n∥y−Xw∥2J(w) = \frac1n\lVert y - Xw\rVert^2.

  • gd(X, y, lr, steps): plain batch gradient descent from zeros; return w.
  • momentum(X, y, lr, beta, steps): heavy-ball momentum.
  • sgd(X, y, lr, epochs, batch, seed): mini-batch SGD, reshuffling each epoch with np.random.default_rng(seed).
  • Then plot the loss per step for gd and momentum (matplotlib) to see the difference.
Open the labPython + NumPy runs in your browser. Sign-in keeps your code and attempts.