Worked Example: Checking a Gradient Numerically
Derive the gradient of a regularised logistic loss, check it against central differences with a relative-error test, see how the step size h trades truncation error against rounding error, and catch a planted chain-rule bug.
Contentsand lesson path
On this page
- The problem
- Step 1: The loss and its analytic gradient
- Step 2: A central-difference checker
- Step 3: Choosing the step size h
- Step 4: Catch a planted bug
- Step 5: The same check with SciPy
- Check your understanding
- Apply it
- Review prompt
Lessons of Linear Algebra & Calculus for ML
- Data as Arrays: Vectors, Matrices and Shapes Concept · 20 min
- Similarity and Structure: Distances, Eigenvectors and the SVD Concept · 30 min
- From Slopes to Gradients: Derivatives, the Chain Rule and Jacobians Concept · 25 min
- Worked Example: Checking a Gradient Numerically Worked example · 15 min
- Lab: Fit a Linear Model with Hand-Written Gradient Descent Lab · 30 min
- Check: Shapes, Gradients and Step Sizes Knowledge check · 10 questions
What you will learn
- Compute partial derivatives of a composed function with the chain rule and verify them with a numerical gradient check.
01. The problem
You have written the gradient of a loss by hand, as in the previous lesson. Before you train with it, you want evidence that it is right. A wrong gradient rarely crashes anything: training still runs, the loss may even fall for a while, and you only notice much later that the model is worse than it should be.
A gradient check compares your analytic gradient (the formula) with a numerical estimate made by nudging each parameter and measuring how the loss changes. If the two agree to many digits, the formula is very likely right. In this worked example you will check the gradient of logistic regression with an L2 penalty, an extra term (λ/2)·‖w‖² that discourages large weights. You will build the checker yourself, choose the step size h with care, and use it to catch a realistic bug.
Create a folder with the six small files below and run them with Python 3.12, NumPy 2.5 and SciPy 1.18 (python -m pip install numpy scipy).
02. Step 1: The loss and its analytic gradient
The loss is the mean log-loss of logistic regression plus the penalty: L(w) = mean log-loss + (λ/2)·Σ w_j². From the previous lesson, the gradient of the mean log-loss is Xᵀ(p − y) / n. The penalty is a sum of squares, and the derivative of (λ/2)·w_j² is λ·w_j: the power rule brings down a 2 that cancels the 1/2. So the full gradient is Xᵀ(p − y) / n + λ·w. The data are 20 random examples with 3 features and labels generated from a known rule plus noise, so the run is repeatable.
import numpy as np
rng = np.random.default_rng(3)
X = rng.normal(size=(20, 3)) # 20 examples, 3 features
y = (X @ [1.0, -2.0, 0.5] + rng.normal(size=20) > 0).astype(float)
LAM = 0.1 # strength of the L2 penalty
def loss(w):
p = 1 / (1 + np.exp(-(X @ w)))
log_loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
return log_loss + LAM / 2 * np.sum(w ** 2)
def grad(w):
p = 1 / (1 + np.exp(-(X @ w)))
return X.T @ (p - y) / len(y) + LAM * w # chain rule result + penalty slope03. Step 2: A central-difference checker
The checker nudges one parameter at a time. Instead of the forward difference (f(w + h) − f(w)) / h, it uses the central difference (f(w + h) − f(w − h)) / 2h, which looks at the same distance on both sides of w. When you expand both sides as a Taylor series, the terms that make the forward difference wrong by about h cancel, and what is left is an error proportional to h². Shrinking h by a factor of 10 then cuts the error by about 100 instead of 10. The price is two loss evaluations per parameter instead of one.
To compare the two gradients, use the relative error |a − n| / max(|a|, |n|) for each parameter. An absolute difference of 10⁻⁶ means nothing on its own: it is tiny for a gradient entry of 50 and huge for one of 10⁻⁶. The 1e-12 floor only avoids dividing by zero when both values are zero.
import numpy as np
from model import grad, loss
def numerical_grad(f, w, h=1e-5):
g = np.zeros_like(w)
for i in range(len(w)):
step = np.zeros_like(w)
step[i] = h
g[i] = (f(w + step) - f(w - step)) / (2 * h) # central difference
return g
def relative_error(a, b):
return np.abs(a - b) / np.maximum(1e-12, np.maximum(np.abs(a), np.abs(b)))
if __name__ == "__main__":
w = np.array([0.3, -0.7, 0.2])
analytic = grad(w)
numeric = numerical_grad(loss, w)
print("analytic:", analytic.round(6))
print("numeric: ", numeric.round(6))
errors = relative_error(analytic, numeric)
print("every relative error below 1e-7:", bool(np.all(errors < 1e-7)))python check.pyanalytic: [-0.200209 0.050854 0.008781]
numeric: [-0.200209 0.050854 0.008781]
every relative error below 1e-7: TrueThe two gradients agree to six decimals and every relative error is below 10⁻⁷. As a rough guide for float64 code on a smooth loss: below about 10⁻⁷ is a pass, around 10⁻⁴ deserves a closer look, and 10⁻² or more almost always means a bug. These thresholds are rules of thumb, not laws; a loss with kinks, such as a ReLU or an absolute value, can give larger errors without any bug (see the callout below).
04. Step 3: Choosing the step size h
It is tempting to think that a smaller h is always more accurate. Measure it. The script compares forward and central differences for the first weight across four step sizes.
import numpy as np
from model import grad, loss
w = np.array([0.3, -0.7, 0.2])
exact = grad(w)[0]
e0 = np.array([1.0, 0.0, 0.0])
print("h forward error central error")
for h in [1e-1, 1e-2, 1e-3, 1e-4]:
forward = (loss(w + h * e0) - loss(w)) / h
central = (loss(w + h * e0) - loss(w - h * e0)) / (2 * h)
print(f"{h:<8.0e} {abs(forward - exact):<14.1e} {abs(central - exact):.1e}")h forward error central error
1e-01 2.4e-02 6.5e-04
1e-02 2.5e-03 6.5e-06
1e-03 2.5e-04 6.5e-08
1e-04 2.5e-05 6.5e-10Each time h shrinks by 10, the forward error shrinks by 10 and the central error by 100: the first is proportional to h, the second to h². This error, which comes from the formula itself, is called truncation error. Now go much smaller.
import numpy as np
from model import grad, loss
w = np.array([0.3, -0.7, 0.2])
exact = grad(w)[0]
e0 = np.array([1.0, 0.0, 0.0])
for h in [1e-6, 1e-9, 1e-12]: # rounding error takes over as h shrinks
central = (loss(w + h * e0) - loss(w - h * e0)) / (2 * h)
print(f"h = {h:.0e}: central error {abs(central - exact):.1e}")h = 1e-06: central error 8.7e-11
h = 1e-09: central error 5.8e-08
h = 1e-12: central error 1.9e-05Below about h = 10⁻⁶ the error grows again. A float64 number carries about 16 significant digits. The loss here is about 0.6, so each evaluation has a rounding error near 10⁻¹⁶. When h is tiny, f(w + h) and f(w − h) are almost equal, and subtracting them cancels most of their digits; dividing by a tiny 2h then magnifies the rounding error that is left. This is rounding error, and it grows as h shrinks. The best h balances the two errors. For central differences in float64, values between 10⁻⁴ and 10⁻⁶ work well for most losses whose parameters are of order 1. In float32, which has only about 7 digits, gradient checks are unreliable; run them in float64.
05. Step 4: Catch a planted bug
A very common hand-derivation mistake is to forget what the power rule does to a constant. Suppose the penalty slope is written as (λ/2)·w instead of λ·w. The loss falls during training either way, so nothing looks wrong. The checker finds it at once.
import numpy as np
from check import numerical_grad, relative_error
from model import LAM, X, loss, y
def buggy_grad(w):
p = 1 / (1 + np.exp(-(X @ w)))
return X.T @ (p - y) / len(y) + LAM / 2 * w # bug: kept the 1/2 of the penalty
w = np.array([0.3, -0.7, 0.2])
errors = relative_error(buggy_grad(w), numerical_grad(loss, w))
for i, e in enumerate(errors):
print(f"w[{i}] relative error {e:.1e}", "<- check this" if e > 1e-5 else "")w[0] relative error 7.0e-02 <- check this
w[1] relative error 4.1e-01 <- check this
w[2] relative error 1.1e+00 <- check thisThe errors are between hundreds of thousands and ten million times above the passing level. Notice that they differ between parameters: the bug matters most where the penalty part λ·w is large compared with the data part. A useful debugging trick follows from this. Check each term of the loss separately, for example with λ = 0 and then with only the penalty, and the faulty term reveals itself.
06. Step 5: The same check with SciPy
SciPy ships a ready-made checker, scipy.optimize.check_grad. It returns the 2-norm (the L2 length) of the difference between your gradient and a forward-difference estimate. Because it reports one absolute number for the whole vector, compare it with the size of the gradient itself, here about 0.2.
import numpy as np
from scipy.optimize import check_grad
from model import grad, loss
w = np.array([0.3, -0.7, 0.2])
gap = check_grad(loss, grad, w)
print("difference norm below 1e-6:", gap < 1e-6)
gap_bad = check_grad(loss, lambda v: grad(v) * 1.01, w) # a gradient 1% too large
print(f"with a 1% error: {gap_bad:.4f}")difference norm below 1e-6: True
with a 1% error: 0.0021A gradient that is only 1% too large gives a gap of 0.0021, about 1% of the gradient length of 0.21, while the correct gradient stays below 10⁻⁶. Your own checker is still worth having: it reports each parameter separately, which tells you where to look.
07. Check your understanding
08. Apply it
Before the lab, check the gradient you wrote in the previous lesson.
- Copy
numerical_gradandrelative_errorinto your project and run them on your mean-squared-error gradient forload_diabetes, at a random weight vector fromnp.random.default_rng(0). - Plant a bug on purpose, for example by forgetting to divide by n, and confirm that the checker flags it.
- Turn the check into a small test that asserts every relative error is below 10⁻⁷, so it runs again whenever you change the gradient.
09. Review prompt
Without looking back, explain: why the central difference is more accurate than the forward difference and what it costs; why the error grows again when h becomes very small; why gradient checks compare relative rather than absolute errors; and two situations in which a correct gradient can fail the check.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.