This is a toolkit chapter, and optional. It covers the one idea from calculus that machine learning leans on: measuring how sensitive an output is to its inputs. Training a model means asking that question about the loss and every weight, millions of times.
How fast is it changing?
For a straight line the question has an easy answer. The line goes up 3 for every 1 it goes across. Its slope is 3, everywhere.
A slope is a rate. If is hours of study and is an exam score, a slope of 3 means three points per hour. Positive slopes go uphill from left to right, negative ones downhill, and a slope of zero is flat.
Curves are harder, because a curve is steeper in some places than others. It has no single slope. It has a slope at each point.
Slope by nudging
To find the slope of a curve at one point, do what you would do with a real hill: take a small step and see how much higher you are.
Pick a point . Nudge it by a small amount . Measure how much the output changed, and divide by the nudge:
slope ≈ change in output ÷ size of the nudge
Shrinking the nudge
- The curve
- Line through the two points
- Run across, rise up
- Nudge (run)
- 2.00
- Change in output (rise)
- 7.972
- Rise ÷ run
- 3.995
- Settles toward
- 2.00
With a big nudge the line cuts across the curve and its slope is only a rough answer. As the nudge shrinks, the line stops changing: it settles onto the line that just touches the curve. The slope it settles on is the
At on the curve , the numbers go like this:
| Nudge | 2 | 1 | 0.1 | 0.01 |
|---|---|---|---|---|
| Rise ÷ run | 4 | 3 | 2.1 | 2.01 |
They are closing in on 2. Try other points and a pattern appears: the slope at always settles on .
Rules instead of nudging
Nudging works for any function, and computers do sometimes find derivatives this way. But for common functions the answer follows a pattern, so it can be written down once and reused.
| Function | Its derivative | In words |
|---|---|---|
| (a constant) | A constant never changes. | |
| A straight line has the same slope everywhere. | ||
| Steeper the further you are from zero. | ||
| Bring the power down, reduce it by one. | ||
| Do each part separately and add. |
The derivative of is written , or . Both mean the same thing: the slope of at .
Take . Handle each part in turn:
- becomes
- becomes
- becomes
So . At the curve is rising at a rate of 17.
One fact makes derivatives useful for finding the best model. At the very bottom of a valley, or the top of a hill, the ground is flat: the derivative is zero. That is how the formula for the best line was found in
A loss curve has derivative −4 at the current value of a weight. What does that tell you?
Several inputs at once
A real loss depends on many weights, not one. With two inputs, picture the function as a landscape: every position has a height.
Standing on a hillside there are now two questions. How steep is it if I step east? And how steep if I step north? Each is answered by nudging one input while holding the other still. The result is a
For the bowl :
To get the first, treat as a constant and use the rules above. To get the second, treat as a constant.
Put the partial derivatives side by side in a vector and you have the
Which way is up?
- Gradient: steepest way up
- Minus the gradient: steepest way down
- Rings of equal height
- Height here
- 10.1
- Slope in the x direction
- 4.8
- Slope in the y direction
- 7.2
- Gradient
- [4.8, 7.2]
This is the whole basis of gradient descent. Compute the gradient of the loss, step the opposite way, repeat. A model with a million weights has a gradient with a million entries, and the recipe is unchanged.
The chain rule
Models are built by feeding one calculation into the next. A weighted sum goes into a sigmoid; the sigmoid goes into a loss. To train the model we need to know how the final output responds to something at the very start.
Consider two steps. First triple the input: . Then square the result: .
- Nudge , and changes 3 times as much.
- Nudge , and changes times as much.
So a nudge to is magnified by 3 and then by . The overall rate is the two multiplied together. This is the
overall rate = rate of the second step × rate of the first step
Rates multiply along the chain
- Rate of step 1
- 3.0
- Rate of step 2
- 6.0
- Overall: multiply them
- 3 × 6.0 = 18.0
- Nudge x by 0.01
- u moves by 0.030
- and y moves by
- 0.181
- y nudge ÷ x nudge
- 18.09
With three steps there are three rates to multiply, and with a hundred steps a hundred. Backpropagation, the algorithm that trains neural networks, is this rule applied carefully from the end of a long chain back to its beginning.
A change to a weight makes a neuron's output change 0.5 times as much. That output's change makes the loss change 4 times as much. How does the loss respond to the weight?
In code
The nudging definition is three lines of Python, and it is a handy way to check a derivative you have worked out by hand.
def slope(f, x, h=1e-5):
return (f(x + h) - f(x - h)) / (2 * h) # nudge both ways for accuracy
f = lambda x: 3 * x**2 + 5 * x + 7
print(slope(f, 2)) # 17.0, matching 6x + 5 at x = 2
def gradient(f, point, h=1e-5):
grad = []
for i in range(len(point)): # nudge one input at a time
up, down = list(point), list(point)
up[i] += h
down[i] -= h
grad.append((f(up) - f(down)) / (2 * h))
return grad
bowl = lambda p: p[0]**2 + 3 * p[1]**2
print(gradient(bowl, [2, 1])) # [4.0, 6.0]
Libraries such as PyTorch do not nudge. They apply the rules and the chain rule automatically, which is exact and far faster.
Key Takeaways
- A derivative is the slope of a function at a point: how much the output changes per unit change in the input.
- It can be found by nudging the input and dividing, or by a few simple rules.
- At a lowest or highest point the derivative is zero.
- With several inputs there is one partial derivative each. Together they form the gradient, which points uphill.
- The chain rule: when calculations are chained, their rates multiply.
- Estimate a slope by nudging the input and dividing.
- Find the derivative of a simple formula with the rules, and use it to find a lowest point.
- Work out a gradient and say which direction it points.
- Apply the chain rule to a calculation done in two steps.
Exercises
Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.
For , estimate the slope at with a nudge of 0.1, then with a nudge of 0.01. What value are the estimates heading towards, and what does the rule give?
Hint
Work out and divide by the nudge.
Solution
With a nudge of 0.1: .
With a nudge of 0.01: .
The estimates are closing in on 6. The rule says the derivative of is , which is exactly 6 at .
Where is the lowest point of , and how low is it?
Hint
At a lowest point the derivative is zero. The derivative of is .
Solution
At a lowest point the derivative is zero. The derivative is , which is zero at . There, .
So the lowest point is at , where the function equals 1. To the left of 3 the derivative is negative (the curve is falling) and to the right it is positive (rising), which confirms it is a lowest point and not a highest one.
Let . Find the gradient at , . If you wanted to make smaller, in which direction would you move?
Hint
Find each partial derivative by treating the other input as a fixed number. The gradient points uphill.
Solution
Treat the other input as a fixed number each time. The partial derivative with respect to is , and with respect to it is . At the point (2, 1) the gradient is .
The gradient points uphill, so to make smaller move the opposite way, along : decrease both and , and by more, because the surface is steeper in that direction.
Let . Use the chain rule to find how fast changes with at . Check your answer by nudging to 1.001.
Hint
Name the inside . Find how fast changes with , how fast changes with , and multiply.
Solution
Split the calculation into two steps: , then . The rates are 3 for the first step and for the second. At , , so the second rate is 8. Rates multiply along the chain: .
Check: at , and . The change in is 0.024009 for a nudge of 0.001, a rate of about 24.01.
In the figure “Which way is up?”, drag the point slowly along one of the rings. What stays true about the arrow the whole way round? Then drag it to the centre. Why does the arrow vanish there?
Hint
A ring joins places of equal height. Think about which way you would have to walk to gain height fastest.
Solution
All the way round, the arrow crosses the ring at right angles. Along a ring the height does not change, so the direction of fastest climb can have no part lying along the ring. It must point straight across it.
At the centre the surface is at its lowest point. Every direction is uphill by the same negligible amount for a tiny step, so there is no direction of climb to point in, and the gradient is zero. This is how gradient descent knows it has arrived.
References and further reading
- M. P. Deisenroth, A. A. Faisal and C. S. Ong, Mathematics for Machine Learning, chapter 5. Free at mml-book.github.io.
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 7 and 8, nnfs.io.
- G. Sanderson, Essence of calculus, 3Blue1Brown.