Skip to content
LeetQuant
QR04 Regression and Numerical Optimisation

QR04 · Regression and Numerical Optimisation · Lesson 6 of 6

Gradient Descent

Batch, stochastic and mini-batch gradient descent, step sizes and convergence on quadratics, momentum, why feature scaling matters, and worked numeric examples.

18 min

Why first-order methods

Newton's method (and IRLS) needs the Hessian and a p×pp \times p solve per step, O(np2+p3)O(np^2 + p^3), and touches all nn observations. With millions of rows or many parameters that is too expensive or impossible (no closed form for a neural network anyway). Gradient descent uses only the gradient:

βk+1=βk−η ∇f(βk).\beta_{k+1} = \beta_k - \eta\,\nabla f(\beta_k) .

The earlier lesson on gradients and Hessians showed the core convergence fact for quadratics. This lesson adds the stochastic versions, momentum, the practical role of feature scaling, and worked numbers.

Objective: predict how fast gradient descent converges from the condition number, pick a step size, explain why scaling and momentum help, and know how SGD's noise changes the picture.

Convergence on a quadratic

Least squares with loss f(β)=12n∥y−Xβ∥2f(\beta) = \tfrac1{2n}\|y - X\beta\|^2 has gradient 1nX⊤(Xβ−y)\tfrac1n X^\top(X\beta - y) and constant Hessian A=1nX⊤XA = \tfrac1n X^\top X, with eigenvalues μ=λmin⁡\mu = \lambda_{\min} to L=λmax⁡L = \lambda_{\max}. In the eigenbasis, the error along eigenvector ii is multiplied by (1−ηλi)(1 - \eta\lambda_i) every step. So:

  • Converges iff η<2/L\eta < 2/L.
  • With η=1/L\eta = 1/L, the slowest direction contracts by 1−1/κ1 - 1/\kappa per step, κ=L/μ\kappa = L/\mu; reaching accuracy ε\varepsilon takes about κln⁡(1/ε)\kappa\ln(1/\varepsilon) steps.
  • The best fixed step η=2/(L+μ)\eta = 2/(L + \mu) gives rate (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1), about κ2ln⁡(1/ε)\tfrac\kappa2\ln(1/\varepsilon) steps.

The condition number sets the cost: iterations grow linearly in κ\kappa. Near a smooth strongly convex minimum, any problem looks like this quadratic, so the same rule of thumb applies locally to logistic regression and beyond.

Worked example

step sizes on an elongated bowl

Minimise f(x,y)=12(x2+10y2)f(x, y) = \tfrac12(x^2 + 10y^2) from (1,1)(1, 1) with gradient descent. Describe the iterates for η=0.1\eta = 0.1, η=2/11\eta = 2/11 and η=0.21\eta = 0.21.

Show solution

The Hessian is diag⁡(1,10)\operatorname{diag}(1, 10), so μ=1\mu = 1, L=10L = 10, κ=10\kappa = 10, and the updates decouple: x←(1−η)xx \leftarrow (1 - \eta)x and y←(1−10η)yy \leftarrow (1 - 10\eta)y.

η=0.1=1/L\eta = 0.1 = 1/L: yy is multiplied by 0, so it is solved in one step; xx is multiplied by 0.9, giving 0.9,0.81,0.729,…0.9, 0.81, 0.729, \dots. The flat direction is slow: reaching 10−610^{-6} needs ln⁡(10−6)/ln⁡0.9≈131\ln(10^{-6})/\ln 0.9 \approx 131 steps.

η=2/11\eta = 2/11: factors 1−2/11=9/111 - 2/11 = 9/11 and 1−20/11=−9/111 - 20/11 = -9/11. Both directions contract by 0.8180.818 per step; yy flips sign each step (the zig-zag across the valley). This is the optimal fixed step, rate (κ−1)/(κ+1)=9/11(\kappa - 1)/(\kappa + 1) = 9/11, about 69 steps to 10−610^{-6}.

