Index Ai Academy
Phase 2 · Math, when you need it · Calculus

Derivatives

The slope at a point: how fast the output changes.

About 30 minutes · A free account opens the whole lesson

Create a free account Try part of it here

Already have an account? Sign in to open this lesson

Why it matters

A derivative answers one question: if you nudge the input a little, how much does the output change? You already know the idea from a car. The speedometer tells you how fast your distance is changing right now. Marketers know it as marginal return: the extra sales from the next $100 of ad spend.

Machine learning uses it for one decision, repeated billions of times. A model has many settings called weights, and an error score called the loss. For each weight, training asks: would nudging it up make the loss go up or down, and by how much? That number tells training which way to move. Almost everything else in deep learning is bookkeeping around it.

What you'll be able to do

  • Explain a derivative as the slope of a function at a point: the rate of change
  • Estimate derivatives numerically with a small step
  • Read the sign and size of a derivative: uphill, downhill, flat
  • Use marginal returns to decide where extra spend stops paying off

What it covers

  1. Steepness you already know
  2. Slope between two points
  3. Shrink the step: the derivative
  4. Computing it in code
  5. Worked example: reading the speedometer
  6. Reading a derivative
  7. Marginal returns

Steepness you already know

Picture a hike. On a gentle path you climb a little for each step forward. On a steep path you climb a lot. Road signs put a number on it: a 10% grade means you rise 10 feet for every 100 feet you move forward.

That number is a slope: rise divided by run. For a straight line it's the same everywhere. Say a line passes through the points (0, 1) and (2, 5). It rises 4 while it runs 2. So its slope is 4 ÷ 2 = 2. Every step of 1 to the right lifts it by 2.

A curve is harder. It can be flat in one place and steep in another. So we ask for the slope at one point. That slope at a point is called the derivative. A speedometer shows one: it tells you how fast you're going at this moment, not your average over the whole trip.

Slope between two points

Take the curve f(x)=x2f(x) = x^2. Here ff is the function. The letter xx is its input. Feed in 3 and you get 9 out.

To find how steep the curve is at x=3x = 3, start with two points. One is at 3. The other is a small step further along. Call the size of that step hh. Then measure the slope of the straight line through the two points. That line is called a secant.

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

In plain words: step forward by hh. See how much the output changed. Divide that change by the size of the step. The wavy equals sign means "roughly equal to".

Worked with small numbers, at x=3x = 3:

  • Step h=1h = 1: the outputs are 16 and 9. The change is 7, divided by 1 gives 7.
  • Step h=0.1h = 0.1: the outputs are 9.61 and 9. The change is 0.61, divided by 0.1 gives 6.1.

The smaller the step, the closer the two points sit. You'll see this in Python in a moment: the one-sided column in the code below is exactly this calculation.

Quick check
On the curve f(x) = x², what is the slope of the straight line through x = 1 and x = 3?
  1. 2
  2. 9
  3. 8
  4. 4
Show the answer

4

The outputs are 1 and 9, so the rise is 8. The run is 3 − 1 = 2. Rise over run: 8 ÷ 2 = 4.

Shrink the step: the derivative

Now make hh smaller and smaller. The second point slides toward the first. The secant line swings around until it touches the curve at that one point. That touching line is the tangent. Its slope is the derivative.

f′(x)=lim⁡h→0f(x+h)−f(x)hf'(x) = \lim_{h \to 0} \frac{f(x + h) - f(x)}{h}

In plain words: f′(x)f'(x), said "f prime of x", is the derivative of ff at xx. The lim⁡h→0\lim_{h \to 0} part means "the value this fraction settles on as the step hh gets closer and closer to 0". You never set hh to exactly 0, since you can't divide by 0.

For f(x)=x2f(x) = x^2 at 3, the slopes went 7, then 6.1. With h=0.01h = 0.01 you get 6.01. They are closing in on 6. So the derivative of x2x^2 at 3 is 6.

You'll also see the derivative written as dfdx\frac{df}{dx}, read "d f by d x". It means the same thing: how fast ff changes as xx changes.

Try it now

Shrink h. The red secant through two points turns into the tangent, and its slope approaches f′(1) = 2.

Computing it in code

You can't make hh shrink forever on a computer. But a tiny hh gets you very close. A better trick is to take a small step each side of the point and measure across both. This is the central difference:

f′(x)≈f(x+h)−f(x−h)2hf'(x) \approx \frac{f(x + h) - f(x - h)}{2h}

In plain words: look a little to the right and a little to the left. Take the change in output between those two points. Divide by the distance between them, which is 2h2h.

Worked at x=3x = 3 with h=1h = 1: the outputs at 4 and 2 are 16 and 4. The change is 12. The distance is 2. So the estimate is 12 ÷ 2 = 6, the true answer.

Here are both methods side by side, with smaller and smaller steps:

def f(x):
    return x ** 2

x = 3
for h in [1, 0.1, 0.01, 0.0001]:
    one_sided = (f(x + h) - f(x)) / h
    central = (f(x + h) - f(x - h)) / (2 * h)
    print(f"h={h:<7} one-sided={one_sided:.6f}  central={central:.6f}")
It runs right here in your browser, with nothing to install.

The one-sided column creeps toward 6: 7, then 6.1, then 6.01, then 6.0001. The central column shows 6 on every row. That's why the central difference is the one to use.

Go deeper Why the central difference does so well

