◆ AI All-in-One

Level 3 In-Depth AI · Math Foundations

Derivatives and Slopes

A derivative measures how fast something changes when you nudge its input. It is the slope of a curve at a point. Training an AI model means computing the derivative of its error with respect to every weight and nudging each weight downhill.

Level
●●●●● Easy
Reading
11 min
To learn it well
50 minutes to read, an hour to practise
↗ Plan a path here

Read first

Nothing — start here.

This leads to

The Chain RuleMaximum Likelihood EstimationPartial Derivatives and Gradients

Why it matters

Training an AI model is a loop of three steps: make predictions, measure how wrong they are (the loss), then adjust the model's weights to make the loss a little smaller. The hard part is the third step. A model may have billions of weights. For each one you need to know: if I nudge this weight up a tiny bit, does the loss go up or down, and by how much?

That question, "how much does the output change when I nudge the input?", is exactly what a derivative answers. Every time Gradient Descent takes a step, it uses derivatives. Every time PyTorch runs loss.backward(), it computes derivatives, billions of them, using the The Chain Rule in a procedure called Backpropagation.

You do not need to become good at calculus exercises to work in AI. Libraries compute derivatives for you. But you do need to understand what a derivative means, because it explains why training works, why it sometimes fails, and what all those grad values are.

The intuition

Slope as steepness

Imagine walking along a hilly road. At every point the road has a slope: how many metres you climb for each metre you walk forward. A road that rises 10 metres over 100 metres has a slope of 10/100=0.110 / 100 = 0.1, a 10% gradient as road signs say. Flat road has slope 0. Going downhill, the slope is negative.

For a straight line, the slope is the same everywhere: rise divided by run. A curve is trickier, because its steepness changes as you go. So we ask for the slope at one point. Zoom in on a smooth curve far enough and it looks like a straight line. The slope of that line is the derivative at that point. The straight line that just touches the curve there, with that slope, is called the tangent line.

Slope as sensitivity

There is a second, equally useful reading. The derivative says how sensitive the output is to the input. If the derivative of your loss with respect to some weight is 3, then nudging that weight up by 0.01 raises the loss by about 3×0.01=0.033 \times 0.01 = 0.03. If the derivative is −3, the same nudge lowers the loss by about 0.03. If it is 0, a small nudge does almost nothing.

A thermostat analogy: if turning the dial up one notch makes the room 2 degrees warmer, the "derivative of temperature with respect to the dial" is 2 degrees per notch.

Key idea The derivative is the slope of a function at a point: how much the output changes per unit change of the input, for a tiny nudge. In AI, it tells you which way to move each weight to reduce the loss.

How it works

From chords to tangents

Take f(x)=x2f(x) = x^2 and ask for its slope at x=1x = 1. We can't take the rise over the run of a single point, so we use two points close together: x=1x = 1 and x=1+hx = 1 + h, where hh is a small step. The straight line through them is called a chord. Its slope is rise over run:

slope of chord=f(1+h)−f(1)h\text{slope of chord} = \frac{f(1 + h) - f(1)}{h}

Work it out for shrinking steps:

Step hh f(1+h)f(1+h) Rise f(1+h)−f(1)f(1+h) - f(1) Slope = rise / hh
2 9 8 4
1 4 3 3
0.5 2.25 1.25 2.5
0.1 1.21 0.21 2.1
0.001 1.002001 0.002001 2.001

The slopes close in on 2. That limit is the derivative of x2x^2 at x=1x = 1.

x f(x) = x² the point x = 1 x = 3 x = 2 x = 1.5 Chords from x = 1 to x = 1 + h slope = (f(1 + h) − f(1)) / h step h slope 2 4 1 3 0.5 2.5 0.001 2.001 → 0 → 2 As the step shrinks, the chord turns into the tangent line (red), whose slope is the derivative: f′(1) = 2.
Fig. 1 The curve f(x) = x² with chords from x = 1 to x = 3, 2 and 1.5. As the second point slides closer, the chord's slope falls from 4 to 3 to 2.5 and approaches 2, the slope of the red tangent line at x = 1.

The formal definition says exactly this. The derivative of ff at xx is the value the chord slope approaches as the step hh shrinks towards zero:

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

"lim" means "the limit as hh goes to 0", the value approached but never quite reached. Two notations are common. f′(x)f'(x) ("f prime of x") is compact. dfdx\frac{df}{dx} ("d f by d x") reminds you it is a tiny change in ff divided by a tiny change in xx. They mean the same thing.

Doing it with algebra

For f(x)=x2f(x) = x^2 we can do the limit exactly:

(x+h)2−x2h=x2+2xh+h2−x2h=2xh+h2h=2x+h\frac{(x + h)^2 - x^2}{h} = \frac{x^2 + 2xh + h^2 - x^2}{h} = \frac{2xh + h^2}{h} = 2x + h

