A car’s speedometer says 52 km/h. But speed is distance divided by time, and at one single instant no time has passed and no distance has been covered. So what does “52 right now” mean?
The answer is the idea of this lesson, and it is also the central question of machine learning: if I nudge this one number a tiny bit, how much does the result change? A model has weights, and the loss measures how wrong it is. If raising a weight by 0.01 makes the loss fall by 0.1, we should raise the weight. The exact change per unit of nudge is the derivative.
Average rate of change
Start with something you can compute. A toy car starts at rest and speeds up. Its distance from the start after seconds is metres. At it has gone 1 m; at it has gone 9 m. Over those two seconds it covered 8 m, so its average speed was
(, the Greek capital delta, means “the change in”.) For any function , the average rate of change between two inputs is the change in output divided by the change in input:
Its unit is “output units per input unit”: metres per second here, or “loss per unit of weight” for a model.
An average hides detail. The car was slower than 4 m/s early on and faster later. Shorter stretches tell more:
| from to | distance gained | average speed |
|---|---|---|
| 1 to 3 | ||
| 1 to 2 | ||
| 1 to 1.5 | ||
| 1 to 1.1 |
As the stretch shrinks, the average speed settles towards 2 m/s. That number is the speed at . Making this precise is the whole lesson.
The same idea for a loss
Take the three-example model from P0.2: the prediction is (with ), the data are , and the loss is the mean squared error . At the loss is . P0.2 raised to and found a loss of about . The average rate of change of the loss between those two weights is
The negative sign says that raising lowers the loss. P0.2 promised that a smaller nudge gives the exact value, . Section “A derivative of a loss” below keeps that promise.
The secant line
Draw the graph of and pick two points on it: and . The straight line through them is a secant line. Its slope is the average rate of change over the stretch from to , and it has a name, the difference quotient:
Here is the step: how far the second point is from the first. It can be negative too (the second point is then on the left of ); the formula does not change.
Let and . The two points are and :
| step | second point | secant slope |
|---|---|---|
| 1 | ||
| 0.5 | ||
| 0.1 | ||
| 0.01 | ||
| 0.001 | ||
The slope is every time. Bring the second point closer, from either side, and the secant slope closes in on 2.
From secant to tangent: the limit
Why does the table say every time? Expand , so
We want the slope “at” the point, with the two points on top of each other. But gives , which has no value: one point has no slope, because rise and run are both 0. The way out is a limit. We simplify first (this is allowed because ), and then ask what the simplified expression approaches as gets closer and closer to 0. Here it approaches 2. We write
A limit asks “what number do the values head towards?”, not “what is the value at ?”. The value at is not even needed.
The derivative of at is the limit of the secant slopes:
Read as “f prime of a”. If the limit exists (it has to be the same whether shrinks from the right or from the left), we say is differentiable at . The line through with slope is the tangent line:
So for at : , and the toy car’s speed at is exactly 2 m/s. The speedometer answer to the opening puzzle is a limit of average speeds over shorter and shorter stretches.
Go deeper What the word limit means exactly
“The values head towards ” can be made exact. We write when we can make as close to as we like by taking small enough, and . In symbols: for every tolerance there is a distance such that whenever (both signs of count).
For and : , so the choice works. To get within of 2, take . The condition is where “never put ” lives in the definition.
For a general the values do not always settle on a single number. At a corner they head to two different numbers, one from each side, and then the limit does not exist. That case is in the section “Where there is no derivative”.
Things to try with the zoom widget:
- Keep at and move from 1 down to . The secant slope goes and the line swings onto the orange tangent. The last readout, “secant slope derivative”, is about here (for the tiniest , round-off in the subtraction changes the last digits).
- Put back to 1 and slide Zoom up. The parabola bends away from the tangent a lot at ×1, but at about ×1000 (×10 000 on a wide screen) the largest gap between them is under a pixel on a phone-sized widget. This is the next section.
- Choose and look at the derivative at : it is , the same as the height . Choose the sigmoid at : the derivative is . Slide to 6, where the sigmoid is nearly flat: the derivative is about (the slider for reaches for the sigmoid and for the others).
- Choose , where starts at 0. Zoom in as far as you like: the corner stays. The right-hand secant slope is and the left-hand one is . Now move to 0.05 and zoom in to ×1000 or more: the corner is out of view, and the curve looks straight again.
Zooming in: a curve is almost a straight line
Look at a small enough piece of a smooth curve and it looks straight, the way a small piece of the Earth looks flat. This is the picture to keep: near , the curve is well described by its tangent line. The widget lets you check it: the gap between curve and tangent, measured in pixels, shrinks as you zoom.
(Where the Earth analogy breaks: the Earth is not flat, and a curve never becomes exactly straight. It only gets closer and closer to its tangent, compared with the size of the view. The tangent line is the best straight-line description near , not an exact one.)
In symbols, near we can replace the curve by the line:
(Read it as: start at , and add “slope times the step”.) For and we have and , so the approximation is . The exact value is . Compare:
| step | approximation | exact | error |
|---|---|---|---|
| 0.5 | 2 | 2.25 | 0.25 |
| 0.1 | 1.2 | 1.21 | 0.01 |
| 0.01 | 1.02 | 1.0201 | 0.0001 |
| 0.001 | 1.002 | 1.002001 | 0.000001 |
For this function the error is exactly . Cut by 10 and the error falls by 100. The error divided by is in the four rows: it goes to 0, and that is what “looks straight when you zoom in” means: the error is tiny even compared with the small step. (For at , where , the error of is about : at and at .)
This approximation is what gradient descent relies on (P1.F3). From on the slope is 6. A step of () is predicted to land at . The true value is . The prediction is decent here, but its error, , grows quickly as steps grow. That is one reason the learning rate cannot be too big. The size of the correction comes from the curvature of , the second derivative (P1.C8).
Go deeper What differentiable means, in one line
A function is differentiable at exactly when the tangent-line approximation has an error with :
This is the zoom picture in symbols: the curve minus its tangent is small even compared with . It also shows that a function differentiable at has no jump there: as , . The reverse fails. has no jump at 0 and still no derivative there.
Notation: four ways to write one thing
All of these mean “the derivative”:
- (“f prime of x”): short, used when the function has a name. is the derivative at the particular point .
- , or when : the “derivative of with respect to ”. It comes from , with replaced by for “a tiny change”.
- : “apply the derivative with respect to to ”. For example, .
- : the value of at . It equals .
For now, read as one symbol, not as the fraction “dy divided by dx” that you can split up or cancel. The derivative is a limit of fractions, and and alone have not been given a meaning here. (Later, with the chain rule in P1.C3, will often behave like a ratio, which is part of why this notation is so convenient.) In machine learning you will write or for a loss with one parameter, and the curly for a loss with many (partial derivatives, P1.C4).
The derivative has units: output units per input unit. If is in metres and in seconds, is in metres per second. If is a loss and a weight, is “loss per unit of weight”.
The derivative is a function
For each input you get a slope : so the derivative is itself a function. Let us find it for three functions, straight from the definition.
A straight line, . Then , so the difference quotient is for every and every , and . A line has the same slope everywhere. A constant function () has derivative 0.
The square, . Now , so
So . At this is 2, as in the table. At it is 6 (the slope used in the gradient-descent example of P1.F3), at it is 0, and at it is .
The cube, . Expanding gives
So , and .
You might spot a pattern (, ). Do not memorise it from two cases: P1.C2 collects the shortcut rules (power, sum, product, quotient, exponential, logarithm), so that you rarely have to go back to the limit. The definition is what those rules are built from, and what the numerical checks below test.
Two derivatives you were promised
The exponential. P1.A2 said that grows at a rate equal to its own value. Here is where that comes from:
The factor does not depend on . Numerically it is at , at , at , and it approaches 1. So the derivative of is . (That this limit is exactly 1 is how P1.C2 defines ; it also sketches why this agrees with the compound-interest definition of P1.A2.) For another base the same factor is . For it approaches , which is the “ times its value” of P1.A2.
The sigmoid. P1.A5 measured the slope of with and told you to shrink it towards 0. Do it at :
| step | secant slope of at |
|---|---|
| 0.1 | 0.1011 |
| 0.01 | 0.1046 |
| 0.001 | 0.10495 |
| 0.0001 | 0.10499 |
It approaches , which is . This is the closed form that P1.A5 gave you to check: at it gives , the largest slope, and at it gives , the flat tail. The same shrinking works for tanh: at the secant slopes are (, the value in P1.A5), () and (), approaching , the closed form from P1.A5. P1.C2 derives both from its rules, and P1.C3 shows a shorter way with the chain rule.
What the derivative tells you
Sign. If , then is rising at (more input gives more output). If , it is falling. If , the graph is flat at for an instant.
Size. A large means a steep graph: the output reacts strongly to the input. A small one means it hardly reacts (the sigmoid’s flat tails, P1.A5).
Use it to predict. The tangent-line approximation turns a slope into a forecast: if , then raising from 2 to 2.01 changes by about .
A loss example. In P1.A1 a one-parameter model had the loss . Write it as . The algebra of , with replaced by , gives :
| what it says | |||
|---|---|---|---|
| 0 | 36 | falling steeply: raise | |
| 2 | 4 | still falling, less steeply: raise | |
| 3 | 0 | flat: the bottom of the bowl | |
| 4 | 4 | rising: lower |
This table is gradient descent in miniature (P1.F3): step against the sign of the slope, and take smaller steps where it is small.
Zero slope is not always a minimum. marks a flat spot. For at 0 it is a minimum, for at 0 a maximum, and for at 0 neither: the slope is 0 there, but the curve keeps rising on both sides. Telling these apart is the job of the second derivative (P1.C8) and of P1.F2.
A derivative of a loss
Back to the loss of the three-example model. Put . The predictions are , the errors are , and expanding the squares gives
At this is , which is the that P0.2 found. As it tends to , so : a nudge of in lowers the loss by about . The same steps for (with held at 1) give a slope of at . Finding both slopes at once is the job of partial derivatives and the gradient (P1.C4, P1.C5).
Estimating a derivative with numbers
Often you cannot differentiate by hand, or you want to check a formula you derived. Then you estimate the slope from function values, using a small but not-zero . These estimates are called finite differences. Three versions:
- Forward: (look ahead).
- Backward: (look behind).
- Central: (look both ways, and divide by the full width ).
Test them on at , where the true slope is 3. Algebra gives the errors exactly:
- forward: , an error of , about for small ;
- central: , an error of exactly .
| forward error | central error | |
|---|---|---|
| 0.1 | 0.31 | 0.01 |
| 0.01 | 0.030 | 0.0001 |
| 0.001 | 0.0030 | 0.000001 |
Shrink by 10 and the forward error shrinks by about 10, while the central error shrinks by 100. We say the forward difference has error of order , and the central difference of order . The central one is better because the bends on the two sides of cancel (the Go-deeper box below shows how). For the square the cancellation is perfect: the central difference of is exactly for every in exact arithmetic.
But a smaller is not always better
The table suggests we should take as tiny as possible. The computer disagrees. It stores numbers with about 16 significant digits (64-bit floating point). When is tiny, and agree in nearly all of those digits, and their difference keeps only a few digits that are mostly rounding noise. Dividing by a tiny then multiplies the noise. Here are real results for at , computed in Python with ordinary floats (the algebra above holds only for exact arithmetic):
| forward error | central error | |
|---|---|---|
The error falls, reaches a bottom, and then climbs again: a U shape on a log scale. At the number is rounded to exactly , so and the forward estimate of the slope is , an error of 3. For these digits are the same on any machine with standard 64-bit floats, because only , , and are involved; another function, or a library or , gives similar sizes, not necessarily the same digits.
The best depends on the method: for this function, about for the forward difference (error about ), and about to for the central difference (error about ). Rules of thumb from error analysis, for functions with values and derivatives of ordinary size: roughly the square root of the machine epsilon (, the gap between 1 and the next float) for the forward difference, which is about , and its cube root, about , for the central difference.
Go deeper Why the central difference is better, and where the best step size comes from
Near , a smooth function is a polynomial plus smaller corrections (Taylor’s idea, covered properly in P1.C8):
Subtract to get the forward estimate: it equals , so its error is about (order ). In the central estimate the terms in cancel, because they have the same sign on both sides: it equals , an error of order . For at we have and , giving and , as in the table.
Round-off adds a second error. Each stored value of is off by a relative amount of roughly , so the numerator is off by about and the estimate by about . Total error is therefore roughly (truncation, growing with ) plus (round-off, growing as shrinks). Setting the two equal gives near for the forward difference and near for the central one, up to constants that depend on . These are rules of thumb, not guarantees.
Things to try with the error explorer:
- With at , slide from 1 to 16. Watch the blue (forward) line fall with a slope of 1 on the log–log plot (a factor of 10 in gives a factor of 10 in error) and the pink (central) line fall twice as fast, until both are lifted by round-off. The status lines change from “truncation” to “round-off” as you cross the bottom.
- Find the best for each method: about 8 for forward, between 5 and 6 for central.
- Go to : is the same number as , so the forward estimate is . Then try , and the sigmoid at : the bottoms of the U move a little, but the shape stays. (The sigmoid is used at because at it is symmetric and its forward and central differences come out the same.)
Gradient checking
This is the main use of finite differences in machine learning. Suppose you derived a gradient by hand, or you wrote backprop code (P4.8). To test it, compare with a central difference of the loss: nudge one weight up and down by a small (often to in 64-bit floats), recompute the loss each time, and see whether the slope matches. If the two disagree by more than rounding noise (compare the relative difference), there is a bug. The test costs two loss evaluations per weight, far too slow for training, so it is used for debugging. Automatic differentiation (P1.C10) finds exact derivatives with rules instead of an to choose.
Where there is no derivative
The derivative needs the secant slopes to settle on one number, from the right and from the left. Three ways this can fail.
A corner. at 0. From the right, the secant slope is for every . From the left, with , it is . The two sides head to different numbers, so the limit does not exist, and neither does . Zooming does not help: the curve is a corner at every scale (try it in the zoom widget). At every other point, has a derivative: for , for .
ReLU is the same kind of corner: has slope from the left and from the right at . So it has no derivative at 0, and yet networks full of ReLU are trained with gradient descent. A library simply picks a value at that single point. For PyTorch (checked with version 2.9.1) the gradient of ReLU at exactly 0 is 0, and so is the gradient of at 0 (the sign of 0 is 0). Other libraries may choose differently. Finite-difference checks are no help at a corner: the central difference of at 0 is exactly , and that of ReLU is , neither of which is a derivative. So do not trust a gradient check at such a point.
A jump. The step function ( for , for ) at 0: from the right the secant slope is 0, but from the left it is , which grows without limit as shrinks. Away from 0, its derivative is 0 everywhere: a flat piece has no slope to follow. This is why a step activation gives gradient-based training nothing to follow, and why smooth curves like the sigmoid replaced it in networks trained this way (P1.A5, P4.4).
A vertical tangent. at 0: the secant slope is , which is at and at . It grows without limit. The tangent is a vertical line, and its “slope” is infinite, so there is no derivative.
In short: a function can be defined and even continuous at a point and still have no derivative there (corner, vertical tangent). It cannot have a derivative where it jumps.
The derivative in three depths
Intuition
The derivative is the speedometer reading: not an average over a trip, but the rate right now. You get it by measuring average rates over shorter and shorter stretches until they stop changing. Zoomed in, a smooth curve is a straight line, and the derivative is that line’s slope.
For a model, the derivative of the loss with respect to a weight is the answer to “if I nudge this weight up a tiny bit, how much does the loss change per unit of nudge?”. Negative means the loss falls, large means it reacts strongly.
Math
Tangent line: . Local linear approximation: , with an error for which .
From the definition: , , .
Finite differences: forward (error of order ) and central (error of order ), plus round-off of order with in 64-bit floats.
No derivative where the one-sided slopes differ (corner), grow without limit (jump, vertical tangent).
Code
def derivative(f, x, h=1e-5):
"""Central-difference estimate of f'(x)."""
return (f(x + h) - f(x - h)) / (2 * h)
derivative(lambda x: x * x, 3.0) # about 6PyTorch finds exact derivatives with automatic differentiation (P1.C10). This runs in Colab or on your machine, not in the browser here:
import torch
x = torch.tensor(1.0, requires_grad=True)
y = x ** 3
y.backward() # computes dy/dx
print(x.grad) # tensor(3.)Try it: shrinking steps and the U-shaped error
The first cell shrinks for and for the sigmoid. The second builds the U-shaped table above and shows the ReLU corner. Change the numbers and predict the output before you run it.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: change a to and predict the derivative of there before running.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: use (math.exp) at and find the with the smallest central error. The true slope is math.exp(1).
Common mistakes
Check your understanding
A toy car has distance metres after seconds. What is its average speed between and ?
It covers metres in seconds, so the average speed is m/s. The 8 is the distance gained, not a speed, and 2 m/s is the speed at the single instant .
Why do we not find by putting into ?
With the numerator is and the denominator is 0. The limit asks where the values head as shrinks, and the derivative is that limit exactly, not an approximation. is perfectly fine.
You know that . Using the tangent-line approximation, about how much does change when goes from 2 to 2.01?
The change is about . The negative slope means falls as rises, and the step is tiny, so the change is tiny too.
You estimate a derivative with a central difference in 64-bit floating point, for a function whose values and derivatives are of ordinary size (around 1). Which step is the best choice?
The error is the sum of a truncation error that shrinks with and a round-off error that grows as shrinks, so it is U-shaped. At the numbers and can even be identical, and divides by zero. is far too big for the curve to look straight.
At , ReLU has slope 0 from the left and slope 1 from the right. What does this tell you about its derivative at 0?
A derivative needs the secant slopes to approach one number from both sides. Here they approach two different numbers, so there is no derivative. Libraries pick a value by convention at that point, but that value is a choice, not a derivative.
Exercises
- For , find the average speed between and , and then the speed at from the definition.
Show answer
Average: m/s. The difference quotient at is , which tends to 4, so the speed at is 4 m/s. - For at , write the difference quotient, the derivative, and the tangent line. Use the tangent line to estimate .
Show answer
The quotient is , so and the tangent is . At it gives . The exact value is , so the error is . - Using the definition, find for .
Show answer
, so (this agrees with at ). - Using the definition, find the derivative of at .
Show answer
. So (the slope is negative: falls as grows). - For the loss with , find the slope at . Which way should move, and what happens to for a nudge of ?
Show answer
: the loss is falling, so raise . A nudge of changes by about . (Exactly: against , a change of .) - Show that the central difference of at with equals the true derivative exactly. Why?
Show answer
. In general , so the central difference is for every : the error terms cancel completely for a quadratic. - Where does have no derivative, and what are the one-sided slopes there?
Show answer
At (the corner). The slope from the left is and from the right is . - In the second code cell, predict the forward estimate of the slope of at with , and explain it.
Show answer
It is (an error of 3). The number rounds to exactly in 64-bit floating point, so . - A weight has (loss units per unit of weight) at the current value. About how much does the loss change if increases by ?
Show answer
About loss units: the loss falls by about . - The sigmoid has slope at . Estimate it with a central difference and in code, and compare with .
Show answer
, and .
Next: computing a derivative from the limit every time is slow. P1.C2 collects the rules for sums, products, quotients, powers, and , and P1.C3 shows how slopes multiply when functions are nested, which is the heart of backpropagation.