η=0.21\eta = 0.21: the yy factor is 1−2.1=−1.11 - 2.1 = -1.1, so ∣y∣|y| grows by 10% per step and the iteration diverges, even though xx still converges. The threshold is 2/L=0.22/L = 0.2: the steep direction caps the step size, and the flat direction then dictates the number of steps. That tension is exactly what κ\kappa measures.

Feature scaling

For least squares, A=1nX⊤XA = \tfrac1n X^\top X, so the conditioning is set by the regressors' scales and correlations:

  • Two uncorrelated, mean-zero regressors with standard deviations 1 and 100 give A≈diag⁡(1,104)A \approx \operatorname{diag}(1, 10^4) and κ=104\kappa = 10^4. With η=1/L\eta = 1/L the flat direction needs about 104ln⁡(106)≈138,00010^4\ln(10^6) \approx 138{,}000 steps to gain six digits. After standardising, A=IA = I, κ=1\kappa = 1, and one step with η=1\eta = 1 solves it.
  • A regressor with a large mean and no intercept centring (prices around 100 rather than returns) creates a near-collinearity with the intercept column, which also inflates κ\kappa. Centre as well as scale.
  • Standardising cannot remove correlation: for two standardised regressors with correlation ρ\rho, AA has eigenvalues 1±ρ1 \pm \rho, so κ=(1+∣ρ∣)/(1−∣ρ∣)\kappa = (1 + |\rho|)/(1 - |\rho|): 9 at ρ=0.8\rho = 0.8, 19 at ρ=0.9\rho = 0.9. Ridge's +λI+\lambda I improves this to (1+∣ρ∣+λ)/(1−∣ρ∣+λ)(1 + |\rho| + \lambda)/(1 - |\rho| + \lambda).

Rescaling the coordinates is the same as preconditioning: running gradient descent with a matrix step P−1∇fP^{-1}\nabla f. Newton is the extreme case P=AP = A (κ=1\kappa = 1); diagonal scaling is the cheap version. Adaptive methods such as Adam keep a running per-coordinate estimate of gradient magnitude and divide by it, a diagonal preconditioner learned on the fly.

Momentum

Gradient descent zig-zags across a narrow valley and creeps along its floor. Heavy-ball momentum keeps a running velocity:

vk+1=βvk−η∇f(xk),xk+1=xk+vk+1.v_{k+1} = \beta v_k - \eta\nabla f(x_k), \qquad x_{k+1} = x_k + v_{k+1} .

Successive gradients across the valley alternate in sign and cancel in vv; gradients along the floor point the same way and accumulate. On a quadratic with eigenvalues in [μ,L][\mu, L], the tuned choice η=4/(L+μ)2\eta = 4/(\sqrt L + \sqrt\mu)^2, β=((κ−1)/(κ+1))2\beta = \big((\sqrt\kappa - 1)/(\sqrt\kappa + 1)\big)^2 gives rate

κ−1κ+1instead ofκ−1κ+1,\frac{\sqrt\kappa - 1}{\sqrt\kappa + 1} \quad\text{instead of}\quad \frac{\kappa - 1}{\kappa + 1},

so iterations scale with κ\sqrt\kappa rather than κ\kappa. For κ=100\kappa = 100: 9/11≈0.8189/11 \approx 0.818 per step instead of 99/101≈0.98099/101 \approx 0.980. Nesterov's accelerated gradient evaluates the gradient at the look-ahead point xk+βvkx_k + \beta v_k and achieves the κ\sqrt\kappa dependence for general smooth strongly convex functions, not just quadratics. Conjugate gradient does even better on quadratics (exact in pp steps in exact arithmetic) and is the standard iterative solver for large least-squares and ridge systems.

Worked example

counting iterations

Minimise 12(x2+100y2)\tfrac12(x^2 + 100y^2) from (1,1)(1, 1) to ∥(x,y)∥<10−6\|(x, y)\| < 10^{-6} with plain gradient descent (η=1/L\eta = 1/L and η=2/(L+μ)\eta = 2/(L + \mu)) and with tuned heavy-ball momentum. Also try η=0.021\eta = 0.021.

Show solution
import math

