Gradient and shape checks
Quick answer
A gradient check compares an analytical derivative to a finite-difference approximation. Shape checks and numerical tolerance help catch silent broadcasting errors and wrong chain-rule factors before training a larger model. Static examples verified locally with Python 3.13.5 and NumPy 2.3.5 where imported. ByteMind execution is unverified.
Central difference
def f(x): return x*x+3*xx=2.; h=1e-5g=(f(x+h)-f(x-h))/(2*h)print(round(g,6),abs(g-7)<1e-8)Expected output: 7.0 True. The analytic derivative 2x+3 agrees within tolerance.
How it works
For parameter theta_i, approximate derivative with (L(theta+he_i)-L(theta-he_i))/(2h). Perturb exactly one scalar at a time, hold data and other parameters fixed, restore it afterward. Float64 and h near 1e-5 are reasonable starting values for smooth small networks; try several h values, since truncation error falls with h while cancellation worsens when h is too small. Use absolute and relative tolerance (e.g. abs(a-b)<=atol+rtolabs(b)), not exact equality. Avoid checking ReLU exactly at a kink; use smooth tanh or samples away from kinks. Verify parameter and gradient shapes are identical, all values finite, and targets match logits. A passing check on a toy input is not proof for all inputs. XOR training on four truth-table rows tests fitting, not generalization. All-zero tanh network may remain at zero for balanced XOR because hidden activations and output weights are zero and summed output bias gradient cancels.
Broadcast shape trap
import numpy as npz=np.zeros((3,1)); y=np.zeros(3)print((z-y).shape,(z-y.reshape(-1,1)).shape)Expected output: (3, 3) (3, 1). Reshape labels explicitly to avoid unintended pairwise errors.
Common mistakes
Do not compare finite differences after changing model state, dropout masks or batches. Do not use a large h and interpret coarse slopes as exact derivatives. Do not overlook a near-zero denominator in relative error. Check shapes before np.allclose, which can broadcast.
Practice and next steps
Run the chapter milestone, inspect the maximum gradient error and compare random initialization with zero initialization. Change h and learning rate one at a time.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Gradient and shape checks — knowledge check
Apply gradient and shape checks to small examples and debugging scenarios.
Why use a tolerance for gradient checks?
What happens if h becomes extremely small?
Where is a ReLU finite difference ambiguous?
What should be checked before comparing gradient arrays?
What does fitting the four XOR rows establish?