Skip to content
BIASED

Gradient descent

Linear regression without the closed form: the loss surface and its shape, feature scaling and the condition number, what convergence guarantees mean, choosing the step by line search, when to stop, and losses with no formula for the minimum.

Walk instead of solve

The topic Least squares ended with two problems of the closed form. The normal equations need the d×dd \times d matrix X⊤XX^\top X and a solve that costs O(nd2+d3)O(nd^2 + d^3), out of reach for a million features. And they exist only for squared error: the Huber loss has no formula for its minimizer, and neither does any classification loss in this course.

Both problems have one answer. Instead of solving ∇Q(w)=0\nabla Q(w) = 0, walk towards that point. Start anywhere, take a small step against the gradient, repeat:

w(k+1)=w(k)−η ∇Q(w(k)).w^{(k+1)} = w^{(k)} - \eta\, \nabla Q\big(w^{(k)}\big).

The negative gradient is the direction of steepest descent, and η>0\eta > 0 is the step size, or learning rate. Both come from the topic Unconstrained optimization of Mathematics for ML. Here we look at what they do to a model.

The loss is the mean squared error from Least squares, Q(w)=1n∥Xw−y∥2Q(w) = \frac1n \lVert Xw - y \rVert^2. Its gradient is

∇Q(w)=2nX⊤(Xw−y).\nabla Q(w) = \frac2n X^\top (Xw - y).

That is two matrix–vector products: first the residuals Xw−yXw - y, then X⊤X^\top times them. A step costs O(nd)O(nd), and only the number of nonzero entries when XX is sparse. Nothing of size d×dd \times d is ever formed.

Take four points x=(0,1,2,3)x = (0, 1, 2, 3), y=(1,3,2,5)y = (1, 3, 2, 5) and the model y^=w1+w2x\hat y = w_1 + w_2 x, so XX has the columns 11 and xx. The minimum is w^=(1.1,1.1)\hat w = (1.1, 1.1) with Q(w^)=0.675Q(\hat w) = 0.675. At w(0)=0w^{(0)} = 0 we have Q=9.75Q = 9.75 and ∇Q=(−5.5,−11)\nabla Q = (-5.5, -11). With η=0.2\eta = 0.2:

step ww Q(w)Q(w)
0 (0,0)(0, 0) 9.759.75
1 (1.1,2.2)(1.1, 2.2) 4.914.91
2 (0.44,0.66)(0.44, 0.66) 2.6592.659

The loss falls. But the slope jumped from 00 past its target 1.11.1 to 2.22.2, then back to 0.660.66. The next block explains the overshoot.

The loss surface of linear regression

For least squares the loss is exactly a quadratic in ww. Its Hessian is the constant matrix A=2nX⊤XA = \frac2n X^\top X, the same at every ww. Around the minimum,

Q(w)=Q(w^)+12(w−w^)⊤A (w−w^).Q(w) = Q(\hat w) + \tfrac12 (w - \hat w)^\top A\, (w - \hat w).

The level sets of QQ are ellipses (ellipsoids for d>2d > 2) centred at w^\hat w. Their axes point along the eigenvectors of AA. Along an eigenvector with eigenvalue λ\lambda the half-axis is proportional to 1/λ1/\sqrt\lambda: a large eigenvalue means a steep, narrow direction. Note that AA is built from the features alone. The targets decide where the bottom of the bowl is; the features decide its shape.

The gradient is ∇Q(w)=A(w−w^)\nabla Q(w) = A(w - \hat w), so the error e(k)=w(k)−w^e^{(k)} = w^{(k)} - \hat w obeys

e(k+1)=(I−ηA) e(k).e^{(k+1)} = (I - \eta A)\, e^{(k)}.

The topic Unconstrained optimization analysed exactly this recursion. Let μ\mu and LL be the smallest and largest eigenvalues of AA, and κ=L/μ\kappa = L/\mu its condition number. It is the same κ(X⊤X)\kappa(X^\top X) that cost the normal equations digits in Least squares; here it costs steps. Then:

  • along an eigenvector with eigenvalue λ\lambda, each step multiplies the error by 1−ηλ1 - \eta\lambda;
  • descent converges from every start exactly when 0<η<2/L0 < \eta < 2/L;
  • the best constant step 2/(L+μ)2/(L + \mu) shrinks the error by the factor (κ−1)/(κ+1)(\kappa - 1)/(\kappa + 1) per step, so a reduction by ε\varepsilon takes about κ2ln⁡(1/ε)\tfrac\kappa2 \ln(1/\varepsilon) steps.

