Gradient checks
A gradient check compares an analytic derivative with a numerical estimate using an explicit tolerance rule.
On this page 8 sections
01Understand the idea#
A gradient check compares a program’s derivative with a finite-difference estimate of the same function at the same point. It helps catch missing factors, signs, and coordinate mixups before using the gradient to train a model.
The check must specify the discrepancy metric and tolerance. Absolute error and relative error answer different questions, especially near zero. Compute the stated metric instead of deciding that two displayed numbers merely look close.
A gradient check compares an analytic derivative with a numerical estimate at the same input. An explicit tolerance decides whether the discrepancy is acceptable.
For absolute tolerance , pass when . Equality passes. Treat displayed decimals as exact in these exercises.
With analytic derivative , numerical estimate , and , the difference is .
If the analytic derivative is 2.01 and the finite-difference estimate is 2.00, their absolute difference is 0.01. Under the relative metric , it is . A tolerance of 0.001 fails this comparison. Always use the denominator and zero-case rule specified by the task.
Analytic ; numerical . Pass if .
Show answer and explanation
Difference exceeds allowance .
02A mixed tolerance uses an absolute allowance t and a relative allowance r#
A mixed tolerance uses an absolute allowance and a relative allowance . Let , the larger absolute derivative value. These values set the allowed discrepancy:
For , , , and , the larger magnitude is . The allowance is .
The discrepancy is . Because , this point passes the mixed rule.
Analytic ; numerical . Pass if .
Show answer and explanation
Difference exceeds allowance .
03A mismatch needs investigation#
A mismatch needs investigation. Check the analytic rules, the numerical step and precision, and whether both evaluations used the same fixed inputs. A corner can also invalidate the comparison.
A passing point does not test all inputs or coordinates. A numerical estimate is not an exact reference by default. Recheck fresh points and coordinates instead of treating one pass as a proof.
Analytic , numerical . Pass if . Assess “correct everywhere.”
Show answer and explanation
Passes: .
04Check several inputs and coordinates, including cases with shared branches#
Check several inputs and coordinates, including cases with shared branches. A passing sample does not prove the whole gradient correct. Near a nondifferentiable point, finite differences can mix behavior from opposite sides, so disagreement needs interpretation rather than an automatic formula change.
Compare the discrepancy with the stated allowance, then interpret the result as local evidence.
- Diagnose a mismatch between analytic and numerical derivatives using a stated tolerance.
Sources & further reading
- [1]Stanford CS231n: Gradient Checks ↗Stanford CS231n · Article