def run(lams, eta, beta=0.0, tol=1e-6, max_iter=100_000):
    """Minimise 0.5 * sum(lam_i * x_i^2) from x = (1, ..., 1); return steps to |x| < tol."""
    x = [1.0] * len(lams)
    v = [0.0] * len(lams)
    for k in range(1, max_iter + 1):
        for i, lam in enumerate(lams):
            v[i] = beta * v[i] - eta * lam * x[i]  # heavy-ball momentum
            x[i] += v[i]
        if math.sqrt(sum(xi * xi for xi in x)) < tol:
            return k
    return None

L, mu = 100.0, 1.0
print("GD, eta = 1/L:      ", run([mu, L], 1 / L))
print("GD, eta = 2/(L+mu): ", run([mu, L], 2 / (L + mu)))
eta = 4 / (math.sqrt(L) + math.sqrt(mu)) ** 2
beta = ((math.sqrt(L) - math.sqrt(mu)) / (math.sqrt(L) + math.sqrt(mu))) ** 2
print("heavy ball:         ", run([mu, L], eta, beta))
print("GD, eta = 0.021:    ", run([mu, L], 0.021))
GD, eta = 1/L:       1375
GD, eta = 2/(L+mu):  709
heavy ball:          95
GD, eta = 0.021:     None

Check against theory. With η=1/L=0.01\eta = 1/L = 0.01 the flat direction contracts by 0.99: ln⁡(10−6)/ln⁡0.99≈1375\ln(10^{-6})/\ln 0.99 \approx 1375. With the optimal step, 0.98020.9802 per step predicts about 691; the count is slightly higher because both coordinates start at 1. Momentum's rate 9/119/11 alone predicts about 69; the tuned heavy ball has a repeated eigenvalue, which adds a factor growing linearly in kk, so it takes 95. That is still about 7 times faster than the best plain step, roughly the κ\sqrt\kappa gain. At η=0.021>2/L\eta = 0.021 > 2/L the steep direction is multiplied by −1.1-1.1 per step and diverges.

Batch, stochastic and mini-batch

For a loss that averages over observations, f(β)=1n∑ifi(β)f(\beta) = \tfrac1n\sum_i f_i(\beta):

VariantGradient per stepCost per stepBehaviour
Batch1n∑i∇fi\tfrac1n\sum_i\nabla f_innexact gradient; rates above apply
Stochastic (SGD)∇fi\nabla f_i, one random ii1unbiased but noisy
Mini-batchaverage over a random batch of size BBBBnoise variance ∝1/B\propto 1/B

A stochastic gradient is an unbiased estimate of the full one, but its noise does not vanish at the optimum (the individual ∇fi\nabla f_i do not all vanish there). Consequences:

  • With a constant step, SGD converges quickly at first and then fluctuates in a band around the optimum whose size is proportional to η\eta (and to the gradient-noise variance /B/B).
  • To converge exactly, decay the step: the Robbins–Monro conditions ∑kηk=∞\sum_k\eta_k = \infty and ∑kηk2<∞\sum_k\eta_k^2 < \infty (e.g. ηk∝1/k\eta_k \propto 1/k). In practice: a constant step, then step down or decay, and average the late iterates (Polyak–Ruppert averaging).
  • Quadrupling the batch halves the gradient noise's standard deviation at four times the cost per step. Mini-batches of tens to thousands use vectorised hardware well; returns to larger batches diminish once the noise is no longer the bottleneck.
  • Each epoch (one pass over the data) of SGD makes nn cheap updates, versus one exact step for batch GD. Early in training, when you are far from the optimum, many rough steps beat one precise one; this is why SGD dominates for large nn.
  • Shuffle the data each epoch. For time series, gradient-descent fitting does not change the validation rules: the model must still be trained only on the past.

Worked example

SGD for a mean

Estimate the mean of a stream y1,y2,…y_1, y_2, \dots (independent, variance σ2\sigma^2) by SGD on f(m)=12E[(y−m)2]f(m) = \tfrac12\mathbb E[(y - m)^2], one observation per step. What does the iteration compute with ηk=1/k\eta_k = 1/k? With a constant η=0.1\eta = 0.1, what is the long-run standard deviation of the estimate?