For the four points A=(2337)A = \begin{pmatrix} 2 & 3 \\ 3 & 7 \end{pmatrix}, with μ=0.595\mu = 0.595, L=8.405L = 8.405 and κ=14.1\kappa = 14.1. Steps above 2/L=0.2382/L = 0.238 diverge. Our η=0.2\eta = 0.2 is close to that limit. Along the steep eigenvector the factor is 1−0.2⋅8.405=−0.681 - 0.2 \cdot 8.405 = -0.68, so this component flips sign at every step: that is the zigzag of the slope. Along the flat eigenvector the factor is 0.880.88, and the error creeps. To shrink the distance to w^\hat w a thousandfold from w=0w = 0, the best step 2/9=0.2222/9 = 0.222 needs 4949 steps, and the common safe default 1/L=0.1191/L = 0.119 needs 8080.

Scaling the features

Where does the ravine come from? Look at the entries of A=2nX⊤XA = \frac2n X^\top X for the four points:

  • the off-diagonal entry 2n∑ixi=3\frac2n \sum_i x_i = 3 couples the intercept and the slope. It is there because the feature has a nonzero mean;
  • the diagonal entries 22 and 77 differ because xx has a larger second moment than the constant column.

Two operations from the topic Data, features and leakage repair the shape. Centring x−mx - m removes the coupling. Scaling by the standard deviation ss evens out the diagonal. For the standardized feature

z=x−ms=x−1.51.118z = \frac{x - m}{s} = \frac{x - 1.5}{1.118}

we get A=2IA = 2I and κ=1\kappa = 1. The level sets are circles, the gradient points straight at the minimum, and the step η=0.5\eta = 0.5 reaches w^\hat w in one step from any start.

Standardization does not change the model. Put z=(x−m)/sz = (x - m)/s into y^=v1+v2z\hat y = v_1 + v_2 z and you get a straight line in xx again. Both fits make the same predictions; only the weights are written in other units. What changes is the geometry the optimizer walks through.

One rule carries over from Data, features and leakage: mm and ss are computed on the training set only, and the same numbers are then applied to validation and test objects.

Real data: what κ costs

On four points the gain is κ=14→1\kappa = 14 \to 1. On real tables it is much larger. Take the wine data bundled with scikit-learn: predict the alcohol content of 178178 wines from the other 1212 measurements. Their standard deviations range from 0.120.12 to 314314.

We run gradient descent from w=0w = 0 with η=1/L\eta = 1/L and track the relative excess loss (Q(w(k))−Q(w^))/(Q(w(0))−Q(w^))\big(Q(w^{(k)}) - Q(\hat w)\big) / \big(Q(w^{(0)}) - Q(\hat w)\big):

features κ\kappa 10 steps 100 steps 1000 steps
raw 1.6⋅1081.6 \cdot 10^8 0.120.12 0.0850.085 0.0170.017
standardized 4545 7.8⋅10−37.8 \cdot 10^{-3} 2⋅10−82 \cdot 10^{-8} machine precision

On raw features the descent barely moves after the first steps. One measurement in the hundreds sets LL and caps the step, and the directions with tiny curvature are left almost untouched. By the estimate κ2ln⁡(1/ε)\tfrac\kappa2 \ln(1/\varepsilon), a thousandfold reduction would need about 5.5⋅1085.5 \cdot 10^8 steps.

Centring alone is not enough here: it leaves κ=1.2⋅107\kappa = 1.2 \cdot 10^7. The scales must be evened out too.

Why does κ=45\kappa = 45 remain after standardization? After it every diagonal entry of AA is 22, but the off-diagonal entries are twice the correlations between features. Correlated features tilt the ellipses away from the coordinate axes. Scaling each feature separately stretches the picture only along the axes, so it cannot straighten a tilted ellipse. That would need a rotation as well, which second-order methods effectively apply.

What is guaranteed and what it means

