Walk down a hillside in thick fog. Gradient descent feels only the slope under its feet, and then needs to be told how long a stride to take. Too short is slow. Too long overshoots, and past a limit it falls off the other side (P1.F3). The right stride depends on how sharply the ground bends, and gradient descent does not measure that.
Newton’s method measures it. It feels the slope and the bend (the second derivative, P1.C8), builds a small bowl that matches both, and jumps to the bottom of that bowl. If the ground really is a bowl, it arrives in one step. If the ground is not, the bowl can be a poor guide, and this lesson shows how. It also explains why almost no large neural network is trained this way.
From slope and bend to a step
P1.C8 built the quadratic model of a function around the point : the value, plus the slope times the step , plus half the curvature times .
This is a parabola in . If it opens upward and has a lowest point. To find it, set the derivative of the right-hand side with respect to to zero: . So the bottom is at , and Newton’s method repeats
There is a second way to read the same formula. Finding a minimum means solving the equation . Draw the tangent line of at the current (its slope is ) and move to the point where that line crosses zero: that is . This is the root-finding method that Newton’s name is attached to, applied to . Keep this second reading in mind: it looks for the zero of and nothing more.
Compare with gradient descent, . Newton’s method is gradient descent with the step size , worked out again at every point from the local curvature. No step size has to be chosen.
On a quadratic: one step, whatever the curvature
Take , which has and . From : , , and the step is , so Newton’s method lands on , the minimum. The parabola it jumps to is itself, because is already a parabola.
Gradient descent with gives as well. With it moves only to . P1.F3 showed that the error is multiplied by at every step. With that factor is exactly : the best possible step size is the reciprocal of the curvature, and Newton’s method finds it by itself.
Now make the bowl five times sharper, . At : , , and Newton’s step is still : it lands on . A fixed would now multiply the error by and blow up, because the safe range shrank to . Newton’s step adapts to the curvature, and a fixed step size does not.
A function that is not a quadratic
For the slope is and the curvature is . The minimum is where , at , and there . Start at and use a calculator for the second step.
- At : , , step , so .
- At : , , step , so .
- Next: , then , then .
The error after each step, for Newton’s method and for gradient descent with (running the code confirms every entry):
| Step | Newton | GD, |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 | ||
| 5 |
Newton’s errors fall like . The number of correct decimal places goes roughly , so it roughly doubles at every step. This is quadratic convergence: the new error is about a constant times the square of the old one, . Here (the ratios settle near ). Gradient descent has linear convergence: the error is multiplied by about the same factor every step ( here), so it needs steps to get below , against for Newton’s method.
Quadratic convergence is a promise with conditions. It holds when at the minimum, when is smooth enough (its second derivative must not jump around), and when the start is close enough to . The next sections are about what happens when the last condition fails. One honest comparison first: gradient descent with the perfect step size also needs only steps on this function. The gain of Newton’s method is that it does not need to be told that number.
The widget: Newton against gradient descent
Both methods start at the same . Blue dots are gradient descent. Pink squares are Newton’s method, and the dashed pink parabola is the model it jumps to from its current square; the pink diamond is the parabola’s lowest (or highest) point. The chart shows each method’s distance to the minimum on a log scale. Switch functions, drag the start, change , and turn on damped Newton (explained below) to see the failures and the repair.
Things to try, all checked against the widget’s own rules (“within ” means the error is below at that step; the widget runs 12 steps):
- Smooth and convex, the defaults (start , ). Newton’s method is within at step 5. Gradient descent has error after 12 steps (it needs 83). Press the button that sets at the minimum (): gradient descent now arrives at step 5 too.
- Quadratic, start 4. Newton’s method is exact at step 1, for any . Gradient descent with is exact at step 1 as well. At (which is exactly ) it bounces for ever. At the error grows by a factor each step: after 12 steps .
- Smooth and convex, start . There the function is almost a straight line, so is tiny and Newton’s first jump is , to . The function is convex and Newton’s method still goes the wrong way for a long time: at , is huge, so it walks back only one unit per step (60 steps in all). Gradient descent with is within at step 8. Tick damped Newton and Newton’s method arrives at step 6.
- Two valleys and a hill, start 0.5. Here , so the parabola opens downward and Newton’s step goes to its top. It moves , the local maximum, and three of its steps raise . Gradient descent with walks toward the right-hand valley. With damped Newton the path ends at the minimum, , at step 6.
- Newton cycles, start 0. The step from goes to and the step from goes back to , for ever. Damped Newton goes and arrives at step 5. From start the pure steps jump around (, , , , then ) before settling down toward the minimum near .
- Convex, yet Newton diverges, start 2. This function has everywhere. Newton’s steps go and the path stops at step 5 when passes one million. From start it converges at step 5. The dividing line is : start at and it converges (step 7), start at and it escapes (step 9). Gradient descent with reaches the minimum at step 4, so the more elaborate method is not always the better one.
Many variables
For several parameters, the second derivative becomes the Hessian matrix (P1.C8) and the slope becomes the gradient . The quadratic model is , and setting its gradient to zero gives Newton’s step
In practice the inverse is never formed. The step is the solution of the linear system , and np.linalg.solve does that faster and more accurately than inverting (P1.B9).
P1.C8 did this once. On the loss of P0.2 from the step is , which lands on , the minimum with , in one step. Gradient descent on the same loss is held back by the condition number (P1.C8).
Now the ravine of P1.F5, , with . From the gradient is and the Newton step is for every : it lands exactly on for , and . Plain gradient descent with needs , and steps (P1.F5). Turn the bowl by and the answer does not change: the Hessian for becomes , the step solves the full system, and the minimum is still reached in one step (to rounding error of about , as the second code cell shows). Dividing each coordinate by its own scale, as adaptive methods do, cannot fix such a tilted valley: for the diagonal of this the condition number stays (P1.F5). Newton’s method uses the off-diagonal numbers too, and those hold the tilt.
Go deeper Why Newton's step does not care how the axes are chosen
Describe the same loss in new coordinates with an invertible matrix (a stretch, a turn, or any mix). In the new coordinates the gradient is and the Hessian is . Newton’s step there is , and mapping it back with gives : the same step in the original coordinates. Gradient descent is different: its step in the new coordinates, , maps back to , which is not . So the speed of gradient descent depends on how the problem is written (this is why rescaling the inputs helps, P3.A11), and Newton’s method is immune to that.
Least squares and logistic regression
Linear regression with the loss has gradient and a constant Hessian . The loss is a quadratic in , so one Newton step from any starting weights lands on the minimum, and that minimum satisfies : the normal equations of P3.A2. Solving the normal equations is one Newton step. (Averaging the loss over the examples divides both the gradient and the Hessian by , so the step does not change.) The step needs to be invertible, which fails when two features are copies of each other; the fix of adding comes up below.
Logistic regression (P3.A7) has no closed form, but its loss is convex and the number of weights is small. Newton’s method on it is classical, and it is the idea behind the iteratively reweighted least squares that statistical software uses for it. The third code cell below counts the steps on a small data set: Newton’s method needs 7 steps, and gradient descent with the standard safe step size (where bounds the curvature) needs 302, both counted until the gradient norm is below .
Where Newton’s method goes wrong
Newton’s method trusts the parabola. Every failure is a case where the parabola is a bad copy of , or where it has no bottom to jump to.
1. The curve bends the wrong way. On the two-valley curve of P1.F3, at the slope is and the curvature is . The parabola opens downward. Its stationary point is a top, and Newton’s step goes there, to . The function value rises from to . The next steps are and , which is the local maximum of . Gradient descent from the same point with slides downhill into the valley at .
This is the core weakness. Newton’s method solves (second reading above), and a maximum and a saddle solve it as well as a minimum does. Near a maximum it converges as fast as near a minimum. In many variables the same happens when has a negative eigenvalue (P1.B12, P1.C8). For , a saddle (P1.F2), the Hessian is , and from Newton’s step goes straight to , the saddle, in one step. Gradient descent with multiplies by and by at every step, so after 30 steps it has left the saddle along (at ). From almost every start, gradient descent is pushed away from a saddle, slowly (started exactly on it would converge to the saddle). Newton’s method is pulled in.
2. Almost no curvature. On from the curvature is and the slope is , so the step is . In one dimension a tiny means “the parabola is very wide, so its bottom is very far away”. When exactly there is no bottom at all and the step is undefined.
3. Far from the minimum. The parabola is only a local model. The function has everywhere, so it is convex, yet from the Newton path is : each jump is bigger than the last. The curve makes Newton’s method alternate for ever. Even for a convex function, quadratic convergence is a promise about the start being close.
4. A singular Hessian. If has an eigenvalue , the system has no solution or infinitely many. For the Hessian is and the gradient is : the second equation reads , and np.linalg.solve raises an error. If the eigenvalue is tiny but not zero, the step is enormous: with the step along is . This is the many-variable version of failure 2.
Repairs
Each of these is a family of methods with its own lesson in a numerical-optimization course. Here is the idea of each, in a few lines.
- Damping and line search. Use the Newton direction but do not trust the full length: halve the step until really drops. The widget’s damped Newton does this. It also uses in place of , with a floor of , so that a negative curvature no longer turns the step uphill and a tiny one does not blow it up. From on the two-valley curve it ends at the minimum (step 6), from on it arrives at step 6, and on the cycling curve it reaches the minimum at step 5. Near a minimum it takes the full Newton step, so the fast convergence stays.
- Trust regions. Decide how far the parabola can be trusted (a radius). Take the best step inside that radius. If the parabola predicted the drop well, enlarge the radius; if it did not, shrink it.
- Adding a multiple of the identity. Use . The eigenvalues of are the old ones plus , so if is bigger than the size of the most negative eigenvalue () they are all positive, and the matrix is invertible. For this is Newton’s step. For a large it is , a small gradient step with . On at (where and ) the step is for , for and for . On the two-valley curve at , turns the curvature into and the step becomes , downhill, to with . This is the Levenberg–Marquardt idea (Levenberg 1944, Marquardt 1963, for least-squares fitting); ridge regression adds the same kind of term (P3.A6).
- Quasi-Newton methods replace by an estimate built from the gradients seen so far. Hessian-vector products avoid ever writing down. Both are in boxes below.
Go deeper Gauss–Newton and Levenberg–Marquardt for least squares
For a loss made of residuals (prediction minus target), let be the matrix of derivatives of the residuals (the Jacobian, P1.C7). The gradient is , and the Hessian is . Gauss–Newton keeps only the first part: it solves . The matrix is positive semi-definite (it has no negative curvature), and it needs no second derivatives. It can still be singular, which is why the Levenberg–Marquardt fix below is needed. It is exact when the residuals are linear in , which is linear regression and its normal equations. Levenberg–Marquardt solves and adjusts during the run. These are standard tools for fitting curves to data, for example in SciPy’s least_squares.
Go deeper Quasi-Newton methods: learning the curvature from gradients
Newton’s method needs . But is how fast changes, and two slopes at two points show that. In one variable, replace by . This is the secant method applied to . On with and the errors are , , , , , , . It is a little slower than Newton’s method (its order of convergence is about , not ) and it never computes a second derivative.
In many variables the same idea is the requirement that the new Hessian estimate satisfy . BFGS (found independently by Broyden, Fletcher, Goldfarb and Shanno, all in 1970) updates or its inverse by a small correction at every step. It still stores an matrix, so for large it has the same memory problem. L-BFGS (Liu and Nocedal, 1989) stores only the last pairs of vectors (the parameter change and the gradient change), often between 5 and 20, which costs about numbers, and computes the step from them without ever forming a matrix. It is a common choice for medium-sized, full-batch problems and is the default solver of scikit-learn’s LogisticRegression. The difficulty with noisy mini-batch gradients is that the gradient differences it relies on are then mostly noise, and making quasi-Newton methods work in that setting is a research topic.
Go deeper Hessian-free methods: Newton's step from Hessian-vector products only
The step solves . The conjugate gradient method solves such a system (for positive definite ) using only products for a sequence of vectors : in exact arithmetic it finishes in at most iterations, and stopping after a few gives an approximate step. A Hessian-vector product is cheap without the Hessian: it is the change of the gradient along , , or computed exactly by differentiating the gradient (automatic differentiation, P1.C10), at a cost of a small multiple of one gradient. So a Newton-like step needs memory of order and no matrix. This is the idea of Newton-CG and of the Hessian-free optimization that Martens popularized for neural networks around 2010; it is why the second-order methods that are used for large models work with products and not with matrices. A damping term is normally added, and each conjugate-gradient iteration costs about as much as one more pass over the data.
Go deeper Newton's method when the second derivative is zero at the minimum
The function has its minimum at with , so a condition of quadratic convergence fails. Newton’s step is : the error is multiplied by at every step, which is linear convergence: from it goes . That is still much better than gradient descent here (with it is at after 5 steps and, as P1.F3 found, at after 100), because . The general rule: when vanishes at the minimum, Newton’s method slows to linear convergence, and when it is near zero the parabola is almost flat and the steps are large and unreliable.
Why it is rarely used at scale
The case for Newton’s method is the number of steps: five instead of eighty-three, seven instead of three hundred. The case against is the price of each step and a few more things that go wrong for neural networks.
- Memory. A model with parameters has an Hessian. For that is entries, about terabytes in 32-bit numbers (P1.C8). For it is entries, bytes. For a model with parameters (the size reported for GPT-3) it is about entries, around bytes.
- Time. A dense solve of costs of order operations: about with a Cholesky factorization (for a positive definite ) and about with the LU method that
np.linalg.solveuses. Taking and gives for a single step: at an assumed operations per second that is about a hundred years (about twice as long with LU). A gradient costs about as much as a pass over the data. - Noise. The training loss is an average over millions of examples, and a mini-batch (P1.F4) gives a noisy estimate of its gradient and of its Hessian. Newton’s method divides by the curvature, so directions with small curvature get large steps, and an error in a small curvature is amplified. If the true curvature is and the gradient is , the step is ; a mini-batch estimate of or gives or , and an estimate at or below gives a huge or wrong-way step.
- Non-convexity. The loss of a network has saddles and regions of negative curvature, where plain Newton’s method is drawn to the wrong kind of point (above). The repairs help, and cost more per step.
- Cost against steps. For logistic regression with weights and examples, a gradient costs about operations. A Newton step builds the Hessian (about ) and solves (order ). When is at least about , that is roughly times more per step (if is smaller, the solve dominates). With and times fewer steps, Newton’s method wins easily. With weights, gradient descent would have to need about times more steps for Newton’s method to break even, and the -entry Hessian could not even be stored. Newton’s method wins when the number of parameters is small, and the advantage disappears as it grows.
Where second-order ideas do appear:
- Small and medium problems. Newton-type solvers and L-BFGS fit logistic regression and many other classical models, and are standard in statistics software. L-BFGS is also used for full-batch problems of moderate size.
- Least squares. Gauss–Newton and Levenberg–Marquardt, above.
- Curvature as a research tool for networks. Estimating the largest curvature with Hessian-vector products (P1.C8), natural-gradient methods and cheaper preconditioners such as K-FAC and Shampoo (proposed around 2015 and 2018) are studied as ways to get some of the benefit of Newton’s method at a price like that of a gradient. How well they compare with Adam-style methods depends on the model and the setting, and it is still an active research question.
What does train most deep networks is first-order: SGD with momentum, and Adam and its relatives (P4.13). They use only gradients. A rescaling by the size of recent gradients is not curvature (P1.F5), so these methods are not second-order methods, however much their step may look like a division.
The recipe in one place
Intuition
Newton’s method draws a bowl that matches the ground at your feet (height, slope and bend) and walks to the bottom of that bowl. If the ground is a bowl, you arrive at once. Near the bottom of a smooth valley the bowl is a very good copy, so each step roughly doubles the number of correct digits. Far away the bowl can be a bad copy: if the ground bends the wrong way you walk to a hilltop, if it is almost flat the bowl’s bottom is miles away, and if the bowl does not exist (no curvature in some direction) there is nowhere to go. The repairs shorten the walk, or bend the bowl upward, or only trust it nearby.
The price is that you must measure the bend in every direction at once, and for a model with a million parameters that is a million-by-million table.
Math
One variable: . This is gradient descent with , and Newton’s root-finding method applied to .
Many variables: , computed by solving .
Convergence: if , is continuous and is close enough to , then
For gradient descent on a quadratic, , which is for .
Quadratic: equals its own model, so one step reaches the minimum when is positive definite.
Failures: (or with a negative eigenvalue): the stationary point of the model is a top or a saddle. : . singular: no unique solution.
Repairs: with eigenvalues ; step halving until with (the widget’s rule); trust regions; BFGS, L-BFGS; conjugate gradient with products.
Cost: memory , a dense solve of order operations ( by Cholesky for positive definite , about by LU).
Code
import numpy as np
def newton(grad, hess, theta, steps):
for _ in range(steps):
g, H = grad(theta), hess(theta)
theta = theta + np.linalg.solve(H, -g) # solve H d = -g, never inv(H)
return thetaFor a model with many parameters you would not call hess. PyTorch can compute a Hessian-vector product by differentiating the gradient a second time (torch.autograd.grad with create_graph=True), and scipy.optimize.minimize(method="L-BFGS-B") or "Newton-CG" give ready-made solvers for medium problems.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
The second cell is the many-variable version: the one-step landings, a saddle, a singular Hessian, and least squares.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The third cell counts the steps on a small logistic regression, with the data made by a formula so that every run gives the same numbers.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Check your understanding
For , where does one Newton step from land?
Here and , so the step is and the landing point is . A quadratic is its own quadratic model, so the jump to the bottom of the model is a jump to the minimum. Newton's method has no step size to tune, and a large curvature makes its step smaller, not larger.
At the current point and . What does Newton's step do?
The step is , which is to the left, while a negative slope means falls to the right. With negative curvature the parabola opens downward and its only stationary point is a top. The step is perfectly well defined; it just goes to the wrong kind of point. It would stay put only if .
Newton's method has quadratic convergence and the error is now about , with the constant near 1. What error should the next two steps give, roughly?
The new error is about times the square of the old one, so the number of correct digits roughly doubles: . A constant factor per step is linear convergence, the behavior of gradient descent. The rate is predictable (given the conditions near a minimum), and not having a step size does not change that.
Why is a dense Newton step impractical for a network with parameters?
The Hessian is , so gives entries, and a dense solve costs of order operations. Networks do have gradients (that is how they are trained), Newton's step is defined in many variables, and the Hessian may be singular or not depending on the model, so "always singular" is not the reason.
A Hessian has eigenvalues and . Which change makes the step solve a system whose matrix has only positive eigenvalues?
The eigenvalues of are the old ones plus , so and are both positive when . Inverting explicitly gives the same matrix problem with less accuracy. Flipping the gradient's sign would send the step toward a maximum along the good directions. More digits of precision do not change a sign.
Exercises
- Newton’s method on from : where does it land?
Show answer
and , so the step is and the landing point is , which is where (). One step, because is a quadratic. - Run one more Newton step on from .
Show answer
and , so the step is and . The minimum is , so the error went from to . - For (a local minimum at , a local maximum at ) take one Newton step from and one from . Where does each go?
Show answer
and . From : , , step , to , toward the minimum at . From : , , step , to , toward the maximum at . The same formula goes to a minimum on one side and a maximum on the other, depending on the sign of . - A model has parameters. How much memory does its Hessian need in 32-bit numbers?
Show answer
entries, times bytes, is bytes, about gigabytes, for one matrix. - . What is the Newton step from , and where does it land?
Show answer
and , so and the landing point is , the minimum, in one step. - On at the slope is and the curvature is . What are the plain Newton step and the step with added to the curvature?
Show answer
Plain: . With : . The added keeps the step from exploding when the curvature is tiny.
Next: P1.F7 adds constraints: how to optimize when the answer must stay on a curve or inside a region. P4.13 returns to the optimizers used in practice, which are first-order, with full training runs.