Toolkit 0.2 // Toolkit

Derivatives and Gradients.

If I change the input a little, how much does the output change?

Reading time
13 min

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 y=3x+1y = 3x + 1 goes up 3 for every 1 it goes across. Its slope is 3, everywhere.

slope=riserun=change in outputchange in input\text{slope} = \frac{\text{rise}}{\text{run}} = \frac{\text{change in output}}{\text{change in input}}

A slope is a rate. If xx is hours of study and yy 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 xx. Nudge it by a small amount hh. Measure how much the output changed, and divide by the nudge:

slope at x  ≈  f(x+h)−f(x)h\text{slope at } x \;\approx\; \frac{f(x + h) - f(x)}{h}

slope ≈ change in output ÷ size of the nudge

Figure

Shrinking the nudge

3, 8.97
  • 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
2.00
Drag the orange point along the curve.
The dark curve is y = x². The orange line passes through the chosen point and a second point a nudge further along. Try it: pull the nudge slider all the way down and watch rise ÷ run settle. Then drag the point to a different x and do it again.

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 of the function at that point.

At x=1x = 1 on the curve y=x2y = x^2, the numbers go like this:

Nudge hh210.10.01
Rise ÷ run432.12.01

They are closing in on 2. Try other points and a pattern appears: the slope at xx always settles on 2x2x.

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.

FunctionIts derivativeIn words
cc (a constant)00A constant never changes.
c xc\,xccA straight line has the same slope everywhere.
x2x^22x2xSteeper the further you are from zero.
xnx^nn xn−1n\,x^{n-1}Bring the power down, reduce it by one.
f+gf + gf′+g′f' + g'Do each part separately and add.

The derivative of ff is written f′(x)f'(x), or dfdx\dfrac{df}{dx}. Both mean the same thing: the slope of ff at xx.

ExampleUsing the rules

Take f(x)=3x2+5x+7f(x) = 3x^2 + 5x + 7. Handle each part in turn:

  • 3x23x^2 becomes 3×2x=6x3 \times 2x = 6x
  • 5x5x becomes 55
  • 77 becomes 00

So f′(x)=6x+5f'(x) = 6x + 5. At x=2x = 2 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 .

Checkpoint

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 (x,y)(x, y) 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 , written with a curly ∂\partial.

For the bowl f(x,y)=x2+3y2f(x, y) = x^2 + 3y^2:

∂f∂x=2x∂f∂y=6y\frac{\partial f}{\partial x} = 2x \qquad\qquad \frac{\partial f}{\partial y} = 6y

To get the first, treat yy as a constant and use the rules above. To get the second, treat xx as a constant.

Put the partial derivatives side by side in a vector and you have the . It has a remarkable property: it points in the direction of steepest ascent. Its opposite therefore points straight downhill.

Figure

Which way is up?

lowest
  • 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]
Drag the orange point around the bowl. The arrows are drawn shorter than the true gradient so they fit.
The bowl seen from above, like a hiking map. Each ring joins points of equal height. Try it: drag the point around. Notice that the arrows always cross the rings at right angles, and shrink to nothing at the centre.

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: u=3xu = 3x. Then square the result: y=u2y = u^2.

  • Nudge xx, and uu changes 3 times as much.
  • Nudge uu, and yy changes 2u2u times as much.

So a nudge to xx is magnified by 3 and then by 2u2u. The overall rate is the two multiplied together. This is the .

dydx=dydu×dudx\frac{dy}{dx} = \frac{dy}{du} \times \frac{du}{dx}

overall rate = rate of the second step × rate of the first step

Figure

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
1.0
Each dark box is a calculation, labelled with how much it magnifies a small change to its input. Try it: set x to 1 and read the overall rate. Then check it against the nudge in the second row of numbers.

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.

Checkpoint

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.
You can now
  • 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.

Exerciseby hand

For f(x)=x2f(x) = x^2, estimate the slope at x=3x = 3 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 f(3+nudge)−f(3)f(3 + \text{nudge}) - f(3) and divide by the nudge.

Solution

With a nudge of 0.1: (3.12−32)/0.1=(9.61−9)/0.1=6.1(3.1^2 - 3^2) / 0.1 = (9.61 - 9) / 0.1 = 6.1.

With a nudge of 0.01: (3.012−32)/0.01=(9.0601−9)/0.01=6.01(3.01^2 - 3^2) / 0.01 = (9.0601 - 9) / 0.01 = 6.01.

The estimates are closing in on 6. The rule says the derivative of x2x^2 is 2x2x, which is exactly 6 at x=3x = 3.

Exerciseby hand

Where is the lowest point of f(x)=x2−6x+10f(x) = x^2 - 6x + 10, and how low is it?

Hint

At a lowest point the derivative is zero. The derivative of x2−6x+10x^2 - 6x + 10 is 2x−62x - 6.

Solution

At a lowest point the derivative is zero. The derivative is 2x−62x - 6, which is zero at x=3x = 3. There, f(3)=9−18+10=1f(3) = 9 - 18 + 10 = 1.

So the lowest point is at x=3x = 3, 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.

Exerciseby hand

Let f(w,b)=w2+3b2f(w, b) = w^2 + 3b^2. Find the gradient at w=2w = 2, b=1b = 1. If you wanted to make ff 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 ww is 2w2w, and with respect to bb it is 6b6b. At the point (2, 1) the gradient is [4, 6][4,\ 6].

The gradient points uphill, so to make ff smaller move the opposite way, along [−4, −6][-4,\ -6]: decrease both ww and bb, and bb by more, because the surface is steeper in that direction.

Exerciseby hand

Let y=(3x+1)2y = (3x + 1)^2. Use the chain rule to find how fast yy changes with xx at x=1x = 1. Check your answer by nudging xx to 1.001.

Hint

Name the inside u=3x+1u = 3x + 1. Find how fast uu changes with xx, how fast yy changes with uu, and multiply.

Solution

Split the calculation into two steps: u=3x+1u = 3x + 1, then y=u2y = u^2. The rates are 3 for the first step and 2u2u for the second. At x=1x = 1, u=4u = 4, so the second rate is 8. Rates multiply along the chain: 3×8=243 \times 8 = 24.

Check: at x=1.001x = 1.001, u=4.003u = 4.003 and y=16.024009y = 16.024009. The change in yy is 0.024009 for a nudge of 0.001, a rate of about 24.01.

Exercisewith the figure

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.

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 0.2.1How fast is it changing?
  3. 0.2.2Slope by nudging
  4. 0.2.3Rules instead of nudging
  5. 0.2.4Several inputs at once
  6. 0.2.5The chain rule
  7. 0.2.6In code
  8. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in