Part 5 of 6 · Prove it with a gradient checkLearn and do
Prove it with a gradient check
Nudge a weight both ways, and the loss gives its gradient
You can't eyeball a gradient, but you can measure one. Try it on v3 at v=2, whose true slope is 12:
def cube(v: float) -> float: """Returns v cubed. Its slope at v is 3 v².""" return v ** 3for eps in [1e-2, 1e-4, 1e-6]: central = (cube(2 + eps) - cube(2 - eps)) / (2 * eps) one_sided = (cube(2 + eps) - cube(2)) / eps print(f"{eps:.0e} {abs(central - 12):.0e} {abs(one_sided - 12):.0e}")
Predict
The slope of v³ at 2 is 12. With a nudge of 1e-4, how far off are the central estimate, which nudges both ways, and the one-sided one, which nudges only up?
Pick one to see what it prints.
Each line is the nudge size ε, then the error of the central difference and of the one-sided difference.
Here are both as lines through the curve. Shrink ε and watch the errors:
Two ways to measure a slopeInteractive
true slope, 12 one-sided central
One-sided slope
15.25
One-sided error
3.25
Central slope
12.25
Central error
0.250
At ε = 0.50 the one-sided line is off by 3.25, and the central one by 0.250. Halve ε and the one-sided error roughly halves, while the central error drops to a quarter: the curve's bend adds an error on each side, and the central line's two errors cancel.
On each side the curve's bend adds an error. In the central version those two errors cancel, so what's left shrinks like ϵ2. The one-sided error shrinks only like ϵ: make ε 100 times smaller, and the one-sided error drops 100 times, the central one 10,000 times.
At ϵ=10−6 the central error stops at 8e-10 instead of 1e-12. Rounding has taken over, and the next part shows why.
For a network, nudge one parameter at a time:
∂θi∂L≈2ϵL(θ+ϵei)−L(θ−ϵei)
Here θ is every parameter laid out as one long vector, θi is one entry of it, and ϵ is the size of the nudge. ei is all zeros except a 1 at position i, so θ±ϵei moves that one entry and leaves the rest alone.
In the editor, write errors(f, true_slope, v, eps): how far each estimate lands from the true slope.
Pick an answer above to see the rest
Instructions
1
Write errors(f, true_slope, v, eps): how far the central and the one-sided estimates of f's slope at v land from true_slope, as a pair of absolute values.
2
The central one nudges both ways, the one-sided one only up.