P1.C5 found that halving a step cut the error of the tangent-plane estimate from to , a factor of about four. Why four? And can the error be predicted instead of only measured? It can. A tangent plane is flat, so what it misses is how the ground bends, and bending is measured by second derivatives. This lesson collects them, first for one input and then for many.
Curvature in one variable
The derivative is the slope of . It is itself a function, so it has a slope too. The second derivative is the derivative of the derivative: how fast the slope changes.
For the slope is , and the slope of the slope is . Check it with numbers: at the slope is , and at it is . The slope grew by over a step of , which is .
| function | what the graph does | ||
|---|---|---|---|
| bends upward everywhere | |||
| bends downward everywhere | |||
| bends downward for , upward for | |||
| bends upward, but very flat near |
The sign of tells which way the graph bends. Where the slope is increasing and the graph bends upward, like a bowl: it is concave up. Where the slope is decreasing and the graph bends downward, like a hill: concave down. The size of tells how sharp the bend is. A point where the bend changes sign, such as for , is an inflection point.
The second-derivative test
At a flat point () the sign of says what kind of point it is, when is continuous near :
- : the graph bends upward around the flat spot, so is a local minimum.
- : a local maximum.
- : no conclusion.
The last case is real. The three functions , and all have and , yet is a minimum, a maximum and neither, respectively. When , look at the next derivatives: for functions with enough derivatives, the first one that is not zero decides. If it is of even order, the point is a minimum when that derivative is positive and a maximum when it is negative. If it is of odd order, the point is neither.
Taylor polynomials: matching a function with powers
Close to a point a smooth function can be copied by a polynomial, one term at a time. Write for the distance from the centre .
- Degree 0, the constant. . It matches the height at .
- Degree 1, the tangent line (P1.C1, P1.C5). . It also matches the slope.
- Degree 2, add the bend. .
Why the ? Over a step of size the slope changes from to about . The average slope over the step is the middle value, , and the height gained is the average slope times . That gives .
The pattern continues. The Taylor polynomial of degree at the centre is
The symbol means the -th derivative, and is a factorial. The factorials are there because differentiating a total of times gives : to make the -th derivative of the polynomial equal , the coefficient must be . So is the polynomial of degree that matches and its first derivatives at the centre.
One example done by hand:
Every derivative of is , and , so at the centre every coefficient is :
At the true value is . The polynomials of degree give . Each new term is smaller than the one before, and the polynomials close in on the true value.
The widget: add one term at a time
Pick a function, a centre and a point , then press “+ term”. The blue curve is and the pink curve is the polynomial. The red bar at is the error.
Things to try:
- With at centre and , add terms from degree to . The polynomial hugs the curve near the centre first and spreads outward as terms are added. At degree the error at is .
- Choose at centre . The degree- polynomial is the same as the degree- one, because only odd powers appear (the status says so). Move to : far from the centre the polynomials swing noticeably (degrees 1, 3, 5 give against the true ), and it takes many terms to settle.
- Choose at centre . With the error shrinks as terms are added. Move to and the status turns red: the polynomials get worse as the degree rises.
- Keep and , but move the centre to . Now is from the centre, inside the new radius, and the polynomials work.
- Choose the sigmoid at centre . At it works; at it fails, although the curve itself is smooth.
How fast the error shrinks
For a smooth function the error of the degree- polynomial is about a constant times , provided the next derivative is not . The next term that was left out, of size , is what dominates. So halving the step divides the error by about . When that derivative is the error falls faster: for at centre the tangent line () has , so its error is about and falls eight-fold, not four-fold, when the step halves. The sigmoid’s tangent line at does the same. For at centre , the table gives the error (in thousandths) of the degree- polynomial for the steps , and the ratio of the last two errors, where halves. The degree is the tangent line, the quadratic and the cubic.
| ratio | ||||
|---|---|---|---|---|
| 1 | ||||
| 2 | ||||
| 3 |
The ratios settle toward , and as the steps get smaller. This explains P1.C5: a tangent plane is a degree-1 model, so halving the step divides its error by about four. For a degree-2 model the error falls about eight-fold, which is a good reason to include the bend.
Where Taylor polynomials stop working
More terms do not always mean a better fit. Try at the centre . Its polynomial is . The sums of degrees to at two points are:
- At the true value is and the polynomials give 0.5, 0.375, 0.4167, 0.401, 0.4073, 0.4047, 0.4058, 0.4053.
- At the true value is and the polynomials give 1.5, 0.375, 1.5, 0.2344, 1.7531, −0.1453, 2.2955, −0.9081.
At the numbers settle on the true value. At they swing farther and farther away. The same happens for (the geometric sum): at the sums approach , and at they grow without bound while the true value is .
The dividing line is a distance, the radius of convergence . Inside it () the error goes to as the degree grows. Outside it () the error grows without bound. The radius is the distance from the centre to the nearest trouble spot of the function:
- is undefined at , so from the centre the radius is . For the trouble spot is , and the radius is as well.
- and have no trouble spots, and their polynomials work at any distance. Far from the centre they only need more terms.
- The sigmoid is smooth at every real , yet its series at has radius . The trouble spots are not on the real line: they are at , where (complex numbers are beyond this lesson), and they still limit the series.
- A new centre moves the radius. For at the centre it is , so at it is , and is now inside.
At the edge itself () the answer depends on the function. For at the right-hand edge the sums still converge, very slowly. For they do not settle.
The lesson for machine learning is that a Taylor polynomial is a local tool. It is a good copy of the function near the centre and says little far away. Gradient descent relies on exactly that: it trusts a local model for one small step and then rebuilds it (P1.F3).
Two ML functions near zero
The Taylor polynomials of the sigmoid and its relative, the softplus (a smooth version of the ReLU of P4.4), are short:
The sigmoid has no term because : its slope is , which is largest, , at . At the true . The line gives , off by , and the cubic gives , off by . For softplus the true value at is and the quadratic gives . A neuron whose input is small is therefore almost linear.
Several inputs: the Hessian
With two inputs, differentiate the partial derivatives again. The second partial derivatives of are
The mixed ones differentiate in two different directions, one after the other. For (P1.C4) we have and , so
The two mixed partials agree, as P1.C4 promised. This holds whenever the second partials are continuous near the point (Schwarz’s theorem, often called Clairaut’s), which covers the smooth functions of this course. The Hessian matrix collects all second partials:
It is also written . Because the mixed partials agree it is a symmetric matrix, so P1.B12 applies: it has real eigenvalues and perpendicular eigenvectors. For it is . In one phrase, the Hessian is the Jacobian (P1.C7) of the gradient: the matrix of slopes of the gradient’s entries.
Two Hessians matter for the rest of the course.
The P0.2 loss. It expands to
with and (P1.C4). Differentiating once more gives
The loss is a quadratic polynomial, so its second derivatives are constants: this Hessian is the same at every point.
The stretched bowl of P1.F3. Here , and , so . This is the matrix that P1.B12 used to explain the factors and of P1.F3.
For inputs the Hessian is an matrix, with entries (about half of them distinct, by symmetry). Keep that number in mind: it is the reason the Hessian is a luxury for large models.
The quadratic model
Add the bend to the tangent plane of P1.C5. The second-order (quadratic) approximation of near , for a step , is
With one input this is , and the Hessian takes the place of . The last term is a single number: multiply into , then take the dot product with .
Check on the P0.2 loss at . There and . Take the step of P1.C5. The first-order change is , while the true change is . The curvature term is
which is exactly P1.C5’s error (). Halve the step to and the term becomes (a quarter, since it contains twice), matching P1.C5’s . For the bigger steps of P1.C5 the same term repairs the estimate:
| step | first order | curvature term | sum = true change |
|---|---|---|---|
The quadratic model is not just close here: it is exact, because the loss is itself a quadratic polynomial, so there are no higher-order terms. Even the big step , where the tangent plane predicted a fall of while the loss actually rose, is predicted perfectly. For a function that is not quadratic the model is only a good local copy.
Check on a function that is not quadratic. Take at . Then and . For the true change is . The first-order estimate is , and adding gives . For the true change is , the first-order estimate and the quadratic estimate . Halving the step cuts the first-order error from to (about four-fold) and the quadratic error from to (eight-fold), as the table of the previous section predicts.
Curvature along a direction
Walk through the point in a direction of length one. The height along the way is the one-variable function of P1.C6. Its slope at is . Its second derivative, the curvature along , is
This comes from putting in the quadratic model: the coefficient is , and is twice that. P1.C6 found that the slice of the loss at along is , so . Now we see where it comes from:
Along the axes the curvature is just a diagonal entry: along and along . The mixed entry matters for the directions in between.
Principal curvatures: the eigenvalues
How does the curvature change as the direction turns? Because is symmetric, P1.B12 gives two perpendicular unit eigenvectors with eigenvalues . Along an eigenvector the curvature equals its eigenvalue, since . In between it is a blend: if makes the angle with , then
so it never leaves the range from to . For this reason the eigenvalues are called the principal curvatures: the largest and the smallest bend, along two perpendicular directions.
For the P0.2 loss the eigenvalues are and (trace , determinant ). The sharp direction is and the nearly flat one is . The direction is from , and , as before. The loss bends sharply when you move -wise and is nearly straight along : that is a long, narrow valley.
The widget: the Hessian under your finger
Things to try:
- Start on the loss (preset “loss”) and press “u = (0.6, 0.8)”: the curvature reads anywhere on the map, because the Hessian is constant. Then press “along λ₁” and “along λ₂” to read the eigenvalues.
- Switch on the quadratic model on the loss: the dashed lines sit on top of the true ones, since the model is exact. On the “curved valley” they match only near the point.
- On the round bowl, the eigenvalues are equal and no axes are drawn: the ground bends the same way in every direction.
- On the stretched bowl, the ratio is . Drag the point: the Hessian does not change.
- On the saddle press “Go to the flat spot”: the eigenvalues are and , and the status names a saddle.
Bowl, hill or saddle: classifying a flat point
Suppose at (a flat point, P1.C5). Then the quadratic model loses its linear term:
where are the components of along the two eigenvectors. The sign of each eigenvalue says whether rises or falls along that axis. This is the preview of P1.B12 made precise. At a point where the gradient is zero and no eigenvalue is :
| eigenvalues of | the ground | the flat point is |
|---|---|---|
| all positive | curves up along every axis | a bowl, a local minimum |
| all negative | curves down along every axis | a hill, a local maximum |
| some positive, some negative | up along some axes, down along others | a saddle |
| one or more equal to | flat to second order along some axis | undecided between the remaining possibilities (see below) |
Examples: has eigenvalues (bowl); has (hill); has (saddle). The P0.2 loss has and at its flat point , both positive, so it is a bowl, which agrees with the minimum of that P1.C4 found. For at the origin : one eigenvalue is and the Hessian cannot decide. The point is in fact a minimum (both and are non-negative), whereas has the same Hessian at the origin and no minimum there. Only terms beyond the second order can decide. A zero eigenvalue still rules some things out: with a negative eigenvalue next to it the point cannot be a minimum (as in ), and with a positive one it cannot be a maximum.
Two warnings.
- Away from a flat point the Hessian does not name a minimum. The Hessian exists everywhere, and its eigenvalues still say how the ground bends, but a point with is not a minimum, maximum or saddle. The valley has its bottom at , where with eigenvalues and . At the Hessian is , so the ground there is saddle-shaped, but the gradient is and the point is not a saddle. Drag the point on that preset to see the eigenvalues change sign.
- Local only. A bowl-shaped flat point is a local minimum. Whether it is the lowest point everywhere is a different question (P1.F2).
Curvature, conditioning and the learning rate
Now put curvature and gradient descent together. On a quadratic loss with Hessian , the gradient at the point is (measuring from the minimum), so one step is , as in the box of P1.B12. Along the eigenvector with eigenvalue the error is multiplied by at every step. On a bowl-shaped quadratic (all eigenvalues positive) it shrinks when , which means . (On a saddle or a hill the error grows along a direction with a negative eigenvalue for every , so descent moves away from the flat point there.) For all directions at once:
For this is , the cap that P1.F3 found by experiment: at the factors are and . For the P0.2 loss it is . A quick run (the second code cell) confirms it: starting from , after steps the loss is (the minimum) for and about for .
The sharpest direction sets the speed limit. The flattest direction then sets the speed: along it the factor is , close to when is small. For the P0.2 loss at the factor along is , so each step removes only a few percent of the error there, while along it is and the error flips sign and dies fast. That is the zig-zag of P1.F3. The size of the problem is the condition number
for and for the P0.2 loss. A large means a long, narrow valley: fast bounce across, slow crawl along. Rescaling the inputs (P3.A11), momentum (P1.F5) and Newton’s step (next) all attack it.
For a loss that is not quadratic the Hessian changes with the point, so computed at the current point is a local guide, not a guarantee for the whole path.
A preview of Newton’s step
If the quadratic model is a good copy of the loss, why not jump to the bottom of the model? Setting the gradient of the model to zero, , gives
This is Newton’s step. In practice one solves (P1.B9) and does not form the inverse. On the P0.2 loss from :
One step lands at , the minimum with . That is no accident: the model of a quadratic is the function itself. On a function that is not quadratic the step is repeated. Newton’s method has its own lesson, P1.F6, with its trouble spots: if has a negative eigenvalue the step can go toward a saddle or uphill, and may have no inverse.
The cost. A model with weights has an Hessian. For that is entries, about terabytes in 32-bit numbers, and for a billion weights entries. Solving with it costs far more. This is why deep learning does not form Hessians. Instead it uses Hessian-vector products: the product for one direction is the change of the gradient along , so two gradient evaluations give , and automatic differentiation (P1.C10) can differentiate the gradient to get it exactly. The second Try-it code cell below does it on the P0.2 loss. With such products the largest curvature can be estimated by repeating the power-iteration idea of P1.B12.
Go deeper Where the error comes from: the remainder
Taylor’s theorem says more than “the error is small”. If exists between and , then there is a point between them with
Here . This is the Lagrange form of the remainder. It shows both claims of this lesson. The error is of size , times a number that depends on the size of the -th derivative, so halving divides it by about when that derivative is not near . And it can be bounded: for at centre and , every derivative between and is at most , so the degree- error is at most . The actual error is .
The remainder does not tell the whole story about series, because a bound on can itself grow with (this is what happens beyond the radius of convergence). A function can even be smooth and have a Taylor series that converges but equals the wrong function: (with value at ) has all derivatives at the origin, so its series there is .
Go deeper When the order of differentiation matters
The equality needs a condition. Take with . Along the axes and , so differentiating once more gives but . The second partials of this function exist at the origin but are not continuous there, so Schwarz’s theorem does not apply. For the smooth losses of machine learning this does not happen, and a ReLU (P4.4) has no derivative at its corner and second derivative everywhere else, so the curvature of a ReLU network comes from how its layers combine, not from bends of the ReLU itself.
Go deeper The two-by-two shortcut with the determinant
For two inputs the eigenvalue rule can be tested without computing eigenvalues. The product of the eigenvalues is . At a flat point:
- : the eigenvalues have the same sign, so it is an extremum. It is a minimum if and a maximum if .
- : opposite signs, a saddle.
- : an eigenvalue is , and the Hessian alone cannot decide between the remaining possibilities.
For at the origin, has : a saddle, with eigenvalues and . With three or more inputs one needs the signs of all the eigenvalues; the determinant alone is not enough.
Go deeper Why the loss Hessian is two over N times X transposed X
For a linear model with squared error, the P0.2 loss is , where the rows of are and . Its gradient is and its Hessian is the constant matrix
For any vector , , so no eigenvalue is negative: the matrix is positive semi-definite (P1.B10), and the loss can be a bowl or a trough, but not a saddle. The shape of the bowl depends only on , and it tends to be long and narrow when the columns of are strongly correlated or on very different scales (P3.A11). A related preview for P1.C11: the Hessian of is , which is when is symmetric.
Go deeper More inputs, and the next order
With inputs the quadratic model is the same formula, with an matrix, and the classification uses all eigenvalues: a mixture of signs is a saddle. Third derivatives form a table with entries, which is why nobody writes the cubic Taylor model of a neural network.
The Hessian in three depths
Intuition
The slope tells how steeply the ground tilts, and the second derivative tells how fast that tilt changes: the bend. In one variable it is a single number. With several inputs the ground can bend one way along one direction and another way along another, so the bend is a matrix, and its eigenvalues are the bends along two perpendicular directions.
A Taylor polynomial copies the ground at a spot: first the height, then the tilt, then the bend. The more terms, the better the copy near the spot, and the copy is useful only within some distance from it.
Math
Along a unit vector : has and . At the signs of the eigenvalues classify the point. Gradient descent on a quadratic has , convergent iff , with rate governed by . Newton: , found by solving .
Code
import numpy as np
def hessian(grad, p, h=1e-4):
"""Hessian by differencing the gradient: column j is the change of the gradient along input j."""
p = np.asarray(p, dtype=float)
cols = [(grad(p + h * e) - grad(p - h * e)) / (2 * h) for e in np.eye(p.size)]
return np.column_stack(cols)
vals, vecs = np.linalg.eigh(H) # eigenvalues in increasing order; classify with their signs
step = np.linalg.solve(H, -g) # Newton's step: solve, do not invertPyTorch returns the Hessian, and Hessian-vector products, with automatic differentiation (this runs in Colab or on your machine, not in the browser here):
import torch
from torch.autograd.functional import hessian, hvp
X = torch.tensor([[1., 1.], [2., 1.], [3., 1.]])
y = torch.tensor([2., 3., 7.])
loss = lambda p: ((X @ p - y) ** 2).mean()
p = torch.tensor([1.0, 0.0])
print(hessian(loss, p)) # [[9.3333, 4.], [4., 2.]]
print(hvp(loss, p, torch.tensor([0.6, 0.8]))[1]) # [8.8, 4.0], without forming the matrixTry it: Taylor polynomials in code
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: use the centre for . The coefficients are and then for . Check that at the polynomials of degree to settle near .
Try it: the Hessian, curvature and Newton on the P0.2 loss
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Challenge: change the data to and rerun. The Hessian does not change (it depends on , not on ). Where does Newton’s step land now?
Common mistakes
Check your understanding
Let . What is , and what does the second-derivative test conclude at the flat point ?
Here and , which is at . A zero second derivative gives no verdict. The point happens to be a minimum, but that comes from looking at higher derivatives (the lowest-order derivative that is not zero is the fourth, and it is positive), and the same also occurs for the maximum of and for the neither-case . The value would need , which is not a flat point.
A smooth function has a non-zero third derivative at the centre. The error of its degree-2 Taylor polynomial is measured for a step and again for a step . About how does the error change?
The leading term that was left out is of order , so the error is about a constant times . Halving multiplies it by . A four-fold fall is what the degree-1 polynomial (tangent line) shows, since its error grows like , and sixteen-fold belongs to the degree-3 polynomial.
What is the Hessian of ?
The partial derivatives of are and . Differentiating again gives , and . The matrix with doubles the mixed entry. The diagonal matrix forgets the mixed partials. The matrix with in it mixes up first derivatives with second derivatives: the entries of a Hessian are second derivatives, and for this function they do not depend on and .
At a point where the gradient is zero, the Hessian has eigenvalues and . What kind of point is it?
Eigenvalues of opposite signs mean rises along one axis and falls along the other, which is a saddle. A minimum needs every eigenvalue positive and a maximum needs every eigenvalue negative. The test is undecided only when an eigenvalue is exactly , not when the sizes differ.
Gradient descent runs on a quadratic loss whose Hessian is . Below which learning rate does it converge, and above which does it diverge?
Along each eigen-direction the error is multiplied by , and this has size below only when . The largest eigenvalue, , gives the strictest limit, . The limit would belong to a curvature of , the smaller eigenvalue, which is not the one that limits the step. The value converges but is far below the limit, and would be the limit for a curvature of .
Exercises
- For , find the flat points and classify them with the second-derivative test. Where is the inflection point?
Show answer
at . , so (a local minimum, ) and (a local maximum, ). The inflection point is at , where changes sign. - Find the degree-3 Taylor polynomial of at the centre , evaluate it at and give its error.
Show answer
, so . The true value is , so the error is about . - The degree- polynomials of at centre for are for , and the true value is . Why do they not settle?
Show answer
The point is from the centre, and the radius of convergence is (the distance to the trouble spot ). Outside the radius, more terms make the polynomial worse: the sums swing wider, reaching at degree and at degree . - Find the gradient and the Hessian of at .
Show answer
. , , , so . - Use the quadratic model with the answer to exercise 4 to estimate .
Show answer
: first order . Curvature term . The estimate is and the true change is . - For the P0.2 loss, with , find the curvature along and along .
Show answer
Along it is . Along it is . Both lie between and . - Classify the flat point at the origin of .
Show answer
at the origin. has eigenvalues and (trace , determinant ). Mixed signs: a saddle. For example, while . - What is the largest learning rate for which gradient descent converges on a quadratic with Hessian , and on the P0.2 loss?
Show answer
: , and . - Take one Newton step on from .
Show answer
, , so , which lands at , the minimum, in one step. - A model has weights. How many entries does its Hessian have, and how much memory is that in 32-bit numbers?
Show answer
entries, at bytes each bytes, about terabytes (about half of that if only one triangle of the symmetric matrix is stored).
Next: P1.C9 turns from slopes to areas (integrals), and P1.C10 shows how a computer gets exact derivatives automatically. P1.C11 gives the matrix-calculus rules for gradients and Hessians of the expressions of machine learning. Later, P1.F2 uses the classification of flat points for minima and saddles, P1.F3 and P1.F5 use the curvature picture for learning rates and momentum, and P1.F6 turns Newton’s step into a method.