You've written a function that computes the gradient of a model's loss by hand, using the chain rule. It runs without errors and the model trains... slowly, and not very well. Is the gradient right? A single wrong sign or a missing factor of 2 won't crash anything; it will just quietly make the model worse. You need a way to check a derivative without trusting the algebra.
Throughout this module you've used a little helper that nudges the input by a tiny step and measures the rise. That's a numerical derivative, and it deserves a lesson of its own. This lesson compares the forward difference and the more accurate central difference, shows by experiment how to choose the step size (too big is inaccurate, too small hits rounding errors), uses numerical derivatives to check a hand-written gradient (gradient checking), and finds slopes of measured data with np.gradient.
What you need first: the chain rule explained step by step and limits and continuity, especially the section on computers and "very close".
Key terms
- Numerical derivative: an approximate slope computed from function values at nearby points, with no algebra.
- Analytical derivative: an exact formula for the slope, found with the rules, such as 2x for x².
- Forward difference: (f(x + h) − f(x)) ÷ h.
- Central difference: (f(x + h) − f(x − h)) ÷ 2h.
- Gradient checking: comparing a hand-coded gradient with a numerical one to catch bugs.
- Truncation error: the error from using a step h that isn't infinitely small.
- Rounding error: the error from the computer storing numbers to only about 16 digits.
Forward vs central difference
The forward difference measures the slope from x to a point just to its right. The central difference measures it from a point just left of x to a point just right of it:
forward: (f(x + h) − f(x)) ÷ h
central: (f(x + h) − f(x − h)) ÷ 2h
Read the central one as "the rise from x − h to x + h, divided by the run, 2h". Picture a curve bending upwards: a secant to the right tilts too steeply, a secant to the left too gently. The central difference balances the two, so their errors largely cancel.
import numpy as np
import matplotlib.pyplot as plt
def forward_difference(f, x, h):
return (f(x + h) - f(x)) / h
def central_difference(f, x, h):
return (f(x + h) - f(x - h)) / (2 * h)
true_slope = np.exp(1.0) # the derivative of eˣ at x = 1 is e¹
print(f"true slope of eˣ at x = 1: {true_slope:.10f}")
for h in [0.1, 0.01, 0.001]:
fwd = forward_difference(np.exp, 1.0, h)
cen = central_difference(np.exp, 1.0, h)
print(f"h = {h:<6} forward error {abs(fwd - true_slope):.2e} central error {abs(cen - true_slope):.2e}")
true slope of eˣ at x = 1: 2.7182818285
h = 0.1 forward error 1.41e-01 central error 4.53e-03
h = 0.01 forward error 1.36e-02 central error 4.53e-05
h = 0.001 forward error 1.36e-03 central error 4.53e-07
Each time h shrinks by 10, the forward difference's error shrinks by 10, but the central difference's error shrinks by 100. With h = 0.001, the central difference is off by only 0.00000045, about 3,000 times better than the forward difference, for the same two function evaluations.
Choosing the step size
Smaller h should mean a better answer, but limits and continuity showed that very small steps break down on a computer. Measure the error for steps from 10⁻¹ down to 10⁻¹⁵:
steps = np.logspace(-15, -1, 57)
forward_errors = [abs(forward_difference(np.exp, 1.0, h) - true_slope) for h in steps]
central_errors = [abs(central_difference(np.exp, 1.0, h) - true_slope) for h in steps]
fig, ax = plt.subplots(figsize=(8, 5))
ax.loglog(steps, forward_errors, "o-", color="#1f5fbf", markersize=4, label="forward difference")
ax.loglog(steps, central_errors, "o-", color="#c2410c", markersize=4, label="central difference")
ax.set_xlabel("step size h (log scale)")
ax.set_ylabel("error (log scale)")
ax.set_title("Too small or too large a step both give big errors")
ax.text(3e-11, 3e-2, "rounding error\ndominates", ha="center")
ax.text(5e-3, 1e-9, "truncation error\ndominates", ha="center")
ax.legend(loc="lower left")
plt.show()
best_forward = steps[np.argmin(forward_errors)]
best_central = steps[np.argmin(central_errors)]
print(f"forward: best h ≈ {best_forward:.0e}, smallest error {min(forward_errors):.1e}")
print(f"central: best h ≈ {best_central:.0e}, smallest error {min(central_errors):.1e}")
forward: best h ≈ 1e-08, smallest error 6.6e-09
central: best h ≈ 3e-06, smallest error 3.3e-11
Two kinds of error pull in opposite directions. On the right of the chart, the step is too big and the secant isn't a tangent (truncation error). On the left, f(x + h) and f(x) agree in almost all their 16 stored digits, so subtracting them loses most of the accuracy (rounding error). The sweet spot is about 10⁻⁸ for the forward difference and about 10⁻⁵ to 10⁻⁶ for the central difference, which reaches an error of 3 × 10⁻¹¹, around 200 times better.
Gradient checking
Here's a model's loss and a hand-written gradient with a typical bug in it. A linear model with two weights predicts ŷ = w₀ + w₁x, and the loss is the mean squared error:
rng = np.random.default_rng(0)
x = rng.uniform(0, 5, 50)
y = 3 + 2 * x + rng.normal(0, 1, 50)
def loss(w):
predictions = w[0] + w[1] * x
return np.mean((predictions - y) ** 2)
def gradient_buggy(w):
error = w[0] + w[1] * x - y
return np.array([np.mean(error), np.mean(error * x)]) # forgot the 2
def gradient_correct(w):
error = w[0] + w[1] * x - y
return np.array([2 * np.mean(error), 2 * np.mean(error * x)]) # chain rule: 2 × error × input
def numerical_gradient(f, w, h=1e-5):
grad = np.zeros_like(w)
for i in range(len(w)):
step = np.zeros_like(w)
step[i] = h # nudge one weight at a time
grad[i] = (f(w + step) - f(w - step)) / (2 * h)
return grad
def relative_difference(a, b):
return np.linalg.norm(a - b) / (np.linalg.norm(a) + np.linalg.norm(b))
w = np.array([0.5, -1.0])
numeric = numerical_gradient(loss, w)
for name, gradient in [("buggy", gradient_buggy), ("correct", gradient_correct)]:
analytic = gradient(w)
print(f"{name:8} analytic {np.round(analytic, 5)}, numeric {np.round(numeric, 5)}, "
f"relative difference {relative_difference(analytic, numeric):.1e}")
buggy analytic [-10.43573 -34.08277], numeric [-20.87146 -68.16553], relative difference 3.3e-01
correct analytic [-20.87146 -68.16553], numeric [-20.87146 -68.16553], relative difference 5.3e-12
The buggy gradient is exactly half the numerical one in both directions, and the relative difference of 0.33 flags it immediately. The correct gradient agrees to a relative difference of 5 × 10⁻¹², as close as rounding allows. Note that the buggy gradient still points the right way, so a model would still train, just with effectively half the learning rate: the kind of bug that's almost impossible to notice without a check.
The recipe for gradient checking:
- Pick a few random weight values (not all zeros, where some bugs hide).
- Compute the analytical gradient with your code.
- Compute the numerical gradient with central differences, nudging one weight at a time, h ≈ 10⁻⁵.
- Compare with the relative difference: below about 10⁻⁷ is good, above 10⁻⁴ means a bug.
- Turn it off for training: it needs two loss evaluations per weight, far too slow for real models.
Slopes of measured data: np.gradient
Sometimes there's no formula at all, only measurements. A runner's distance is recorded every 2 seconds:
times = np.array([0, 2, 4, 6, 8, 10, 12]) # seconds
distance = np.array([0, 5, 14, 26, 40, 55, 70]) # metres
speed = np.gradient(distance, times)
for t, d, v in zip(times, distance, speed):
print(f"t = {t:2} s: distance {d:2} m, speed ≈ {v:.2f} m/s")
t = 0 s: distance 0 m, speed ≈ 2.50 m/s
t = 2 s: distance 5 m, speed ≈ 3.50 m/s
t = 4 s: distance 14 m, speed ≈ 5.25 m/s
t = 6 s: distance 26 m, speed ≈ 6.50 m/s
t = 8 s: distance 40 m, speed ≈ 7.25 m/s
t = 10 s: distance 55 m, speed ≈ 7.50 m/s
t = 12 s: distance 70 m, speed ≈ 7.50 m/s
np.gradient uses central differences for the inside points ((26 − 5) ÷ 4 = 5.25 m/s at t = 4) and one-sided differences at the two ends. The runner speeds up from about 2.5 m/s to a steady 7.5 m/s. It's the same idea as everything in this module, applied to data instead of a formula.
Where machine learning uses numerical derivatives
- Gradient checking: verifying hand-written backward passes, as above. PyTorch provides
torch.autograd.gradcheckfor the same purpose. - Black-box optimisation: tuning a setting such as a threshold, where the "function" is a whole training run with no formula.
- Data analysis: rates of change of measured signals, such as sales per day or a sensor's reading per second, with
np.gradient.
What machine learning doesn't use for training is numerical derivatives: a model with a million weights would need two million loss evaluations per step. Instead, libraries such as PyTorch, TensorFlow and JAX use automatic differentiation: they record each operation in the forward pass and apply the chain rule backwards, exactly as in the chain rule lesson. That gives exact gradients for all the weights at roughly the cost of one extra pass.
Common mistakes
- Using h = 10⁻¹⁵ "to be accurate". Rounding errors take over; use about 10⁻⁸ for forward and 10⁻⁵ for central differences (for values of everyday size).
- Using forward differences for gradient checks. Central differences are about a million times more accurate for the same number of evaluations per weight.
- Comparing with an absolute difference. A difference of 0.001 is tiny for a gradient of 1,000 and huge for a gradient of 0.001. Use a relative difference.
- Gradient checking near a corner. At ReLU's corner or the edge of a clip, the numerical slope mixes two sides and disagrees for no real bug.
Practice
- Use the central difference with h = 10⁻⁵ to estimate the slope of ln x at x = 4. What should it be?
Show the answer
print(round(central_difference(np.log, 4.0, 1e-5), 8))
0.25
The exact slope is 1/x = 0.25.
- Why is the central difference exact for any parabola, such as f(x) = 3x² + 2x?
Show the answer
f(x + h) − f(x − h) = 3[(x + h)² − (x − h)²] + 2(2h) = 3 × 4xh + 4h = 12xh + 4h. Divide by 2h: 6x + 2, the exact derivative, whatever the size of h. The h² terms cancel, and a parabola has nothing beyond h².
- A colleague's gradient check reports a relative difference of 0.33. What does that suggest?
Show the answer
A real bug: a correct gradient gives a relative difference below about 10⁻⁷. A value of 0.33 means the analytical gradient is off by a constant factor of 2 (if a = b/2, then |a − b| ÷ (|a| + |b|) = 0.5b ÷ 1.5b = 1/3), most likely a missing 2 from a squared term, exactly like the bug above.
- Temperatures recorded hourly were 12, 13, 15, 18, 20 °C. Use
np.gradientto estimate the rate of warming at each hour.
Show the answer
print(np.gradient(np.array([12, 13, 15, 18, 20]), 1.0))
[1. 1.5 2.5 2.5 2. ]
At the ends it uses one-sided differences; in the middle, central differences. The warming was fastest, 2.5 °C per hour, around the third and fourth readings.
Interview questions
What is gradient checking and when would you use it?
Gradient checking compares an analytically computed gradient with a numerical estimate from central differences, nudging one parameter at a time. You use it when implementing a custom layer, loss or backward pass, on a few random parameter values with a small model, and turn it off for training because it costs two loss evaluations per parameter.
Why is the central difference more accurate than the forward difference?
By Taylor expansion, the forward difference has error proportional to h (the curvature term doesn't cancel), while in the central difference the h² terms cancel, leaving error proportional to h². With h = 10⁻⁵ that's an error around 10⁻¹⁰ instead of 10⁻⁵.
Why don't deep learning frameworks use numerical differentiation?
It costs two forward passes per parameter, which is impossible for millions of parameters, and it's only approximate. Reverse-mode automatic differentiation (backpropagation) computes exact gradients for all parameters at roughly the cost of one forward and one backward pass.
Key takeaways
- A numerical derivative estimates the slope from nearby function values, with no algebra.
- The central difference, (f(x + h) − f(x − h)) ÷ 2h, is far more accurate than the forward difference.
- The step size is a balance: too large gives truncation error, too small gives rounding error. Use h ≈ 10⁻⁵ for central differences.
- Gradient checking compares your hand-written gradient with a numerical one; relative differences above 10⁻⁴ mean a bug.
- np.gradient estimates slopes from measured data; training itself uses automatic differentiation.
Frequently asked questions
Is np.gradient the same as a derivative?
It's an estimate of the derivative from sampled values: central differences inside the array and one-sided differences at the ends. It's as good as your sampling: points far apart or noisy measurements give rough slopes.
What's the difference between numerical and automatic differentiation?
Numerical differentiation nudges inputs and measures the change: approximate, and slow for many inputs. Automatic differentiation applies the exact derivative rules to every operation the code performs, using the chain rule: exact (up to rounding) and fast. Symbolic differentiation, a third kind, manipulates formulas like a person would.
Can I compute second derivatives numerically?
Yes: (f(x + h) − 2f(x) + f(x − h)) ÷ h² estimates the second derivative, the rate of change of the slope. Rounding errors are worse, so h around 10⁻⁴ works better.
What to learn next
- Use the derivative to find the best value of a function in maxima and minima with derivatives, the first lesson of the optimisation module.
- See gradients in action in gradient descent explained.
- Review why tiny steps fail in limits and continuity explained.