Most losses in this course are not quadratic: Huber, logistic, the losses of networks. The analysis carries over through two properties from Unconstrained optimization. A loss is LL-smooth if its gradient is LL-Lipschitz; for a twice differentiable loss, no Hessian eigenvalue exceeds LL in absolute value. It is μ\mu-strongly convex if every Hessian eigenvalue is at least μ>0\mu > 0, everywhere. Least squares with independent columns has both properties, with the μ\mu and LL of AA.

With η=1/L\eta = 1/L each step lowers QQ by at least ∥∇Q∥2/(2L)\lVert \nabla Q \rVert^2 / (2L) (the descent lemma). Three guarantees follow; here R=∥w(0)−w^∥R = \lVert w^{(0)} - \hat w \rVert is the starting distance.

loss guarantee for η=1/L\eta = 1/L
LL-smooth min⁡k<K∥∇Q(w(k))∥2≤2L (Q(w(0))−inf⁡Q)/K\min_{k < K} \lVert \nabla Q(w^{(k)}) \rVert^2 \le 2L\,\big(Q(w^{(0)}) - \inf Q\big)/K
convex and LL-smooth Q(w(k))−Q(w^)≤LR2/(2k)Q(w^{(k)}) - Q(\hat w) \le L R^2 / (2k)
μ\mu-strongly convex and LL-smooth ∥w(k)−w^∥2≤(1−1/κ)kR2\lVert w^{(k)} - \hat w \rVert^2 \le (1 - 1/\kappa)^k R^2

How to read them:

  • They are worst-case bounds. They say how the cost grows with LL, κ\kappa and RR, not how many steps your problem needs. For the four points the convex bound after 8080 steps promises an excess loss below 0.130.13. The actual excess is 7⋅10−77 \cdot 10^{-7}.
  • They hold for the stated step only. Above 2/L2/L a quadratic diverges, and no bound says otherwise.
  • Without convexity only the gradient is promised to be small. The point reached may be a saddle, and it depends on the start. For networks with ReLU even smoothness fails at some points, so there the bound is a guide, not a theorem.
  • Collinear features from Least squares make μ=0\mu = 0: the loss is convex but not strongly convex, and the minimizer is not unique. Least squares is still a fixed quadratic. Every step adds a vector X⊤vX^\top v, so from w=0w = 0 the iterates stay in the row space of XX and converge to the minimum-norm solution, the same X+yX^+ y that np.linalg.lstsq returns.

Choosing the step: a grid and line search

All of this needs LL, and LL is rarely known; for a network, never. Two practical answers.

A grid on a log scale. Try η=1,0.3,0.1,0.03,0.01\eta = 1, 0.3, 0.1, 0.03, 0.01 for a few hundred steps and keep the largest that does not diverge. A loss that grows from the first steps means η>2/L\eta > 2/L. On standardized wine 2/L=0.2162/L = 0.216. After 200200 steps, η=0.3\eta = 0.3 gives a loss of 5⋅10985 \cdot 10^{98}, η=0.1\eta = 0.1 sits at the minimum 0.2660.266, and η=0.01\eta = 0.01 is still at 0.3210.321.

Backtracking line search. Choose the step anew at every iteration. Compute g=∇Q(w)g = \nabla Q(w), start from a large η\eta and halve it until the step gives a sufficient decrease (the Armijo condition):

Q(w−ηg)≤Q(w)−η2∥g∥2.Q(w - \eta g) \le Q(w) - \frac\eta2 \lVert g \rVert^2.

By the descent lemma every η≤1/L\eta \le 1/L passes this test. So the search ends with η≥1/(2L)\eta \ge 1/(2L), without knowing LL. It also accepts longer steps where the gradient happens to point along a flat direction. The price is extra evaluations of QQ, each costing O(nd)O(nd), like a gradient.

On standardized wine 1/L=0.1081/L = 0.108. In 100100 backtracking steps starting from η=1\eta = 1, the accepted steps were:

η\eta 0.06250.0625 0.1250.125 0.250.25 0.50.5 11
times 1212 4141 99 1212 2626

The final gradient norm is 1.8⋅10−61.8 \cdot 10^{-6}, against 1.5⋅10−31.5 \cdot 10^{-3} after 100100 steps with the fixed η=1/L\eta = 1/L. The search cost about 300300 loss evaluations on top of the 100100 gradients.

