Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 15 min · revision 2

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

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.

Python · model.py
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 slope

03. 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.

Python · check.py
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)))
Terminal
python check.py
Expected output
analytic: [-0.200209  0.050854  0.008781]
numeric:  [-0.200209  0.050854  0.008781]
every relative error below 1e-7: True

The 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.

Python · step_size.py
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}")
Expected output
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-10

Each 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.

Python · tiny_h.py
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}")
Illustrative output: the digits come from rounding and can differ on your machine
h = 1e-06: central error 8.7e-11
h = 1e-09: central error 5.8e-08
h = 1e-12: central error 1.9e-05

Below 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.

Python · find_bug.py
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 "")
Expected output
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 this

The 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.

Python · scipy_check.py
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}")
Expected output
difference norm below 1e-6: True
with a 1% error: 0.0021

A 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

Practice check · 3 questions

Reading a gradient check

Use what you measured in this worked example.

Q1. A float64 gradient check on a smooth loss gives relative errors near 10⁻⁹ for every weight, and 0.5 for the bias. What is the most likely explanation?
Q2. Your loss contains an absolute-value term |w₂|. The check passes everywhere except at one point where w₂ = 0.000003, with h = 0.00001. What should you conclude first?
Q3. Why is it a poor idea to run the gradient check of this lesson at w = [0, 0, 0]?
Practice only: not graded, not saved, not evidence.

08. Apply it

Before the lab, check the gradient you wrote in the previous lesson.

  1. Copy numerical_grad and relative_error into your project and run them on your mean-squared-error gradient for load_diabetes, at a random weight vector from np.random.default_rng(0).
  2. Plant a bug on purpose, for example by forgetting to divide by n, and confirm that the checker flags it.
  3. 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.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check