Why first-order methods
Newton's method (and IRLS) needs the Hessian and a solve per step, , and touches all 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:
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 has gradient and constant Hessian , with eigenvalues to . In the eigenbasis, the error along eigenvector is multiplied by every step. So:
- Converges iff .
- With , the slowest direction contracts by per step, ; reaching accuracy takes about steps.
- The best fixed step gives rate , about steps.
The condition number sets the cost: iterations grow linearly in . 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 from with gradient descent. Describe the iterates for , and .
Show solutionHide solution
The Hessian is , so , , , and the updates decouple: and .
: is multiplied by 0, so it is solved in one step; is multiplied by 0.9, giving . The flat direction is slow: reaching needs steps.
: factors and . Both directions contract by per step; flips sign each step (the zig-zag across the valley). This is the optimal fixed step, rate , about 69 steps to .
: the factor is , so grows by 10% per step and the iteration diverges, even though still converges. The threshold is : the steep direction caps the step size, and the flat direction then dictates the number of steps. That tension is exactly what measures.
Feature scaling
For least squares, , so the conditioning is set by the regressors' scales and correlations:
- Two uncorrelated, mean-zero regressors with standard deviations 1 and 100 give and . With the flat direction needs about steps to gain six digits. After standardising, , , and one step with 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 . Centre as well as scale.
- Standardising cannot remove correlation: for two standardised regressors with correlation , has eigenvalues , so : 9 at , 19 at . Ridge's improves this to .
Rescaling the coordinates is the same as preconditioning: running gradient descent with a matrix step . Newton is the extreme case (); 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:
Successive gradients across the valley alternate in sign and cancel in ; gradients along the floor point the same way and accumulate. On a quadratic with eigenvalues in , the tuned choice , gives rate
so iterations scale with rather than . For : per step instead of . Nesterov's accelerated gradient evaluates the gradient at the look-ahead point and achieves the dependence for general smooth strongly convex functions, not just quadratics. Conjugate gradient does even better on quadratics (exact in steps in exact arithmetic) and is the standard iterative solver for large least-squares and ridge systems.
Worked example
counting iterations
Minimise from to with plain gradient descent ( and ) and with tuned heavy-ball momentum. Also try .
Show solutionHide 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 the flat direction contracts by 0.99: . With the optimal step, per step predicts about 691; the count is slightly higher because both coordinates start at 1. Momentum's rate alone predicts about 69; the tuned heavy ball has a repeated eigenvalue, which adds a factor growing linearly in , so it takes 95. That is still about 7 times faster than the best plain step, roughly the gain. At the steep direction is multiplied by per step and diverges.
Batch, stochastic and mini-batch
For a loss that averages over observations, :
| Variant | Gradient per step | Cost per step | Behaviour |
|---|---|---|---|
| Batch | exact gradient; rates above apply | ||
| Stochastic (SGD) | , one random | 1 | unbiased but noisy |
| Mini-batch | average over a random batch of size | noise variance |
A stochastic gradient is an unbiased estimate of the full one, but its noise does not vanish at the optimum (the individual 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 (and to the gradient-noise variance ).
- To converge exactly, decay the step: the Robbins–Monro conditions and (e.g. ). 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 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 .
- 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 (independent, variance ) by SGD on , one observation per step. What does the iteration compute with ? With a constant , what is the long-run standard deviation of the estimate?
Show solutionHide solution
The stochastic gradient at observation is , so the update is .
: , which is exactly the running sample mean. Its variance goes to zero: the decaying step satisfies Robbins–Monro and SGD converges.
Constant : , an exponentially weighted moving average. In steady state
a standard deviation of about that never shrinks, whatever the sample size. That is the "noise band" of constant-step SGD, with variance roughly proportional to . 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 , with estimated by a few power iterations on , 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 in the hundreds), Newton/IRLS or L-BFGS beats gradient descent comfortably. Use (S)GD when or 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 ; iterations ), "what is the largest stable step?" (), "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?" ( instead of ).
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 , what per-step contraction does tuned heavy-ball momentum achieve, compared with 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 and takes about steps at : the condition number is the cost.
- Feature scaling and centring are preconditioning: they cut , often from enormous to near 1. Correlation remains, .
- Momentum (heavy ball, Nesterov) improves the dependence from to .
- SGD and mini-batches trade exact gradients for cheap steps; constant steps leave a noise band proportional to , 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).