As hh shrinks to 0, this becomes 2x2x. So the derivative of x2x^2 is 2x2x: at x=1x = 1 the slope is 2, at x=3x = 3 it is 6, at x=−1x = -1 it is −2-2. Notice that the derivative is itself a function: it gives the slope at every point.

The rules you actually need

Nobody computes limits each time. A handful of rules cover almost everything:

Function f(x)f(x) Derivative f′(x)f'(x) Example
a constant cc 00 flat line, no slope
xnx^n (power rule) n xn−1n\,x^{n-1} x3→3x2x^3 \to 3x^2,   x→1\;x \to 1
c⋅g(x)c \cdot g(x) c⋅g′(x)c \cdot g'(x) 5x2→10x5x^2 \to 10x
g(x)+k(x)g(x) + k(x) g′(x)+k′(x)g'(x) + k'(x) x2+3x→2x+3x^2 + 3x \to 2x + 3
exe^x exe^x the exponential is its own slope
ln⁡x\ln x (natural log) 1/x1/x used in every log-likelihood loss
sigmoid σ(x)=11+e−x\sigma(x) = \frac{1}{1 + e^{-x}} σ(x) (1−σ(x))\sigma(x)\,(1 - \sigma(x)) at 0: 0.5×0.5=0.250.5 \times 0.5 = 0.25
ReLU max⁡(0,x)\max(0, x) 0 if x<0x < 0, 1 if x>0x > 0 the most common activation

The last two are Activation Functions used inside neural networks. Their derivatives matter because every gradient flows through them. The sigmoid's slope is never more than 0.25, which is one reason deep stacks of sigmoids train badly (Vanishing and Exploding Gradients). The ReLU's slope is exactly 1 for positive inputs, which helps a lot.

For functions built by plugging one function into another, such as σ(wx+b)\sigma(wx + b), you need the The Chain Rule, the next chapter.

Minima: where the slope is zero

The sign of the derivative tells you which way is downhill:

  • Negative slope: the function goes down as xx increases. Downhill is to the right.
  • Positive slope: the function goes up as xx increases. Downhill is to the left.
  • Zero slope: the curve is flat. You are at the bottom of a valley (a minimum), the top of a hill (a maximum), or a flat ledge.

Take the loss L(w)=(w−2)2+1L(w) = (w - 2)^2 + 1. Its derivative, by the rules above, is L′(w)=2(w−2)L'(w) = 2(w - 2). At w=0.5w = 0.5 the slope is −3-3, so increase ww. At w=3.5w = 3.5 it is +3+3, so decrease ww. At w=2w = 2 it is 0: that is the minimum, where the loss is 1.

slope −3 slope 0 slope +3 loss L(w) = (w − 2)² + 1 w L′(w) = 2(w − 2) w + − zero at the minimum Reading a slope negative: downhill is to the right zero: flat; a minimum (or a maximum) positive: downhill is to the left The derivative is itself a function: one slope for every w
Fig. 2 Top: the loss L(w) = (w − 2)² + 1 with tangent lines at three points: slope −3 on the left, slope 0 at the bottom, slope +3 on the right. Bottom: the derivative L′(w) = 2(w − 2) as its own graph. It crosses zero exactly where the loss is lowest.

This gives the core rule of training: move the weight against the sign of the slope. Subtract a small multiple of the derivative: w←w−η L′(w)w \leftarrow w - \eta\, L'(w), where η\eta is the learning rate. That is Gradient Descent in one line.

For simple functions you can also find the minimum directly by solving L′(w)=0L'(w) = 0. Here 2(w−2)=02(w - 2) = 0 gives w=2w = 2. For a neural network with millions of weights there is no such formula, so we walk downhill step by step instead.

The second derivative: curvature

The derivative of the derivative is the second derivative, written f′′(x)f''(x). It tells you how fast the slope itself is changing, which is the curvature. For L(w)=(w−2)2+1L(w) = (w - 2)^2 + 1, L′′(w)=2L''(w) = 2: positive everywhere, meaning the curve bends upward like a bowl, so the flat point is a minimum. A negative second derivative would mean a hilltop. Some advanced optimisers use curvature to choose step sizes, but most deep learning gets by with first derivatives only, because second derivatives for billions of weights are too expensive.

Numerical derivatives

You can estimate a derivative with a computer and no algebra at all: just compute the chord slope with a very small hh. This is a finite difference. A more accurate version uses a chord centred on xx:

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

This is too slow for training, since it needs two extra evaluations of the loss per weight, which for a billion weights is hopeless. But it is perfect for checking derivatives computed in other ways, a technique called gradient checking.

In code

import numpy as np

def f(x):
    return x ** 2

def numerical_derivative(f, x, h=1e-5):
    # central difference: slope of a tiny chord centred on x
    return (f(x + h) - f(x - h)) / (2 * h)

