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
- Builds on
- 0 concepts →
- Quiz
- 5 questions ↓
Read first
Nothing — start here.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 , 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 . 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 and ask for its slope at . We can't take the rise over the run of a single point, so we use two points close together: and , where is a small step. The straight line through them is called a chord. Its slope is rise over run:
Work it out for shrinking steps:
| Step | Rise | Slope = rise / | |
|---|---|---|---|
| 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 at .
The formal definition says exactly this. The derivative of at is the value the chord slope approaches as the step shrinks towards zero:
"lim" means "the limit as goes to 0", the value approached but never quite reached. Two notations are common. ("f prime of x") is compact. ("d f by d x") reminds you it is a tiny change in divided by a tiny change in . They mean the same thing.
Doing it with algebra
For we can do the limit exactly:
As shrinks to 0, this becomes . So the derivative of is : at the slope is 2, at it is 6, at it is . 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 | Derivative | Example |
|---|---|---|
| a constant | flat line, no slope | |
| (power rule) | , | |
| the exponential is its own slope | ||
| (natural log) | used in every log-likelihood loss | |
| sigmoid | at 0: | |
| ReLU | 0 if , 1 if | 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 , 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 increases. Downhill is to the right.
- Positive slope: the function goes up as 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 . Its derivative, by the rules above, is . At the slope is , so increase . At it is , so decrease . At it is 0: that is the minimum, where the loss is 1.
This gives the core rule of training: move the weight against the sign of the slope. Subtract a small multiple of the derivative: , where is the learning rate. That is Gradient Descent in one line.
For simple functions you can also find the minimum directly by solving . Here gives . 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 . It tells you how fast the slope itself is changing, which is the curvature. For , : 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 . This is a finite difference. A more accurate version uses a chord centred on :
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 too small. Computers store numbers with about 16 significant digits. With , is mostly rounding error. A step around 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 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 with . 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.gradaccumulates: calling.backward()twice adds the two derivatives together. That is why every training loop callsoptimizer.zero_grad()beforeloss.backward(). Forgetting it is one of the most common training bugs.
Where it leads
- The Chain Rule: how to differentiate functions built from other functions, the key to backpropagation.
- Partial Derivatives and Gradients: derivatives when a function has many inputs, such as a loss that depends on millions of weights. The collection of slopes is the gradient.
- Gradient Descent: the algorithm that uses those slopes to train models.
- Activation Functions and Vanishing and Exploding Gradients: why the derivatives of the functions inside a network matter.
- Maximum Likelihood Estimation: setting a derivative to zero is how classic statistics finds the best parameters.
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 notation to Leibniz, and the 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
- Using the power rule, find the derivative of . Where is its slope zero? Is that a minimum or a maximum?
- Use
numerical_derivativeto estimate the slope of at . Compare withnp.expat the same points. What do you notice?- Try
h = 1e-12andh = 1e-20innumerical_derivative(f, 3.0). What goes wrong, and why?Hint for 1: , zero at . The second derivative is , so it's a minimum.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Essence of Calculus
Derivatives, the chain rule and integrals, explained visually in short videos.
Differential Calculus
Patient video lessons and practice on limits, derivatives, the derivative rules and the chain rule.
Mathematics for Machine Learning
The linear algebra, calculus, probability and optimisation that ML uses, in one free book.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
micrograd
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