Deriving Gradient Descent (ML #4)
Chapters 1–3 all used the same move: compute a gradient, step against it, repeat. It worked, and it worked every time, which is exactly why it’s dangerous — nobody ever told you why the step size has a hard upper limit or why a method that converges in 3 steps and one that needs 3,000 are doing the same job.
This chapter is about the optimizers themselves. We’ll derive the convergence condition \(\eta < 2/\lambda_{\max}\), see why ill-conditioning is the real enemy, and derive Newton’s method — which uses the Hessian to get quadratic convergence at the cost of a matrix inverse per step.
By the end you will be able to derive the stability bound, predict how many iterations a problem will need before running it, and explain why Adam exists.
The general template
Every supervised model has this shape: an objective \(J(\theta)\), a gradient \(\nabla_\theta J\), and a search for the minimum. The gradient is the direction of steepest ascent, so \(-\nabla J\) is steepest descent:
\[ \theta_{t+1} = \theta_t - \eta \nabla_\theta J(\theta_t) \]
One line. Everything that follows is about the single scalar \(\eta\).
Deriving when gradient descent fails
Restrict to a quadratic objective, \(J(\theta) = \frac{1}{2}\theta^\top A\theta - b^\top\theta\) with \(A\) positive definite. Its gradient is \(A\theta - b\). Diagonalize: in the eigenbasis of \(A\) the problem separates into \(d\) independent 1-D problems, each with eigenvalue \(\lambda_i\).
The 1-D problem: minimize \(\frac{1}{2}\lambda z^2 - \mu z\), whose optimum is \(z^* = \mu/\lambda\). Gradient descent does:
\[ z_{t+1} = z_t - \eta\left(\lambda z_t - \mu\right) = z_t(1 - \eta\lambda) + \eta\mu \]
Subtract the fixed point \(z^* = \mu/\lambda\) and the \(\eta\mu\) term cancels exactly:
\[ z_{t+1} - z^* = \left(1 - \eta\lambda\right)\left(z_t - z^*\right) \]
Iterating, the error decays geometrically:
\[ \boxed{\; z_t - z^* = \left(1 - \eta\lambda\right)^{t}\left(z_0 - z^*\right) \;} \]
Everything follows from that one line. Convergence needs the multiplier’s magnitude below 1:
\[ |1 - \eta\lambda| < 1 \;\Longleftrightarrow\; 0 < \eta < \frac{2}{\lambda} \]
Two consequences, and they pull in opposite directions:
- \(\eta \ge 2/\lambda_{\max}\) diverges. The stiffest direction has multiplier magnitude \(\ge 1\), so error grows without bound. Chapter 1 saw exactly this: at \(\eta = 6/\lambda_{\max}\) the loss overflowed to
nan. - Convergence is governed by \(\lambda_{\min}\), speed by \(\lambda_{\max}\). The slowest direction contracts by \((1-\eta\lambda_{\min})^{t}\) per step — that factor sets how many iterations you need.
This is the sharp asymmetry to internalize: you are forced to pick \(\eta\) small enough for the stiffest direction (\(\eta < 2/\lambda_{\max}\)) but you’re paid for speed in the softest direction. Their gap is the condition number \(\kappa = \lambda_{\max}/\lambda_{\min}\).
import numpy as np
A = np.diag([1.0, 10.0, 100.0]) # deliberately ill-conditioned
b = np.array([1.0, 10.0, 100.0])
w_star = np.linalg.solve(A, b)
def gd_error(lr, iters):
w = np.zeros(3)
for _ in range(iters):
w -= lr * (A @ w - b)
return np.linalg.norm(w - w_star)
print("lr=0.019 (< 2/100 = 0.02, stable):")
for T in [100, 300, 1000]:
print(f" {T:5d} iters -> error {gd_error(0.019, T):.3e}")
print("lr=0.02 exactly: multiplier on the stiff direction is 1-0.02*100 = -1")
for T in [1, 50, 200]:
print(f" {T:4d} iters -> error {gd_error(0.02, T):.4f}")
The run confirms the formula precisely. With \(\eta = 0.019\):
| iterations | \(\lVert\theta_t - \theta^*\rVert\) |
|---|---|
| 100 | 1.47e-01 |
| 300 | 3.17e-03 |
| 1000 | 4.67e-09 |
At \(T = 1000\) the error is \(4.67\times 10^{-9}\), and the theory says exactly why: the soft direction decays as \(0.981^{1000} = 4.67\times 10^{-9}\). The measured error matches the closed form to four significant figures.
Now the boundary case \(\eta = 2/\lambda_{\max} = 0.02\) exactly. The stiff direction’s multiplier is \(1 - 0.02(100) = -1\): the error flips sign every step and never shrinks. The soft directions still converge, so the total error doesn’t stay constant — it plateaus at whatever they leave behind (1.0088 after 200 iterations, still dominated by the permanent oscillation).
Here is the whole stability question in one picture. For one eigenvalue \(\lambda\), the per-step multiplier \(r = 1-\eta\lambda\) multiplies the error; the iteration converges only when \(|r| < 1\):
\begin{tikzpicture}[font=\rmfamily, >=stealth]
\draw[->, thick] (-0.2,0) -- (3.4,0) node[right, font=\rmfamily\scriptsize] {$\eta$};
% divergence bands
\fill[red!14] (0,1.9) -- (0.5,1.9) -- (0.5,-1.9) -- (0,-1.9) -- cycle;
\fill[red!14] (2.0,1.9) -- (3.2,1.9) -- (3.2,-1.9) -- (2.0,-1.9) -- cycle;
% convergence band
\fill[green!14] (0.5,1.9) -- (2.0,1.9) -- (2.0,-1.9) -- (0.5,-1.9) -- cycle;
\node[font=\rmfamily\scriptsize, text=green!45!black] at (1.25,1.45) {converges};
\node[font=\rmfamily\scriptsize, text=red!60!black] at (0.25,1.45) {diverge};
\node[font=\rmfamily\scriptsize, text=red!60!black] at (2.6,1.45) {diverge};
\draw[dashed, thick] (0.5,0) -- (0.5,-1.9) node[below, font=\rmfamily\scriptsize] {$1/\lambda$};
\draw[dashed, thick] (2.0,0) -- (2.0,-1.9) node[below, font=\rmfamily\scriptsize] {$2/\lambda$};
\draw[dashed, thick] (1.0,0) -- (1.0,-1.9) node[below, font=\rmfamily\scriptsize] {$1/\lambda_{\max}$};
\node[font=\rmfamily\scriptsize, text=black!65] at (1.5,-2.35) {stable window; slow convergence inside it};
\end{tikzpicture}
The stable window has width \(\frac{2}{\lambda_{\max}} - \frac{1}{\lambda_{\max}} = \frac{1}{\lambda_{\max}}\), so for large \(\lambda_{\max}\) you have almost no room to be wrong — and the practical rule (take a fraction of \(2/\lambda_{\max}\)) exists because you rarely know \(\lambda_{\max}\) exactly.
Conditioning is the real problem
The stability bound \(\eta < 2/\lambda_{\max}\) is usually satisfiable by taking a small step. The stubborn case is ill-conditioned problems: \(\kappa \gg 1\) forces \(\eta\) small, which makes the soft directions crawl. Concretely, on \(\text{diag}(1, 10, 100)\) you’re forced to \(\eta < 0.02\) to keep the stiff direction stable, and at that step size the soft direction contracts by only 1.9% per iteration. You cannot do better with plain gradient descent — the geometry forbids it.
This is why Chapter 1’s standardization advice was not cosmetic. Scaling features changes \(\lambda_{\max}\) and \(\lambda_{\min}\) directly; centering and unit-variance columns make the spectrum far less spread. Other fixes for the same disease:
- Momentum. Accumulate a velocity \(v_{t+1} = \beta v_t + \nabla J\), step along \(v\). In the eigenbasis this multiplies the multiplier by \((1 - \eta\lambda(1-\beta)^{-1})\)-ish, damping oscillation in stiff directions while letting soft ones accumulate speed.
- Preconditioning. Change coordinates so the problem is well-conditioned. Newton’s method is the ultimate preconditioner (below); diagonal preconditioners approximate it cheaply.
Newton’s method: use the curvature
Gradient descent asks “which way is downhill?” Newton asks “if I were to walk downhill quadratically, where would I land?” That means taking a Taylor step to second order:
\[ J(\theta + \Delta) \approx J(\theta) + \nabla J(\theta)^\top \Delta + \frac{1}{2}\Delta^\top H \Delta \]
Minimize the right side over \(\Delta\). Differentiating w.r.t. \(\Delta\) and setting to zero:
\[ \nabla J(\theta) + H\Delta = 0 \;\Longrightarrow\; \Delta = -H^{-1}\nabla J(\theta) \]
Newton’s update, derived:
\[ \boxed{\; \theta_{t+1} = \theta_t - \left[\nabla^2_\theta J(\theta_t)\right]^{-1}\nabla_\theta J(\theta_t) \;} \]
The intuition behind the linear solve: in the eigenbasis, Newton knows each \(\lambda_i\) and takes an exact step along each eigendirection. For a quadratic, that means it lands on the optimum in one step, regardless of conditioning. For a general smooth function, it converges quadratically near the optimum — the number of correct digits roughly doubles each step.
Verified on the logistic regression from Chapter 3 (whose gradient is \(\frac{1}{n}\tilde{X}^\top(\hat p - y)\) and Hessian is \(\frac{1}{n}\tilde{X}^\top\text{diag}(\hat p(1-\hat p))\tilde{X}\)):
| Newton steps | loss |
|---|---|
| 1 | 0.43017309 |
| 2 | 0.38120900 |
| 3 | 0.38098730 |
| 4 | 0.38098730 (unchanged) |
Three steps to machine precision, and gradient descent needs thousands for the same answer. The doubling is visible: 6 digits, then 7, then 8.
The catch is cost. Newton’s method needs a \(d\times d\) Hessian (and its inverse) per step. For \(d = 10{,}000\) features that’s prohibitive, and the Hessian is only convenient when \(d\) is small (logistic regression) or has structure (a neural net’s per-layer Hessian, deep-learning-guide.md). Note also that Newton’s method has no stability bound on a step size — it can overshoot on strongly non-quadratic losses. This is why real implementations (scipy, PyTorch’s Newton-CG) use damped Newton, capping the step.
Full-batch vs stochastic
The gradient of a sum is a sum of per-sample gradients, so you can compute it on a subset. That gives the three standard variants:
| variant | samples per step | cost/step | noise | typical use |
|---|---|---|---|---|
| batch GD | all \(n\) | \(O(nd)\) | none | small data, convex proofs |
| stochastic (SGD) | 1 | \(O(d)\) | high | large \(n\), deep nets |
| mini-batch | \(k\) (32–1024) | \(O(kd)\) | moderate | the default in practice |
SGD’s advantage isn’t only speed — it’s that the noise acts as implicit regularization. The gradient it samples is unbiased for the full gradient, but its fluctuations let the iterate escape shallow regions and settle in wider, flatter basins, which tends to generalize better. That’s why, for identical math, SGD-trained models often beat full-batch ones out-of-sample. Mini-batches exist because vectorized matrix multiplies on \(k\) rows are dramatically faster per sample than \(k\) separate row operations.
\[\hat{g}_t = \frac{1}{k}\sum_{i \in B_t} \nabla_\theta J_i(\theta_t), \qquad \mathbb{E}[\hat{g}_t] = \nabla_\theta J(\theta_t) \]
Adam layers an adaptive step on top: it keeps a running mean \(\hat{m}\) of gradients and a running second moment \(\hat{v}\) of their squares, and divides by \(\sqrt{\hat{v}}\), which approximates a diagonal Hessian preconditioner. That’s the cheap fix for the conditioning disease above.
Pitfalls
- Picking \(\eta\) by feel. Compute \(\lambda_{\max}\) of the Hessian (a power iteration or a few steps of
eigvalsh) and use a fraction of \(2/\lambda_{\max}\). Guessing wastes hours and can silently diverge. - \(\eta = 2/\lambda_{\max}\) exactly. The stiff direction oscillates forever at constant amplitude. Stay strictly below.
- Newton on wide problems. The \(d\times d\) Hessian is intractable for large \(d\). Use it for small or structured models; use SGD/Adam otherwise.
- Undamped Newton. Without a trust region or line search, Newton steps can overshoot and increase the loss. Damped/trust-region variants are standard.
- Convergence checked on training loss only. Watch a held-out split; a model with rising train loss is diverging, one with falling train and rising validation is overfitting (Chapter 13).
- Shuffling forgotten in SGD. Correlated batches (e.g. sorted data) give biased gradients. Shuffle every epoch.
Derive \(z_{t+1} - z^* = (1-\eta\lambda)(z_t - z^*)\) for a quadratic in one dimension, and read off the convergence condition and the per-step decay rate. Why does ill-conditioning hurt even when \(\eta < 2/\lambda_{\max}\) is satisfied? A logistic regression with \(d = 50{,}000\) features: which method would you use, and what’s the concrete obstacle to the other one?
ASolution
With gradient \(\lambda z - \mu\) and optimum \(z^* = \mu/\lambda\): \(z_{t+1} = z_t - \eta(\lambda z_t - \mu) = z_t(1-\eta\lambda) + \eta\mu\); subtracting \(z^*\) gives \(z_{t+1}-z^* = (1-\eta\lambda)(z_t-z^*)\) because \(\eta\mu = \eta\lambda z^*\). Iterating multiplies the error \(t\) times, so the error is \((1-\eta\lambda)^t(z_0-z^*)\), and it decays exactly when \(|1-\eta\lambda|<1\), i.e. \(0<\eta<2/\lambda\). The per-step rate is \(|1-\eta\lambda|\), set by \(\lambda_{\min}\) for the slowest direction. Ill-conditioning hurts because the stable bound is dictated by \(\lambda_{\max}\) while the speed is set by \(\lambda_{\min}\): with \(\kappa\) large you’re forced into a tiny \(\eta\) and the soft direction then contracts by only \(1-\eta\lambda_{\min}\) per step, so conditioning — not the stability bound — sets iteration count (standardization and momentum/preconditioning both attack this). For \(d=50{,}000\), use mini-batch SGD or Adam: Newton’s per-iteration cost is a \(50{,}000\times50{,}000\) Hessian construction and factorization, which is hundreds of GB of memory and cubic time, versus a \(O(kd)\) gradient for SGD — the obstacle is that you cannot form or invert the Hessian at that dimension.
Next: Deriving k-Nearest Neighbors (ML #5) — the algorithm with no training step at all, and what the geometry of distance does to it.