Show solution

The stochastic gradient at observation kk is −(yk−m)-(y_k - m), so the update is mk=mk−1+ηk(yk−mk−1)m_k = m_{k-1} + \eta_k(y_k - m_{k-1}).

ηk=1/k\eta_k = 1/k: mk=k−1kmk−1+1kykm_k = \tfrac{k-1}{k}m_{k-1} + \tfrac1k y_k, which is exactly the running sample mean. Its variance σ2/k\sigma^2/k goes to zero: the decaying step satisfies Robbins–Monro and SGD converges.

Constant η=0.1\eta = 0.1: mk=0.9 mk−1+0.1 ykm_k = 0.9\,m_{k-1} + 0.1\,y_k, an exponentially weighted moving average. In steady state

Var⁡(m)=η2σ21−(1−η)2=η σ22−η=0.11.9σ2≈0.053 σ2,\operatorname{Var}(m) = \frac{\eta^2\sigma^2}{1 - (1 - \eta)^2} = \frac{\eta\,\sigma^2}{2 - \eta} = \frac{0.1}{1.9}\sigma^2 \approx 0.053\,\sigma^2,

a standard deviation of about 0.23σ0.23\sigma that never shrinks, whatever the sample size. That is the "noise band" of constant-step SGD, with variance roughly proportional to η\eta. It is also why a constant step can be a feature: it tracks a drifting target, which is what an EWMA volatility or mean estimator is for.

Practical checklist and interview angle

  • Standardise features; check the loss decreases (plot it); if it oscillates or blows up, halve the step.
  • A standard starting point for a least-squares-type loss is η≈1/L\eta \approx 1/L, with LL estimated by a few power iterations on AA, or use a backtracking line search for batch GD.
  • Stop on a relative change in loss or a small gradient norm, or by validation error (early stopping, which regularises much like ridge).
  • For small, smooth problems (logistic regression with pp in the hundreds), Newton/IRLS or L-BFGS beats gradient descent comfortably. Use (S)GD when nn or pp is huge, or the model has no useful Hessian.

Interview questions here are usually quantitative: "why does unscaled data slow gradient descent?" (condition number of X⊤XX^\top X; iterations ∝κ\propto\kappa), "what is the largest stable step?" (2/L2/L), "why does SGD not converge with a fixed step and what do you do?" (noise at the optimum; decay or average), and "what does momentum buy?" (κ\sqrt\kappa instead of κ\kappa).

Knowledge check

A least-squares problem has two uncorrelated, mean-zero regressors with standard deviations 1 and 10 (no standardisation). What is the condition number of the Hessian, which drives gradient descent's iteration count?

Knowledge check

For a quadratic with condition number κ=100\kappa = 100, what per-step contraction does tuned heavy-ball momentum achieve, compared with (κ−1)/(κ+1)≈0.98(\kappa - 1)/(\kappa + 1) \approx 0.98 for the best fixed gradient step?

Knowledge check

You run SGD with batch size 1 and a constant learning rate on a least-squares problem. After the loss stops falling, what do the iterates do?

Knowledge check

Two standardised regressors have correlation 0.8. What is the condition number of their correlation matrix (the least-squares Hessian up to scale)?

Key takeaways

  • On a quadratic (least squares), gradient descent needs η<2/L\eta < 2/L and takes about κln⁡(1/ε)\kappa\ln(1/\varepsilon) steps at η=1/L\eta = 1/L: the condition number is the cost.
  • Feature scaling and centring are preconditioning: they cut κ\kappa, often from enormous to near 1. Correlation remains, κ=(1+∣ρ∣)/(1−∣ρ∣)\kappa = (1 + |\rho|)/(1 - |\rho|).
  • Momentum (heavy ball, Nesterov) improves the dependence from κ\kappa to κ\sqrt\kappa.
  • SGD and mini-batches trade exact gradients for cheap steps; constant steps leave a noise band proportional to η\eta, so decay the step or average the iterates to converge.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).