A one-sided step only looks ahead. On a curve that bends, that view is lopsided, so it overshoots or undershoots. The central difference looks both ways, and the two lopsided errors mostly cancel. For a curve shaped exactly like x2x^2 they cancel completely, which is why every row shows 6. For most other curves they don't cancel completely, but the result is still much closer than a one-sided step of the same size.

Engineers use numerical derivatives like this to check their gradient code. They're too slow for training, though. Each weight needs at least one extra run of the function, and big models have billions of weights. The next lessons give exact formulas instead.

Worked example

Worked example: reading the speedometer

You start a road trip and slowly speed up. After t hours you have driven 50 × t + 5 × t² miles. How fast are you going at the 2-hour mark? Use the central difference with a step of half an hour each side.

def miles(t):
    return 50 * t + 5 * t ** 2

t, h = 2, 0.5
print(miles(t + h), miles(t - h))
print((miles(t + h) - miles(t - h)) / (2 * h))
In the lesson you can change this and run it.

At 2.5 hours you've driven 156.25 miles. At 1.5 hours you'd driven 86.25 miles. That's 70 miles in the hour between them, so at the 2-hour mark you're doing 70 miles per hour. That number is the derivative of distance with respect to time: what the speedometer shows.

Quick check
Predict the output (roughly).
f = lambda x: x ** 2
print((f(4.1) - f(3.9)) / 0.2)
  1. About 0.8
  2. About 16
  3. About 4
  4. About 8
Show the answer

About 8

This is the central difference at x = 4 with h = 0.1. The outputs are 16.81 and 15.21, a change of 1.6. Divided by 0.2 that's 8. Python prints 7.999999999999998 because of tiny rounding in decimals.

Reading a derivative

Back to the hike. The derivative tells you what the ground is like under your feet, if you face toward bigger xx:

f′(x)f'(x)Meaning at that point
positivegoing uphill: increasing xx increases ff
negativegoing downhill: increasing xx decreases ff
zeroflat: a peak, a valley, or a plateau
large in sizesteep: small changes in xx have big effects

At the very top of a hill and the very bottom of a valley, the ground is flat. The derivative is zero there. That's why "find where the derivative is zero" is the classic way to find the best value of something.

It's also why a tiny gradient during training can mean two different things. (A gradient is the derivative when there are many weights; you'll meet it soon.) Training may have reached the bottom of the valley. Or it may be stuck on a flat plateau.

Quick check
At the current weight value, the derivative of the loss is −4. What should training do to lower the loss?
  1. Leave it: the loss is at its minimum
  2. Decrease the weight
  3. Set the weight to −4
  4. Increase the weight: the loss goes down as the weight goes up
Show the answer

Increase the weight: the loss goes down as the weight goes up

A negative slope means downhill is to the right, so a bigger weight gives a smaller loss.

Marginal returns

In the functions lesson you met a curve for ad conversions. As spend grows, conversions keep rising, but more and more slowly. Here it is again. The letter ss is the spend in dollars. Then c(s)c(s) is the number of conversions that spend buys:

c(s)=900⋅ss+4000c(s) = 900 \cdot \frac{s}{s + 4000}

In plain words: conversions can never pass 900, the ceiling. The 4000 sets how fast you approach it: spending $4,000 gets you halfway, to 450.

Worked example: spend $1,000 and you get 900 × 1000 ÷ 5000 = 180 conversions.

The derivative c′(s)c'(s) is the marginal return: the extra conversions from one more dollar at spend ss. Each conversion earns a $60 margin. So one more dollar of spend brings back 60⋅c′(s)60 \cdot c'(s) dollars. That extra dollar pays for itself only while this is more than 1:

60⋅c′(s)>160 \cdot c'(s) > 1

In plain words: keep spending while the next dollar earns back more than a dollar.

The code estimates c′(s)c'(s) with the central difference at five budgets:

import numpy as np

def conversions(s):
    return 900 * s / (s + 4000)

def derivative(f, x, h=1e-3):
    return (f(x + h) - f(x - h)) / (2 * h)

for spend in [1000, 5000, 10000, 15000, 20000]:
    marginal = derivative(conversions, spend)
    label = f"${spend:,}"
    print(f"at {label:>7}: {marginal * 1000:6.2f} conversions per extra $1,000, worth ${60 * marginal:.2f} per $1")

Read one row. At $10,000 the next $1,000 buys about 18.37 conversions. That's about 0.018 per dollar, worth $1.10 at $60 each. Still worth it. At $15,000 the next dollar brings back only $0.60.

So somewhere between $10,000 and $15,000 the next dollar starts returning less than a dollar. That crossover is the profit peak you found by grid search in the functions lesson. This time you found it by reading slopes.

Quick check
At $20,000 of spend, the code shows each extra $1 brings back $0.37. What should you do with the budget?
  1. Raise it: conversions are still going up
  2. Keep it: $0.37 is positive, so it's profitable
  3. Lower it: each extra dollar there earns back only about 37 cents
  4. Double it to reach the ceiling of 900
Show the answer

Lower it: each extra dollar there earns back only about 37 cents

Conversions still rise, but each extra dollar returns less than a dollar. Past the crossover, extra spend loses money, so the budget should come down toward it.

Practice what you just read

  • 3 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 4 review cards for spaced repetition

Create a free account

Try a quiz question

What does f′(x) = 0 tell you?

  1. The function is flat at x: possibly a peak, valley or plateau
  2. f(x) = 0: the function's output is zero at x
  3. The function doesn't exist or is undefined at x
  4. x is the largest input the function can accept

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson