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 matrix and a solve that costs , 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 , walk towards that point. Start anywhere, take a small step against the gradient, repeat:
The negative gradient is the direction of steepest descent, and 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, . Its gradient is
That is two matrix–vector products: first the residuals , then times them. A step costs , and only the number of nonzero entries when is sparse. Nothing of size is ever formed.
Take four points , and the model , so has the columns and . The minimum is with . At we have and . With :
| step | ||
|---|---|---|
| 0 | ||
| 1 | ||
| 2 |
The loss falls. But the slope jumped from past its target to , then back to . The next block explains the overshoot.
The loss surface of linear regression
For least squares the loss is exactly a quadratic in . Its Hessian is the constant matrix , the same at every . Around the minimum,
The level sets of are ellipses (ellipsoids for ) centred at . Their axes point along the eigenvectors of . Along an eigenvector with eigenvalue the half-axis is proportional to : a large eigenvalue means a steep, narrow direction. Note that is built from the features alone. The targets decide where the bottom of the bowl is; the features decide its shape.
The gradient is , so the error obeys
The topic Unconstrained optimization analysed exactly this recursion. Let and be the smallest and largest eigenvalues of , and its condition number. It is the same that cost the normal equations digits in Least squares; here it costs steps. Then:
- along an eigenvector with eigenvalue , each step multiplies the error by ;
- descent converges from every start exactly when ;
- the best constant step shrinks the error by the factor per step, so a reduction by takes about steps.
For the four points , with , and . Steps above diverge. Our is close to that limit. Along the steep eigenvector the factor is , so this component flips sign at every step: that is the zigzag of the slope. Along the flat eigenvector the factor is , and the error creeps. To shrink the distance to a thousandfold from , the best step needs steps, and the common safe default needs .
Scaling the features
Where does the ravine come from? Look at the entries of for the four points:
- the off-diagonal entry couples the intercept and the slope. It is there because the feature has a nonzero mean;
- the diagonal entries and differ because has a larger second moment than the constant column.
Two operations from the topic Data, features and leakage repair the shape. Centring removes the coupling. Scaling by the standard deviation evens out the diagonal. For the standardized feature
we get and . The level sets are circles, the gradient points straight at the minimum, and the step reaches in one step from any start.
Standardization does not change the model. Put into and you get a straight line in 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: and 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 . On real tables it is much larger. Take the wine data bundled with scikit-learn: predict the alcohol content of wines from the other measurements. Their standard deviations range from to .
We run gradient descent from with and track the relative excess loss :
| features | 10 steps | 100 steps | 1000 steps | |
|---|---|---|---|---|
| raw | ||||
| standardized | machine precision |
On raw features the descent barely moves after the first steps. One measurement in the hundreds sets and caps the step, and the directions with tiny curvature are left almost untouched. By the estimate , a thousandfold reduction would need about steps.
Centring alone is not enough here: it leaves . The scales must be evened out too.
Why does remain after standardization? After it every diagonal entry of is , 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 -smooth if its gradient is -Lipschitz; for a twice differentiable loss, no Hessian eigenvalue exceeds in absolute value. It is -strongly convex if every Hessian eigenvalue is at least , everywhere. Least squares with independent columns has both properties, with the and of .
With each step lowers by at least (the descent lemma). Three guarantees follow; here is the starting distance.
| loss | guarantee for |
|---|---|
| -smooth | |
| convex and -smooth | |
| -strongly convex and -smooth |
How to read them:
- They are worst-case bounds. They say how the cost grows with , and , not how many steps your problem needs. For the four points the convex bound after steps promises an excess loss below . The actual excess is .
- They hold for the stated step only. Above 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 : 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 , so from the iterates stay in the row space of and converge to the minimum-norm solution, the same that
np.linalg.lstsqreturns.
Choosing the step: a grid and line search
All of this needs , and is rarely known; for a network, never. Two practical answers.
A grid on a log scale. Try for a few hundred steps and keep the largest that does not diverge. A loss that grows from the first steps means . On standardized wine . After steps, gives a loss of , sits at the minimum , and is still at .
Backtracking line search. Choose the step anew at every iteration. Compute , start from a large and halve it until the step gives a sufficient decrease (the Armijo condition):
By the descent lemma every passes this test. So the search ends with , without knowing . It also accepts longer steps where the gradient happens to point along a flat direction. The price is extra evaluations of , each costing , like a gradient.
On standardized wine . In backtracking steps starting from , the accepted steps were:
| times |
The final gradient norm is , against after steps with the fixed . The search cost about loss evaluations on top of the 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 solve per step. The topic Logistic regression uses it where is small.
When to stop
The textbook stopping rules: stop when , or the relative decrease of , 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 into training and test sets, standardize with the training statistics, and run descent with :
| fit | training MSE | test MSE |
|---|---|---|
| normal equations | ||
| 10 steps | ||
| 30 steps | ||
| 100 steps |
After steps the training loss is within of the exact minimum. The test MSE of the exact fit, meanwhile, is , or depending on which random split we take. The test estimate wobbles by more than between splits, the noise of a validation estimate from Validation and overfitting. Steps beyond 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 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 from Least squares is quadratic for and linear beyond. Its derivative is the residual clipped to . So for ,
The second derivative of is at most , so is -smooth with the largest eigenvalue of , and is safe.
Ten points with contain one outlier at . Least squares gives . Five thousand steps on the Huber loss with reach , the Huber line from Least squares. The absolute loss is not differentiable at zero residual. Its subgradient can replace the gradient, but then the steps must shrink over time.
| normal equations | gradient descent | |
|---|---|---|
| needs | and a solve | the gradient, per step |
| cost | once | times about steps |
| losses | squared error only | any differentiable loss |
| knobs | none | step and number of steps |
| feature scale affects | accuracy | speed |
One cost remains. Every step touches all objects, because the gradient is an average of per-object gradients. With 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.
Answers are saved on the server and tied to this browser until you sign in.