Newton's method goes further and uses the curvature itself. On a quadratic it solves the normal equations in one step, at the price of a d×dd \times d solve per step. The topic Logistic regression uses it where dd is small.

When to stop

The textbook stopping rules: stop when ∥∇Q∥\lVert \nabla Q \rVert, or the relative decrease of QQ, falls below a tolerance. But in machine learning the training loss is not the goal. The goal is the risk on new data, as the topic What machine learning is put it. Optimization error matters only next to the statistical error.

Split wine 70/3070/30 into training and test sets, standardize with the training statistics, and run descent with η=1/L\eta = 1/L:

fit training MSE test MSE
normal equations 0.2410.241 0.3770.377
10 steps 1.7821.782 1.8531.853
30 steps 0.2420.242 0.3620.362
100 steps 0.2410.241 0.3740.374

After 3030 steps the training loss is within 0.0020.002 of the exact minimum. The test MSE of the exact fit, meanwhile, is 0.3770.377, 0.2440.244 or 0.3110.311 depending on which random split we take. The test estimate wobbles by more than 0.10.1 between splits, the noise of a validation estimate from Validation and overfitting. Steps beyond 3030 polish digits the data cannot confirm.

Hence the stopping rule of practice: watch the loss on a validation set and stop when it stops improving. This is early stopping. Note that 3030 steps even beat the exact fit on the test set here. Stopping early keeps the weights closer to the start, a mild form of what the topic Regularization will do on purpose.

Losses without a formula

Gradient descent needs only the gradient, so it works unchanged for losses with no formula for the minimizer. The Huber loss ρδ(r)\rho_\delta(r) from Least squares is quadratic for ∣r∣≤δ\lvert r \rvert \le \delta and linear beyond. Its derivative is the residual clipped to [−δ,δ][-\delta, \delta]. So for Q(w)=1n∑iρδ(yi−⟨w,xi⟩)Q(w) = \frac1n \sum_i \rho_\delta(y_i - \langle w, x_i \rangle),

∇Q(w)=−1nX⊤clip⁡(y−Xw, −δ, δ).\nabla Q(w) = -\frac1n X^\top \operatorname{clip}(y - Xw,\, -\delta,\, \delta).

The second derivative of ρδ\rho_\delta is at most 11, so QQ is LL-smooth with LL the largest eigenvalue of 1nX⊤X\frac1n X^\top X, and η=1/L\eta = 1/L is safe.

Ten points x=0,1,…,9x = 0, 1, \dots, 9 with y=(1.3,1.1,2.2,3.0,2.7,3.6,3.5,4.9,13.0,5.3)y = (1.3, 1.1, 2.2, 3.0, 2.7, 3.6, 3.5, 4.9, 13.0, 5.3) contain one outlier at x=8x = 8. Least squares gives 0.373+0.819x0.373 + 0.819x. Five thousand steps on the Huber loss with δ=1\delta = 1 reach 0.986+0.533x0.986 + 0.533x, the Huber line from Least squares. The absolute loss is not differentiable at zero residual. Its subgradient sign⁡(r)\operatorname{sign}(r) can replace the gradient, but then the steps must shrink over time.

normal equations gradient descent
needs X⊤XX^\top X and a d×dd \times d solve the gradient, O(nd)O(nd) per step
cost O(nd2+d3)O(nd^2 + d^3) once O(nd)O(nd) times about κln⁡(1/ε)\kappa \ln(1/\varepsilon) steps
losses squared error only any differentiable loss
knobs none step η\eta and number of steps
feature scale affects accuracy speed

One cost remains. Every step touches all nn objects, because the gradient is an average of nn per-object gradients. With nn in the millions one step is a full pass over the data, and most of it is redundant. An average can be estimated from a small random sample. The next topic, Stochastic and adaptive optimizers, makes that trade: minibatch gradients, why a constant step then stops short of the minimum, and momentum and per-coordinate steps (AdaGrad, RMSProp, Adam) that attack the condition number from this topic.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Gradient descent on a quadraticoptional

    Descent on ½‖Aw−b‖²: loss path and step-size condition. Self-check in the notebook.

    ~20 min · easier on a computer · Gradient descent topic read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.