Lesson 4 of 7 · Math for AI: Linear Algebra & Calculus Essentials

Derivatives: Slope, Rate of Change & the Functions ML Uses

Training a model comes down to one question asked millions of times: if I nudge this number, does the loss go up or down, and by how much? A derivative is the exact answer.

The statistics course, Lesson 8 (The Statistics Behind Training a Model), described gradient descent as "feel the slope, step downhill" and skipped the calculus. This lesson supplies it, using only algebra. A function f(x) turns an input into an output, and its derivative says how fast the output changes when the input changes.

1. Slope: how fast is something changing?

A team logs the training loss of a model at the end of each epoch (one pass over the data). At epoch 2 the loss is 2.40. At epoch 5 it is 1.80. How fast is it falling? Divide the change in loss by the change in epochs:

slope = (change in output) / (change in input)
= (1.80 − 2.40) / (5 − 2)
= −0.60 / 3
= −0.20 loss per epoch

The negative sign means "going down." The size means "0.20 units of loss per epoch." That is the whole idea of a rate of change: output units per input unit. For a straight line the slope is the same everywhere, so two points are enough.

Real loss curves are not straight: early epochs may drop 0.5 each, later ones 0.01. The slope above is only an average. Training needs the slope at one exact spot, because the next update happens at one spot. That is the derivative.

2. From average slope to exact slope: shrink the gap

Take a curve whose slope changes: f(x) = x². We want its slope at x = 3, where f(3) = 9. Pick a second point a small distance h to the right, at x = 3 + h, and compute the slope between the two points:

slope between the points = ( f(3 + h) − f(3) ) / h

Start with h = 1 and keep shrinking it. In Python: for h in [1, 0.1, 0.01, 0.001, 1e-6]: print(h, (f(3+h) - f(3)) / h) with f = lambda x: x*x.

hf(3 + h)slope = (f(3 + h) − 9) / h
1167.0
0.19.616.1
0.019.06016.01
0.0019.0060016.001
0.0000019.0000060000016.000001

(Python adds tiny rounding noise in the last digits; the table shows exact values.) The slopes march toward 6: 7, 6.1, 6.01, 6.001. You can see why with algebra. For any h:

(3 + h)² − 3² = 9 + 6h + h² − 9 = 6h + h²
divide by h: 6 + h
as h shrinks toward 0, 6 + h gets as close to 6 as you like

"As close to 6 as you like by making h small enough" is exactly what a limit means. You never set h to 0 (that would be 0/0, which is undefined); you ask where the slope is heading. The derivative of f at x is that limit, written f′(x) (read "f prime of x") or df/dx:

f′(x) = limit as h → 0 of ( f(x + h) − f(x) ) / h

Doing the same algebra at a general x gives (x + h)² − x² = 2xh + h², so the slope is 2x + h and the derivative is 2x. At x = 3 that is 6, matching the table.

Key Insight A derivative is not a new kind of object. It is the ordinary slope from section 1, measured between two points that have been pushed so close together that the curve looks straight between them.

3. The tangent line: the best straight-line stand-in

Once you know the slope at a point, you can draw the straight line through that point with that slope. It is the tangent line. For f(x) = x² at x = 3 the point is (3, 9) and the slope is 6, so the tangent is y = 9 + 6(x − 3), which simplifies to y = 6x − 9.

012 34 x 05101520 f(x) = x² (3, 9) tangent, slope 6 secant to (4, 16), slope 7

The blue curve is y = x². The dashed yellow line joins the points at x = 3 and x = 4 (average slope 7). Slide the second point toward x = 3 and that line rotates into the solid green tangent, slope 6, which is the derivative.

Near the touching point the tangent and the curve are almost the same, so you can use the tangent as a cheap replacement. This is the best local linear approximation: f(x) ≈ f(a) + f′(a)(x − a) for x close to a. Test it:

Tangent at a = 3: y = 9 + 6(x − 3)
x = 3.1: tangent = 9 + 6(0.1) = 9.6 true f = 3.1² = 9.61 error 0.01
x = 2.5: tangent = 9 + 6(−0.5) = 6.0 true f = 2.5² = 6.25 error 0.25
x = 4: tangent = 9 + 6(1) = 15 true f = 16 error 1