for h in [1, 0.1, 0.001]:
    print(h, (f(3 + h) - f(3)) / h)          # chord slopes approach 6
# 1 7.0
# 0.1 6.100000000000012
# 0.001 6.000999999999479

print(numerical_derivative(f, 3.0))           # 6.000000000039306  (exact: 2*3 = 6)

# The sigmoid and its derivative sigma * (1 - sigma)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
z = 0.5
exact = sigmoid(z) * (1 - sigmoid(z))
print(exact, numerical_derivative(sigmoid, z))
# 0.2350037122015945 0.23500371220119828   they agree

In PyTorch you never write derivative formulas. You mark a tensor with requires_grad=True, compute with it, and call .backward(). This is called automatic differentiation:

import torch

x = torch.tensor(3.0, requires_grad=True)
y = x ** 2
y.backward()          # compute dy/dx
print(x.grad)         # tensor(6.)

Andrej Karpathy's tiny micrograd library shows how this works in about 100 lines of Python.

Common pitfalls

  • Making hh too small. Computers store numbers with about 16 significant digits. With h=10−15h = 10^{-15}, f(x+h)−f(x)f(x + h) - f(x) is mostly rounding error. A step around 10−510^{-5} is a good default for the central difference in 64-bit floats, and much larger for 32-bit.
  • Forgetting the derivative is local. A slope of −3-3 means the loss falls by about 0.03 for a nudge of 0.01. It says nothing reliable about a nudge of 10. That is why gradient descent takes small steps.
  • Points without a slope. ReLU has a sharp corner at 0, where the derivative isn't defined. Libraries simply use 0 (or 1) there, and in practice it doesn't matter.
  • Zero slope isn't always a minimum. It can be a maximum or a flat ledge. In many dimensions it is often a saddle point.
  • Confusing f′(x)f'(x) with f(x)f(x). A large loss can have a small slope (a wide, flat plateau), and a small loss can have a large slope. Training speed depends on the slope, not the loss.

Watch out In PyTorch, x.grad accumulates: calling .backward() twice adds the two derivatives together. That is why every training loop calls optimizer.zero_grad() before loss.backward(). Forgetting it is one of the most common training bugs.

Where it leads

A bit of history

Isaac Newton (in the 1660s, calling them "fluxions") and Gottfried Wilhelm Leibniz (published 1684) independently invented calculus, and fought bitterly over who came first. We owe the dydx\frac{dy}{dx} notation to Leibniz, and the f′(x)f'(x) notation to Joseph-Louis Lagrange a century later. The rigorous definition using limits came in the 19th century from Augustin-Louis Cauchy and Karl Weierstrass. Computing derivatives automatically by following a program's operations, the basis of PyTorch's autograd, was developed from the 1960s onward. Seppo Linnainmaa's 1970 master's thesis described the "reverse mode" that backpropagation uses.

Try it

  1. Using the power rule, find the derivative of f(x)=3x2−4x+7f(x) = 3x^2 - 4x + 7. Where is its slope zero? Is that a minimum or a maximum?
  2. Use numerical_derivative to estimate the slope of exe^x at x=0,1,2x = 0, 1, 2. Compare with np.exp at the same points. What do you notice?
  3. Try h = 1e-12 and h = 1e-20 in numerical_derivative(f, 3.0). What goes wrong, and why?

Hint for 1: f′(x)=6x−4f'(x) = 6x - 4, zero at x=2/3x = 2/3. The second derivative is 6>06 > 0, so it's a minimum.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. The derivative of the loss with respect to a weight is −3. If you nudge that weight up by 0.01, roughly what happens to the loss?

  2. What is the derivative of f(x) = 5x² + 3x, and what is the slope at x = 1?

  3. You estimate a derivative with a finite difference and set h = 10⁻¹⁵ to be extra accurate. The answer comes out as garbage. Why?

  4. Your loss has slope zero at the current weight. What can you safely conclude?

  5. In PyTorch you call loss.backward() in a loop but never call optimizer.zero_grad(). What goes wrong?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Essence of Calculus

3Blue1Brown · Beginner · Free

Derivatives, the chain rule and integrals, explained visually in short videos.

Course

Differential Calculus

Khan Academy · Beginner · Free

Patient video lessons and practice on limits, derivatives, the derivative rules and the chain rule.

Book

Mathematics for Machine Learning

Deisenroth, Faisal & Ong · 2020 · Intermediate · Free

The linear algebra, calculus, probability and optimisation that ML uses, in one free book.

Book

Dive into Deep Learning

Zhang, Lipton, Li & Smola · Intermediate · Free

An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.

Tool

micrograd

Andrej Karpathy · Intermediate · Free

A tiny autograd engine in about 100 lines. Reading it is the best way to demystify backprop.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/math/derivatives.md