Rates of change: slope, derivative and the gradient
Before this lesson: lesson 04 (slope of a line, and ), lesson 06 (vectors, the dot product and ) and lesson 03 (NumPy). Time: about 65 minutes, plus the notebook. This is the hardest lesson of the track; take a break after section 2.
Why this matters #
- Training is gradient descent. Every neural network, from a logistic regression to a large language model, is trained by moving the parameters against the gradient of the loss: . SGD, momentum and Adam are all variants of this step.
- Backpropagation computes a gradient. It is the chain rule, applied to millions of parameters at once.
PyTorch's
loss.backward()fillsparam.gradwith for every parameter. - The learning rate is the most important hyperparameter. Too small and training is slow; too large and the loss explodes. Section 3 shows exactly where the boundary is for the simplest loss.
- Gradients answer "what if" questions. The gradient of a model output with respect to the input pixels is a saliency map. In physics, the force on an atom is minus the gradient of the energy; ML force fields for molecules are trained on such gradients.
This lesson is a first look. The Calculus track proves the rules, and the Optimization track studies gradient descent in depth.
1. Predict first #
2. The picture #
From a secant to a tangent #
The average rate of change of between and is the change in output divided by the change in input:
In the picture it is the slope of the secant line, the straight line through the two points and of the graph. For from to ():
Now let the second point slide toward the first: gets smaller. The secant line turns, and it comes closer and closer to one line that just touches the curve at : the tangent line. The slope of the tangent line is the derivative .
Press Shrink h and watch the orange secant turn into the aqua tangent at the blue point. The panel computes the secant slope; its difference to the tangent slope shrinks with . Try a negative : the secant now uses a point on the left, and the slopes approach the same value. At the quotient is , which is not defined: the derivative is a limit, not a division by zero.
For at the secant slopes are (we show this in section 3): for , for , for . They approach .
What is the average rate of change of from to ?
. The value 8 is the change without the division by . The values 2 and 6 are the slopes of the tangent at the two end points (, ); the secant slope lies between them.
Zoom in: the curve looks like a line #
Here is a second way to see the derivative. Zoom in on a smooth curve around a point. The more you zoom, the straighter the curve looks. In the end you cannot tell it from its tangent line. So near :
This is the local linear approximation (or linearization). Example: estimate . Take , , . We know , and the slope of at 4 is (from the rules in section 3). So
The true value is ; the error is .
Move the zoom slider to the right. The window around gets up to 200 times narrower, and the blue curve and the aqua tangent line become one line. The magenta segment is the error of the linear approximation at the edge of the window. On the right, that error is plotted against on log–log axes. It follows the dashed line of slope 2: ten times smaller gives about 100 times smaller error.
The error is not just small; it is small compared with . For a smooth it shrinks like . This is the reason why the tangent is the best line through the point: any other slope leaves an error of about , which is much larger than for small .
Many inputs: slices of a surface #
A function of two inputs, , has a graph that is a surface: the height above the point is . How steep is it? That depends on the direction. Start with the two simplest directions.
- Hold fixed and change only . You walk on a slice of the surface. Its slope is the partial derivative .
- Hold fixed and change only . The slope of this slice is .
For : holding fixed, is a constant, so . Holding fixed, is a constant, so .
Move the sliders and , and drag the figure to rotate it. The orange curve is the slice "hold "; the slope of its dashed tangent is . The aqua curve is the slice "hold ", with slope . The two slopes together form the gradient, the blue arrow on the floor. It lives in the input plane , not on the surface.
The gradient on a contour map #
A surface is hard to draw. A contour map shows the same function in 2-D: each contour line (or level set) connects the points with the same value . The height lines of a hiking map are contour lines.
The gradient is the vector of the partial derivatives:
It is an arrow in the input plane. On the map, it has three properties that you can test in the next figure:
- it points in the direction in which grows fastest (steepest ascent);
- its length is that fastest rate of growth;
- it crosses the contour line at a right angle.
Drag the orange tip of the unit direction around the dashed circle. The slope of in that direction is ; the chart plots it against the angle of . Find the largest value: it is reached when points along the blue gradient, and it equals (the blue line in the chart). Press u along the contour: the slope is 0, and lies on the dashed tangent of the aqua contour line. Drag the black point to test other places.
The chart is a cosine curve. This is lesson 06 again: , and is largest at .
Walking downhill: gradient descent #
To make small, go against the gradient. Gradient descent repeats one step:
where the learning rate sets the step size. For (one input) the gradient is , so the step is . Each step multiplies by the same factor . Everything depends on the size of this factor.
Choose a preset under Try and watch the orange iterates on the blue parabola. The panel shows the factor . With zig-zag the factor is negative: the point jumps from side to side but still gets closer. At it is : the point flips between forever. Above 1 it diverges. Switch to 2-D: on the aqua contours of , the steep direction starts to zig-zag first. The chart shows at each step on a log scale.
Gradient descent on starts at with . What happens?
The factor is , so , , , and grows without limit. A convex bowl does not protect you from a too large learning rate. Jumping between happens at (factor ); one step to the minimum happens at (factor 0).
3. Definitions and main results #
The derivative #
Definition. The derivative of at is the limit of the secant slopes:
If this limit exists (the same value for from both sides), is differentiable at . Other notations: , ; physicists write for a derivative in time. "" means: the value that the quotient approaches as gets closer and closer to 0, without being 0. The function that maps each to is the derivative function.
Example: . Every algebra step:
- .
- .
- Divide by (allowed, since ): .
- Let : . So .
At : the secant slope is and the derivative is , as in the first figure.
Not every function has a derivative everywhere. at : the secant slope is , which is for and for . The two sides disagree, so there is no limit. The graph has a corner. The ReLU activation has the same corner at 0; deep-learning libraries use the slope 0 there.
Local linear approximation #
Result. If is differentiable at , then
Why. Divide by : . The first term tends to by definition, so the difference tends to 0.
For the remainder is exact and easy: . In general, if has a second derivative, ; this is the start of the Taylor series (Calculus lesson 3).
Rules for derivatives #
These rules follow from the definition (the Calculus track proves them). is a constant.
| function | derivative | example |
|---|---|---|
| (power rule) | ; | |
| the slope of equals its height | ||
| () | at the slope is 1 | |
| (chain rule) |
Why is its own derivative (the claim of lesson 04). . The second factor is the secant slope of at 0, and it tends to 1: . So the derivative is . That the slope at 0 is exactly 1 is what makes special.
The chain rule says: if changes by a factor , and changes by a factor at , the two factors multiply. Example: the sigmoid of lesson 05. Outer function with ; inner function with . So
because . At : ; at : . The notebook checks the formula numerically. In a network, backpropagation applies the chain rule once per layer.
What the derivative tells you #
- If , is increasing near ; if , it is decreasing.
- Theorem. If is differentiable and has a minimum or a maximum at an inner point of an interval, then .
Proof for a minimum
- At a minimum, for all small .
- For the secant slope is (non-negative divided by positive). So its limit is .
- For the same quotient is (non-negative divided by negative). So .
- Both together: .
The converse is false. has , but 0 is neither a minimum nor a maximum: on the left and on the right. A point with is a critical point (or stationary point); it may be a minimum, a maximum or neither.
Example (a log-likelihood, as in lesson 04). Three heads and one tail have the log-likelihood for . By the rules and the chain rule, . Set it to 0: , so , the fraction of heads. Since for and for , this is a maximum.
at some point . What can you conclude?
is necessary at a smooth inner minimum, but not sufficient. For , and grows on both sides of 0 in the same direction, so 0 is neither. You need more information, for example the sign of on both sides.
Numerical derivatives #
A computer can estimate a derivative without any rules, from two function values:
For at with : forward , central . The true value is 6. The truncation error (the error from ) is about for the forward difference and for the central difference. So the central difference is much more accurate for the same .
But cannot be tiny. A float64 number has about 16 correct significant digits, and floats are not exact (lesson 03). For a very small , and agree in almost all digits, and the subtraction loses them: this round-off error grows like . The total error is U-shaped in . For at :
| forward error | central error | |
|---|---|---|
Good default steps: for the forward difference and for the central difference (for values of and near 1).
Where the error terms come from
If has three derivatives, the Taylor expansion gives
- Forward: , error of order .
- Central: subtract the two expansions; the even terms cancel: , error of order .
Each function value has a relative round-off error of about (machine epsilon). Dividing by turns it into an error of about . Balancing against gives the best forward step ; balancing against gives for the central difference. Calculus lesson 7 covers this in detail.
Partial derivatives and the gradient #
Definition. For , the partial derivative with respect to is the derivative in while all other inputs are held fixed:
where is the unit vector with a 1 in place and 0 elsewhere. In practice: treat every other variable as a constant and use the one-variable rules. The gradient is the vector of all partial derivatives:
It has the same size as the input ; it lives in the input space. The symbol is read "nabla" or "del".
Example. . Holding fixed, is a constant: . Holding fixed, is a constant: . So and .
What is the gradient of at ?
Hold fixed: . Hold fixed: . The answer forgets the factor in the first partial derivative. The gradient is a vector with one entry per input, not one number; is the value of the function.
The direction of steepest ascent #
The partial derivatives are slopes along the axes. The slope in any other direction is a combination of them.
Definition. For a unit vector (), the directional derivative of at in the direction is
Theorem. If is differentiable at (for example, if all partial derivatives exist and are continuous near ), then
Why this is true. The linear approximation works in many variables too: . In 2-D, a step changes by about (the -part of the step) plus (the -part). Put and divide by . (The Calculus track gives the full proof.)
Theorem (steepest ascent). Let . Among all unit vectors :
- is largest for , and the largest value is ;
- is smallest for (steepest descent), with value ;
- exactly for the that are orthogonal to .
Proof. Let be the angle between and . By the geometric formula of the dot product (lesson 06):
- , since .
- takes all values from to . It is 1 only at ( points along ), only at , and 0 only at .
- Multiply by the positive number . This gives claims 1, 2 and 3.
The gradient is perpendicular to the contour line. Along the contour line through , does not change. So for the direction of the contour line (its tangent), . By claim 3, is orthogonal to . (This is a sketch; it needs , so that the contour is a smooth curve near .)
Gradient descent and the learning rate #
Gradient descent starts at and repeats
Why a small step decreases . By the linear approximation with :
If , the decrease is positive. The approximation is only good for small steps, so a too large can increase .
Exact analysis for . The step is , so
With and , for :
| learning rate | factor | behaviour | from |
|---|---|---|---|
| converges, same sign each step | : | ||
| exact minimum after one step | |||
| converges with a zig-zag | : | ||
| flips between and | |||
| diverges | : |
So gradient descent on converges exactly when , that is, . The bound depends on the curvature: for the factor is , and the condition is . A steeper bowl needs a smaller learning rate. For (the 2-D figure) the factors are for and for ; the steep direction limits to below .
You run gradient descent on with . What do you see?
, so and . Both factors have size below 1, so both coordinates converge. Only the factor is negative, so only changes sign each step. The steep direction (, with the larger second derivative) is the first to zig-zag.
Answers to section 1. (1) The average speed is km/h: the slope of the secant over two hours. The speedometer shows the instantaneous speed, the derivative at 2 pm. The car can be faster at some times and slower at others. (2) Height grows most along the gradient of the height function (steepest ascent), at the rate . It does not change (to first order) along the contour line, at a right angle to the gradient. (3) With : , so it converges slowly to 0 ( after 20 steps). With : , it diverges.
4. Worked example #
Take , the bowl of the figures, at the point .
(a) Value. .
(b) Partial derivatives. Hold fixed: . Hold fixed: .
(c) Gradient and its length.
(d) Slopes in three directions.
- Along the -axis, : . This is .
- Along : . This direction is orthogonal to , so it is the direction of the contour line through .
- Along the gradient, : . This is , the largest possible slope.
(e) Linear approximation. Estimate , a step :
The true value is . The step goes along the contour line, so the linear term is 0; the change of comes from the curvature (the part).
(f) One gradient descent step with :
The value fell from to . The linear approximation predicted . The true value is a little higher: the bowl curves up, and the exact correction here is , so . ✓
5. In code #
NumPy checks the worked example. The numerical gradient uses central differences, one coordinate at a time.
import numpy as np
f = lambda v: v[0]**2 + 2 * v[1]**2
grad = lambda v: np.array([2 * v[0], 4 * v[1]])
def num_grad(f, v, h=1e-5):
e = np.eye(len(v)) # rows are the unit vectors e_j
return np.array([(f(v + h * e[j]) - f(v - h * e[j])) / (2 * h) for j in range(len(v))])
p = np.array([1.0, 0.5])
g = grad(p)
print(f(p), g, np.linalg.norm(g)) # 1.5 [2. 2.] 2.8284271247461903
print(num_grad(f, p)) # [2. 2.]
for u in [np.array([1., 0.]), np.array([1., -1.]) / np.sqrt(2), g / np.linalg.norm(g)]:
print(g @ u) # 2.0, then 0.0, then 2.82842712474619
d = np.array([0.1, -0.1])
print(f(p) + g @ d, f(p + d)) # 1.5 1.5300000000000002
q = p - 0.1 * g # one gradient descent step
print(q, f(q)) # [0.8 0.3] 0.8200000000000001
s = lambda x: x**2 # forward and central difference at 3
print((s(3.1) - s(3)) / 0.1, (s(3.1) - s(2.9)) / 0.2) # 6.100000000000012 6.000000000000005
sig = lambda z: 1 / (1 + np.exp(-z)) # sigma' = sigma (1 - sigma) at z = 2
print(sig(2) * (1 - sig(2)), (sig(2 + 1e-5) - sig(2 - 1e-5)) / 2e-5) # 0.10499... 0.10499...
The last digits such as ...0012 are round-off (lesson 03). Compare floats with np.isclose.
6. Where it shows up #
- Training neural networks. Every optimizer (SGD, momentum, Adam, AdamW) uses , the gradient of the loss with respect to all parameters. Stochastic gradient descent estimates it on a small batch of data. See Optimization lesson 1.
- Backpropagation and automatic differentiation. PyTorch and JAX apply the chain rule through the computation, and get the full gradient for the cost of a few function evaluations. Finite differences would need evaluations for parameters, which is impossible for .
- Gradient checking. When you write a new layer by hand, you compare its gradient with central differences on a few random inputs, as in the notebook. A relative error near is fine; means a bug.
- Learning-rate choice. Loss curves that explode or oscillate are the 2-D figure on a large scale: the learning rate is above the limit of the steepest direction. Warmup and learning-rate schedules handle this.
- Saliency and adversarial examples. The gradient of a class score with respect to the input pixels shows which pixels matter. The fast gradient sign method moves each pixel a tiny step along the sign of this gradient and can change the prediction.
- ML for science. In molecular dynamics the force on each atom is , minus the gradient of the potential energy. Neural network potentials learn and get the forces by automatic differentiation. Sensitivity analysis of a simulation asks for the partial derivatives of an output with respect to its parameters.
7. Common mistakes #
- Dividing by . The derivative is a limit as , not the quotient at , which is . Simplify first (as in ), then let .
- Thinking that means a minimum. It can be a maximum or neither ( at 0). In many dimensions, also happens at saddle points, which are common in neural network losses.
- Drawing the gradient on the surface. is a vector in the input space, with one entry per input. It points in the direction to move , not up the graph.
- Going along to minimize. The gradient points uphill. To make a loss smaller, step along .
- Choosing a tiny for numerical derivatives. gives a large round-off error. Use about with central differences.
- Thinking that a convex bowl is safe with any learning rate. Even on , diverges. The limit is set by the steepest direction, not by the average one.
- Mixing up partial derivatives. For of , is a constant factor: the answer is , not .
8. Check yourself #
- Compute the secant slope of between and , and the derivative at .
Answer
Secant: . Derivative: , so . The secant slope is larger because the curve gets steeper between 1 and 2. - Use the linear approximation of at 0 to estimate . How large is the error, roughly?
Answer
. The error is about ; the true value is , so the error is . - Lesson 04 claimed that is smallest at . Check it with the derivative.
Answer
. Set it to 0: , so , so and . For the derivative is negative and for positive, so it is a minimum, with value . - Find the gradient of at . What is the largest slope of at that point, and in which direction?
Answer
, . So . The largest slope is , in the direction . - Give a unit direction in which does not change (to first order) at .
Answer
. A direction orthogonal to it is (dot product ). As a unit vector: , or the opposite . - Gradient descent on . Which learning rates converge?
Answer
, so . Convergence needs , that is, . (With the rule for : .)
Define the derivative as a limit.
, the limit of the secant slopes.
What is the local linear approximation of near ?
; the tangent line at . For smooth the error is of order .
Estimate with a linear approximation.
(true ).
What are the derivatives of , and ?
, , and (for ).
What does the partial derivative of measure?
The slope of when changes and is held fixed: the slope of the slice of the surface at constant .
What is the gradient of ?
The vector of partial derivatives , a vector in the input space.
Why is the gradient the direction of steepest ascent, and what is the steepest slope?
For a unit vector , the slope is , largest at . The steepest slope is .
How is the gradient related to the contour line through a point?
It is perpendicular to it: along the contour does not change, so for the contour direction .
Write the gradient descent update. For , which learning rates converge?
. For it is , which converges for .
Why is the central difference better than the forward difference?
Its error is of order instead of , because the even terms of the Taylor expansion cancel.
9. Interview angle #
- "Why do we step along the negative gradient?" — For a small step , . Among steps of a fixed length, is most negative when points along (Cauchy–Schwarz, or ). So gives the fastest first-order decrease.
- "What happens if the learning rate is too large?" — The steps overshoot. On the update multiplies
by ; for this has size above 1 and the iterates diverge. In practice the loss oscillates
or becomes
nan. - "How do you check that your backward pass is correct?" — Gradient checking: compare the analytic gradient with central differences , , in float64, using the relative error.
- "Why not train with finite differences?" — They need function evaluations per gradient, one pair per parameter, and they are less accurate. Reverse-mode automatic differentiation (backpropagation) gets all partial derivatives for a small constant times the cost of one evaluation.
- "The gradient is zero. Are you at a minimum?" — Not necessarily: it can be a maximum or a saddle point. In high dimensions, saddle points are much more common than poor local minima (Dauphin et al., 2014).
10. Practice #
The notebook for this lesson runs in Colab or in your browser. Five exercises, each with a check cell and a folded solution:
- Write the forward and central differences, and plot their errors against for at 1 (the U-shaped curves).
- Check numerically on 201 points.
- Write a numerical gradient for any and compare it with analytic gradients.
- Run gradient descent on , plot the path on the contours, and find the largest stable learning rate.
- Show that the error of the linear approximation of at 0, divided by , tends to .
11. Watch and read #
- Deisenroth, Faisal and Ong, Mathematics for Machine Learning, free PDF: §5.1 (differentiation of univariate functions) and §5.2 (partial differentiation and gradients).
- OpenStax, Calculus Volume 1, free: chapter 3 (derivatives), sections 3.1–3.3 and 3.6 (the chain rule).
- Next steps: Calculus lesson 1 (derivatives in one variable, with proofs) and Optimization lesson 1 (loss surfaces and gradient descent).
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.