The error is exactly (x − 3)², so shrinking the distance by 10 shrinks the error by 100. This is why gradient descent takes small steps: the derivative describes the loss only near where you stand. The learning rate from the statistics course, Lesson 8, is how far you trust the straight-line picture.

4. The rules you actually need

You will almost never compute a derivative from the limit. A short list of rules covers nearly everything. Below, c is a fixed number, and f and g are functions of x.

RuleStatementExample
Constantd/dx of c = 0a bias offset of 7 never changes as x changes: slope 0
Powerd/dx of xn = n·xn−1x³ → 3x²; at x = 2 the slope is 12
Constant multipled/dx of c·f = c·f′5x² → 5·2x = 10x
Sum(f + g)′ = f′ + g′x² − 6x + 10 → 2x − 6 + 0
Product(f·g)′ = f′g + fg′see below
Quotient(f/g)′ = (f′g − fg′) / g²see below

Check the power rule against section 2: x² has n = 2, so the derivative is 2x. Subtraction works like the sum rule, and 6x is 6 times x¹, giving 6.

The product and quotient rules each need both pieces. Two short examples (the symbol e and the function ex are introduced in the next section; here just use that its derivative is itself):

Product: h(x) = x² · ex
h′(x) = (2x)(ex) + (x²)(ex) = ex(2x + x²)
at x = 1: e · (2 + 1) = 3e ≈ 8.1548
Quotient: k(x) = x / (x + 1)
k′(x) = ( (1)(x + 1) − (x)(1) ) / (x + 1)² = 1 / (x + 1)²
at x = 1: 1 / 4 = 0.25

Both agree with the shrinking-h method: at h = 10⁻⁶ the product slope is 8.15486 and the quotient slope is 0.2499999.

5. The exponential and the natural log

Two functions show up in nearly every ML formula. The exponential ex, where e ≈ 2.71828 is a fixed constant, has the unusual property that it is its own derivative: d/dx of ex = ex. Its slope at every point equals its height. Check at x = 0: the height is e0 = 1, and with h = 0.001 the slope is (e0.001 − 1)/0.001 = 1.0005, heading to 1.

The natural logarithm ln(x) is the inverse: ln(ex) = x. It is defined for x > 0, and its derivative is d/dx of ln(x) = 1/x. At x = 2 the slope is 0.5; at x = 0.1 the slope is 10. The curve flattens as x grows and becomes very steep near 0. Remember that: it explains log loss in section 6.

One extra rule is needed, in its simplest form. When a function is nested inside another, the chain rule says: multiply the outer function's derivative (evaluated at the inner function's value) by the inner function's derivative. Example: e−x has outer function eu and inner function u = −x. The outer derivative is eu = e−x, the inner derivative is −1, so d/dx of e−x = −e−x.

6. Derivatives of the functions that appear in ML

6a. Squared error

A regression model predicts a number ŷ (read "y-hat") for a target value y. The squared error is L(ŷ) = (y − ŷ)². Treat y as a fixed number and ask how the loss changes as the prediction moves. Expand and use the rules:

L = (y − ŷ)² = y² − 2yŷ + ŷ²
dL/dŷ = 0 − 2y + 2ŷ = −2(y − ŷ)

A toy relevance-scoring model should output y = 1.0 but outputs ŷ = 0.4:

loss = (1.0 − 0.4)² = 0.6² = 0.36
slope = −2(1.0 − 0.4) = −1.2

The slope is negative, so raising ŷ lowers the loss. At ŷ = 0.7 the loss is 0.09 and the slope is −0.6: as the prediction improves the slope shrinks toward 0, which is why training slows near a good solution without anyone programming it to.

6b. The sigmoid

The sigmoid σ(x) = 1 / (1 + e−x) squeezes any number into the range 0 to 1, so a classifier can read it as a probability (see the statistics course, Lesson 3, Probability Foundations & Bayes' Theorem). Differentiate it with the quotient rule. The numerator is 1 (derivative 0). The denominator is g = 1 + e−x, with g′ = −e−x from the chain-rule example above.

σ′(x) = ( 0·g − 1·g′ ) / g² = e−x / (1 + e−x)²
Split into two fractions:
[ 1 / (1 + e−x) ] · [ e−x / (1 + e−x) ] = σ(x) · (1 − σ(x))
because 1 − σ(x) = e−x / (1 + e−x)

So σ′ = σ(1 − σ): once you have computed the sigmoid's output, its derivative costs one multiplication. Values:

xσ(x)σ′(x) = σ(1 − σ)
−40.01800.0177
−20.11920.1050
00.50000.2500
20.88080.1050
40.98200.0177

The slope peaks at 0.25 at x = 0 and is nearly flat in the tails, so a unit with a far-from-zero input passes almost no learning signal back ("saturation").

6c. ReLU and its sharp corner

The ReLU (rectified linear unit) is ReLU(x) = max(0, x): it returns 0 for negative inputs and the input itself for positive ones. For x < 0 it is the flat line 0, so the slope is 0. For x > 0 it is the line y = x, so the slope is 1.

ReLU(−2) = 0 slope 0
ReLU( 3) = 3 slope 1
ReLU( 0) = 0 slope: ???

At exactly x = 0 the curve has a corner. Approaching from the left the slope is 0; from the right it is 1. The shrinking-h slope (ReLU(0 + h) − ReLU(0)) / h equals 1 for positive h and 0 for negative h, so the two sides never agree on one limit. The derivative does not exist at 0, and ReLU is called non-differentiable there.

Training code still needs a number, so deep-learning frameworks pick one: they typically define the gradient at exactly 0 to be 0 (a convention, not a theorem; check your framework's documentation). A floating-point input is almost never exactly 0, so a corner is not a crash, just one point with a fixed rule.

6d. Log loss: −log(p)

When a classifier says the true class has probability p, its penalty is log loss (cross-entropy for a single example), L(p) = −ln(p). It connects to the information measures in the statistics course, Lesson 7 (Information Theory). From section 5, d/dp of ln(p) = 1/p, so the constant multiple rule gives L′(p) = −1/p.

p on the true classloss −ln(p)slope −1/p
0.90.1054−1.11
0.50.6931−2
0.12.3026−10
0.014.6052−100

Every slope is negative: more probability on the right answer lowers the loss. The slope blows up as p nears 0, so a confidently wrong prediction gets a huge corrective push.

In a real classifier p comes from a sigmoid of a raw score z (called a logit): p = σ(z). Chain the two derivatives, outer first:

L(z) = −ln σ(z)
dL/dz = ( −1/σ ) · σ(1 − σ) = −(1 − σ) = σ(z) − 1
z = 2: σ(2) = 0.8808 dL/dz = 0.8808 − 1 = −0.1192
z = −2: σ(−2) = 0.1192 dL/dz = 0.1192 − 1 = −0.8808

The product collapses to "prediction minus target". A score of 2 is mostly right and gets a gentle −0.1192; a score of −2 is mostly wrong and gets −0.8808. The 1/σ from log loss cancels the sigmoid's flat tails, so a confident wrong answer is not starved of gradient.

7. Reading the sign: which way do I move?

The derivative of the loss with respect to a parameter tells you two things at once.

The update rule that combines these is x ← x − (learning rate) × f′(x). Subtracting the slope moves you against it, which is always downhill. Take the loss f(x) = (x − 3)² + 1 = x² − 6x + 10, whose derivative by the sum, power and constant rules is f′(x) = 2x − 6. Start at x = 0 with learning rate 0.1:

stepxf(x)f′(x) = 2x − 6next x = x − 0.1·f′(x)
0010−60 − 0.1(−6) = 0.6
10.66.76−4.80.6 + 0.48 = 1.08
21.084.6864−3.841.08 + 0.384 = 1.464
31.4643.3593−3.0721.464 + 0.3072 = 1.7712

The slope is negative the whole way, so x keeps moving right, the loss keeps dropping (10, 6.76, 4.69, 3.36), and the slope's magnitude shrinks each step, so the steps shrink too (the next x would be 1.7712). The minimum is where 2x − 6 = 0, that is x = 3, with loss 1. The same recipe, applied to millions of parameters at once, is training; M5 shows how.

Curvature, in one paragraph. The derivative of the derivative is the second derivative f″(x): how fast the slope itself changes. For x² − 6x + 10 it is the derivative of 2x − 6, which is 2: positive everywhere, so the curve bends upward like a bowl. Slope 0 with a positive second derivative is a minimum; with a negative one, a peak. A large second derivative means the slope changes fast, so a step that was safe can overshoot, which is the geometry behind "learning rate too big" in the statistics course, Lesson 8.

8. Debugging habit: check your derivative numerically

Hand-derived gradients are easy to get subtly wrong, and a wrong gradient often does not crash anything: the loss just trains badly. The cheap defense is a finite-difference check. Use the definition from section 2 to estimate the slope with a small h, and compare it to your formula. A slightly better estimate uses points on both sides of x (the central difference):

estimate = ( f(x + h) − f(x − h) ) / (2h)

Test the log-loss-through-sigmoid derivative from section 6d at z = 2, where the formula says −0.1192:

import math
s = lambda z: 1 / (1 + math.exp(-z))
L = lambda z: -math.log(s(z))
for h in [1e-2, 1e-5, 1e-8]:
est = (L(2 + h) - L(2 - h)) / (2 * h)
print(h, est, abs(est - (s(2) - 1)) / abs(s(2) - 1))
hcentral-difference estimaterelative error vs. σ(2) − 1
10−2−0.1192041.1 × 10−5
10−5−0.11920295 × 10−13
10−8−0.11920295 × 10−8

Smaller is not always better: at 10⁻⁸ rounding error dominates and the check gets worse again; around 10⁻⁵ is a good default. Now suppose someone wrote the derivative as just −σ(z), a plausible slip. Their formula gives −0.8808 at z = 2 while the estimate says −0.1192: relative error ≈ 6.4, a loud failure. A correct formula agrees to roughly 10⁻⁶ or better.

Pitfall Finite differences are for checking, not training: each parameter needs an extra model evaluation, so a billion parameters means a billion extra runs per step. Check a tiny model or a few random parameters, then turn it off. Do not test exactly at a corner like ReLU at 0, where the true derivative does not exist.

9. Why this matters for building AI systems

Vanishing signals have a concrete cause. The sigmoid's slope never exceeds 0.25 and is near 0 in its tails. Multiply several such slopes together, as happens when learning signals pass back through many layers, and the product collapses: 0.25 × 0.25 × 0.25 = 0.0156. When early layers barely learn, the table in section 6b is the first place to look.

Loss choices are derivative choices. Squared error has a gentle slope that fades as predictions improve; log loss has a slope of −1/p that is huge for confident mistakes. The derivative tells you which examples dominate training.

Numerical checks catch silent bugs. A finite-difference check on a custom layer or loss is a ten-line test that catches wrong signs and missing terms before they cost a training run.

Recap

Leads into M5

Everything here involved one input at a time. A real model has millions of parameters, and the loss depends on all of them. M5 (Partial Derivatives & Gradients) asks for the slope along each parameter separately, collects those slopes into a single vector called the gradient, and shows why that vector points uphill, which is what gradient descent walks against.

✅ Check Yourself

1. For f(x) = x², the slope between x = 3 and x = 3 + h is 6 + h. What is the derivative at x = 3, and why?

0, because setting h = 0 makes the numerator zero
7, because that is the slope for the first step you try
6, because 6 + h gets as close to 6 as you like when h shrinks toward 0

2. A loss is L(w) = 5w² − 20w + 7. What is its derivative, and where is its minimum?

10w − 20, so the minimum is at w = 2
10w − 20 + 7, so the minimum is at w = 1.3
5w − 20, so the minimum is at w = 4

3. A sigmoid unit outputs σ(x) = 0.9 for some input. What is the sigmoid's slope at that input?

0.9, because the slope equals the output
0.09, because σ′ = σ(1 − σ) = 0.9 × 0.1
0.25, because the sigmoid's slope is always 0.25

4. A network's loss has a derivative of +3.5 with respect to one weight, and the learning rate is 0.1. What does a gradient descent update do to that weight?

Increases it by 0.35, because the slope is positive
Leaves it unchanged, because the slope is not zero
Decreases it by 0.35, because raising the weight would raise the loss

5. Your hand-written gradient for a custom loss gives −0.88 at a test point, but a central-difference estimate with h = 10−5 gives −0.12. What should you conclude?

The finite-difference estimate is probably wrong, because it is only approximate
Your formula almost certainly has a bug, since a correct one would agree to about 5 or more decimal places
Both are fine, because gradients only need to point in roughly the right direction