Neural networks and backpropagation: gradients, checks and initialisation
- Intermediate
- 1 h
- Lesson 1 of 4 in Deep learning and transformers
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:The learning problem: generalization, bias-variance and regularizationML foundations
- Completed:Linear models, loss functions and gradient descentML foundations
You will be able to
- Explain why a network needs non-linear activations, choose between ReLU, GELU, sigmoid and tanh by how they saturate, and give the shape of every tensor and the parameter count of a 2-layer network.
- Work backpropagation by hand through a 2-layer ReLU network with softmax cross-entropy using the chain rule, and verify the result with a central-difference gradient check.
- Explain vanishing and exploding gradients as products of per-layer factors, and say how the choice of activation and of Xavier or He initialisation changes those factors.
Concept
A neural network is the same three pieces as every model so far: a function, a loss and an optimizer. The function is a stack of layers, each a linear map followed by a non-linear activation. The loss is one you know, such as cross-entropy. The optimizer is gradient descent. What is new is how the gradient is computed for millions of parameters: backpropagation is the chain rule applied from the output backwards, reusing the numbers saved on the way forward.
In the linear-models lesson the gradient of the loss with respect to the score was prediction minus target, ; in a network that quantity appears at the last layer and backpropagation carries it back. That lesson deferred AdamW, learning-rate schedules and gradient clipping, and the first lesson listed early stopping among the fixes for overfitting; they are paid off in the next lesson, which is about keeping a network trainable. This lesson is about how the gradient is computed, checked and kept from vanishing or exploding.
Why It Matters
Most of the work of getting a network to train is knowing why the loss is flat, why the gradients are zero in the first layers, and whether your backward pass is even correct. Each has a mechanism that fits in a few lines, and these are standard interview questions (common industry pattern).
Mental Model
Picture a relay of 20 people, each multiplying the message by a number before passing it on. If the numbers are a little below 1 the message fades; a little above 1 and it becomes a shout. Forward, the message is the activation. Backward, the relay runs in reverse and the message is the gradient. Initialisation sets the typical multiplier and activations decide how much gets through. Normalisation, which resets the volume, and clipping, which caps the shout, come in the next lesson.
Neurons, layers and shapes
A neuron computes : a weighted sum plus a bias, passed through an activation . A layer is many neurons reading the same input, which is one matrix multiply: . For one input , hidden units and classes:
| Tensor | Shape | Meaning |
|---|---|---|
| One input | ||
| First layer | ||
| Pre-activation and activation | ||
| Output layer | ||
| Logits |
For a batch of inputs stacked as rows, each vector gains a leading and has shape . The parameter count is : 101,770 for 784 inputs, 128 hidden units and 10 classes.
Why a non-linearity is required
An affine function of an affine function is itself affine (Dive into Deep Learning, MLPs): . The script checks it on random matrices and finds the two forms differ by about , which is rounding error. A stack of linear layers is one linear layer with extra parameters.
XOR shows the cost. Write the rule as . The four points require , , and . Adding the middle two gives , so , a contradiction (derived here). A search over 15,625 linear rules gets at most 3 of 4 points. Two ReLU units, and , with output , return exactly. One hidden layer with enough units can in principle approximate any continuous function (the standard universal approximation statement; the textbook words it more loosely as any function), but finding the weights is the hard part (Dive into Deep Learning, MLPs); the rest of the lesson is about that second problem.
Choosing an activation
| Activation | Formula | Gradient behaviour | Typical use |
|---|---|---|---|
| Sigmoid | At most 0.25, near 0 for large | Binary output; gating (common practice) | |
| Tanh | At most 1, near 0 for large | Older hidden layers; squashing values in recurrent cells (common practice) | |
| ReLU | 1 for , 0 for | Default hidden layer | |
| GELU | Smooth, small non-zero values for negative | Widely used in transformer language models (common practice) |
The sigmoid’s derivative peaks at 0.25 and tanh’s at 1 (Dive into Deep Learning, MLPs). Saturation is the problem: far from zero both flatten. The script prints sigmoid derivatives of 0.25 at , 0.105 at 2, 0.0066 at 5 and at 10, and tanh derivatives of 1, 0.071, and . Over ten sigmoid layers the activation-derivative part of the gradient shrinks by at least .
ReLU does not saturate for positive inputs and is cheap, but its derivative is exactly 0 for negative . A unit that is negative for every input in the data gets no gradient and cannot recover: a dead ReLU (derived here). GELU is with the standard normal CDF, so it weights inputs by value instead of gating by sign (Hendrycks and Gimpel); the script gives at and at , damped and not zeroed.
One place the non-linearity pays off: a network trained to reproduce its own input through a narrow middle layer is an autoencoder, which can be read as a non-linear counterpart of the PCA in the unsupervised lesson (a loose analogy).
Backpropagation by the chain rule
Training needs for every parameter. Backpropagation evaluates the chain-rule product from the output towards the input, so each layer reuses the gradient already computed for the layer after it, and the activations saved in the forward pass (Dive into Deep Learning, backpropagation). One backward sweep gives every parameter’s gradient.
The recipe
For , , , and loss :
The first line is the softmax result from the linear-models lesson, which carries over to a network’s last layer (Dive into Deep Learning, softmax regression). The pattern repeats: a weight gradient is the error at the layer’s output times its input, and the error goes back through the transposed weights and the activation’s derivative. The ReLU derivative is a mask that passes the gradient where .
Counting multiply-adds (derived here): forward does one matrix-vector product per layer, backward does two of the same size, one for and one for , so backward costs about twice forward. Memory is the other bill: the saved activations stay until the backward pass finishes and grow with layers and batch size, which is why training needs more memory than prediction (Dive into Deep Learning, backpropagation).
Worked example: one input, two layers
Take , , , , input and true class (the second class, counting from 0). The script prints every number below.
| Step | Value |
|---|---|
| Loss | 2.1269 |
| rows and | |
| after the mask | |
| rows and |
The model puts 88% on the wrong class, so the loss and are large. The second hidden unit was inactive (): it passed nothing forward, so its output weights get zero gradient, and the mask blocks the 0.6606 arriving from above, so its input weights get zero too. One step at learning rate 0.1 takes the loss from 2.1269 to 0.6089.
Checking gradients numerically
A hand-written backward pass is easy to get subtly wrong, and a wrong gradient still gives a loss that moves. The test is the definition of a derivative: nudge one parameter by and compare. The central difference has error shrinking as , against for a one-sided difference. CS231n’s rules of thumb for the relative error: above the gradient is probably wrong, or below is good, and larger values can be acceptable where the function has kinks. Errors build up with depth, so for a 10-layer network 1e-2 may be acceptable. It recommends double precision, and a few data points, because a nudge across a ReLU kink makes the two gradients legitimately disagree (CS231n).
On the worked example with , all 12 parameters agree to a maximum relative error of . Three plausible bugs in the backward pass only:
| Bug | Max relative error |
|---|---|
| Correct code | |
| ReLU mask forgotten | 1.00 |
| used where is needed | 0.75 |
| Sign of flipped | 2.00 |
The check costs two forward passes per parameter, so use it on a tiny network when you write a new layer. Two cheaper checks: the initial loss should be about (2.3026 for 10 classes), and the model must overfit a tiny batch to near zero loss (CS231n; Karpathy). In the script’s two-class network with the output weights scaled by 0.01 the initial loss is 0.693, which is , against 0.990 for ordinary output initialisation. Four training points reach a loss of 0.0067 after 300 epochs.
Vanishing and exploding gradients
Through layers the gradient is a product of per-layer factors, each made of weights and an activation derivative. Below 1 the product shrinks exponentially; above 1 it grows exponentially. The early layers either learn nothing or receive updates large enough to destroy the model (Dive into Deep Learning, numerical stability). The same arithmetic applies forward to the activations.
Initialisation: Xavier and He
Initialisation sets the typical factor before training. All-zero (or any constant) weights are a trap: every hidden unit computes and receives the same thing, so the symmetry never breaks (Dive into Deep Learning, numerical stability). Small random weights break it, and their scale decides whether signals survive depth. Glorot and Bengio found the logistic sigmoid poorly suited to deep networks with random initialisation, because its non-zero mean can push the top hidden layer into saturation (Glorot and Bengio).
Both standard schemes choose the weight variance so activation variance stays roughly constant across layers. Xavier (Glorot) uses variance (PyTorch, nn.init), which is for a square layer. It does not account for ReLU, which zeroes about half the pre-activations and halves the mean square, so He initialisation doubles the variance to (derived here; He et al. derived an initialisation for rectifiers). PyTorch’s Kaiming initialiser uses a gain of for ReLU, with standard deviation gain over .
The script tests it: 20 layers of width 64, eight random inputs, the rms activation at layers 1 and 20, and the rms of the gradient at the input over its rms at the output.
| Activation and weight scale | Activation rms, layer 1 to 20 | Gradient rms, input over output | Gradient factor per layer |
|---|---|---|---|
| tanh, std 0.01 | 0.081 to | 0.078 | |
| tanh, Xavier | 0.64 to 0.16 | 0.115 | 0.898 |
| tanh, std 1.0 | 0.96 to 0.94 (saturated) | 1.955 | |
| sigmoid, Xavier | 0.53 to 0.52 | 0.227 | |
| ReLU, std 0.01 | 0.056 to | 0.059 | |
| ReLU, Xavier | 0.70 to | 0.744 | |
| ReLU, He | 0.99 to 0.95 | 2.7 | 1.052 |
| ReLU, 2 times He | 2.0 to | 2.103 |
The gradient column stays within a factor of about 3 across weight seeds 0, 1 and 2 (the script prints all three). What it shows:
- Scale decides. Too small and the signal vanishes both ways; too large and it explodes. A factor of two in variance separates ReLU with He (stable) from ReLU with Xavier, whose activation rms is multiplied by about 0.71 per layer (it keeps 71%), matching .
- Sigmoid vanishes even at a sensible scale. The gradient is multiplied by about 0.23 per layer; ten layers give a factor near (derived here).
- Saturation does not guarantee vanishing. The per-layer factor is the weight scale times the activation derivative. With tanh at std 1.0 the activations sit near where the derivative is small, yet the gradient grows by towards the input, because the large weights outweigh it.
Remedies: ReLU-family activations, a scale-aware initialisation and, covered in the next lesson, normalisation layers and gradient clipping. Residual connections give the gradient a path around layers; they belong with architectures later in this module.
Code
This standard-library script produced every number in the lesson. It has fixed seeds and runs in about 2 seconds (Python 3.14). Another Python version may draw different random data, which moves the exact numbers in sections 4 and 5 but not their orders of magnitude or the pattern.
import itertools
import math
import random
import statistics
import time
T0 = time.time()
def matvec(W, v):
return [sum(w * x for w, x in zip(row, v)) for row in W]
def softmax(z):
m = max(z)
e = [math.exp(a - m) for a in z]
s = sum(e)
return [a / s for a in e]
def rms(v):
return math.sqrt(sum(a * a for a in v) / len(v))
# ---- a 2-layer network: x -> ReLU(W1 x + b1) -> softmax(W2 a1 + b2) ----
def forward(P, x, mask=None):
W1, b1, W2, b2 = P
z1 = [s + b for s, b in zip(matvec(W1, x), b1)]
a1 = [max(0.0, z) for z in z1]
if mask:
a1 = [a * m for a, m in zip(a1, mask)]
z2 = [s + b for s, b in zip(matvec(W2, a1), b2)]
return z1, a1, z2, softmax(z2)
def loss_of(P, x, y):
return -math.log(forward(P, x)[3][y])
def backward(P, x, y, cache, mask=None):
W1, b1, W2, b2 = P
z1, a1, z2, p = cache
dz2 = [pk - (1.0 if k == y else 0.0) for k, pk in enumerate(p)]
dW2 = [[d * a for a in a1] for d in dz2]
da1 = [sum(W2[k][j] * dz2[k] for k in range(len(dz2))) for j in range(len(a1))]
if mask:
da1 = [d * m for d, m in zip(da1, mask)]
dz1 = [d if z > 0 else 0.0 for d, z in zip(da1, z1)]
dW1 = [[d * xi for xi in x] for d in dz1]
return [dW1, dz1, dW2, dz2], dz2, da1, dz1
def cells(T):
for t in T:
if isinstance(t[0], list):
for row in t:
for j in range(len(row)):
yield row, j
else:
for j in range(len(t)):
yield t, j
def numeric_grad(P, x, y, h=1e-5):
out = []
for c, j in cells(P):
old = c[j]
c[j] = old + h
up = loss_of(P, x, y)
c[j] = old - h
dn = loss_of(P, x, y)
c[j] = old
out.append((up - dn) / (2 * h))
return out
def rel_err(a, n):
return abs(a - n) / max(abs(a), abs(n), 1e-8)
print("== 1. Worked example: 2 inputs, 2 ReLU units, 2 classes, label y = class 1 ==")
P = [[[0.5, 0.25], [-1.0, 0.5]], [0.0, -0.5], [[1.0, 0.5], [-1.0, -0.25]], [0.0, 0.0]]
x, y = [1.0, 2.0], 1
cache = forward(P, x)
z1, a1, z2, p = cache
G, dz2, da1, dz1 = backward(P, x, y, cache)
print("z1", z1, "a1", a1, "z2", z2)
print("p", [round(v, 4) for v in p], "loss", round(loss_of(P, x, y), 4))
print("dz2 = p - y", [round(v, 4) for v in dz2])
print("dW2", [[round(v, 4) for v in r] for r in G[2]], "db2", [round(v, 4) for v in G[3]])
print("da1 = W2^T dz2", [round(v, 4) for v in da1], " dz1 = da1 * 1[z1>0]", [round(v, 4) for v in dz1])
print("dW1", [[round(v, 4) for v in r] for r in G[0]], "db1", [round(v, 4) for v in G[1]])
flat = [g for c, j in cells(G) for g in [c[j]]]
num = numeric_grad(P, x, y)
print("gradient check, 12 parameters, central difference h=1e-5: max abs diff %.1e, max relative error %.1e"
% (max(abs(a - n) for a, n in zip(flat, num)), max(rel_err(a, n) for a, n in zip(flat, num))))
# the same check on three plausible bugs
def check(G_bad):
f = [g for c, j in cells(G_bad) for g in [c[j]]]
return max(rel_err(a, n) for a, n in zip(f, num))
no_mask = [[[d * xi for xi in x] for d in da1], da1, G[2], G[3]]
flipped = [[[-v for v in r] for r in G[0]], [-v for v in G[1]], [[-v for v in r] for r in G[2]], [-v for v in G[3]]]
W2 = P[2]
wrong = [W2[0][0] * dz2[0] + W2[0][1] * dz2[1], W2[1][0] * dz2[0] + W2[1][1] * dz2[1]] # rows, not columns
dz1_t = [d if z > 0 else 0.0 for d, z in zip(wrong, z1)]
wrongT = [[[d * xi for xi in x] for d in dz1_t], dz1_t, G[2], G[3]]
print("bug: ReLU mask forgotten -> max relative error %.2f" % check(no_mask))
print("bug: sign of p - y flipped -> max relative error %.2f" % check(flipped))
print("bug: W2 used where W2^T needed -> max relative error %.2f" % check(wrongT))
lr = 0.1
Q = [[r[:] for r in P[0]], P[1][:], [r[:] for r in P[2]], P[3][:]]
for (c, j), (g, k) in zip(cells(Q), cells(G)):
c[j] -= lr * g[k]
print("after one step lr=0.1: loss %.4f -> %.4f" % (loss_of(P, x, y), loss_of(Q, x, y)))
print("\n== 2. Why a non-linearity ==")
rng = random.Random(0)
A1 = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(4)]
c1 = [rng.gauss(0, 1) for _ in range(4)]
A2 = [[rng.gauss(0, 1) for _ in range(4)] for _ in range(2)]
c2 = [rng.gauss(0, 1) for _ in range(2)]
A = [[sum(A2[i][k] * A1[k][j] for k in range(4)) for j in range(3)] for i in range(2)]
cc = [sum(A2[i][k] * c1[k] for k in range(4)) + c2[i] for i in range(2)]
worst = 0.0
for _ in range(5):
v = [rng.gauss(0, 1) for _ in range(3)]
two = [s + b for s, b in zip(matvec(A2, [s + b for s, b in zip(matvec(A1, v), c1)]), c2)]
one = [s + b for s, b in zip(matvec(A, v), cc)]
worst = max(worst, max(abs(a - b) for a, b in zip(two, one)))
print("two stacked linear layers vs one layer (A2 A1)x + (A2 c1 + c2): max difference %.1e" % worst)
pts = [((0, 0), 0), ((0, 1), 1), ((1, 0), 1), ((1, 1), 0)]
best = 0
grid = [i / 4 for i in range(-12, 13)]
for w1, w2, b in itertools.product(grid, repeat=3):
best = max(best, sum((w1 * a + w2 * c + b > 0) == bool(t) for (a, c), t in pts))
print("XOR: best linear rule found on a 25^3 grid classifies %d of 4" % best)
xor_out = []
for (a, c), t in pts:
h1, h2 = max(0, a + c), max(0, a + c - 1)
xor_out.append(h1 - 2 * h2)
print("XOR with hidden relu(a+c), relu(a+c-1), output h1 - 2 h2:", xor_out)
print("parameters of 784 -> 128 -> 10:", 128 * (784 + 1) + 10 * (128 + 1))
print("\n== 3. Derivatives and saturation ==")
sig = lambda z: 1 / (1 + math.exp(-z))
for z in (0, 2, 5, 10):
print("z=%2d sigmoid' %.2e tanh' %.2e" % (z, sig(z) * (1 - sig(z)), 1 - math.tanh(z) ** 2))
print("best-case product of 10 sigmoid derivatives: 0.25**10 = %.2e" % 0.25 ** 10)
gelu = lambda z: z * 0.5 * (1 + math.erf(z / math.sqrt(2)))
print("GELU at -3, -1, 0, 1, 3:", [round(gelu(z), 4) for z in (-3, -1, 0, 1, 3)])
print("\n== 4. Signal through 20 layers of width 64 (8 random inputs, rms of the activations) ==")
def deep(act, std_fn, depth=20, width=64, seed=0):
rng = random.Random(seed)
Ws = [[[rng.gauss(0, std_fn(width)) for _ in range(width)] for _ in range(width)] for _ in range(depth)]
fwd, bwd = [], []
for _ in range(8):
a = [rng.gauss(0, 1) for _ in range(width)]
zs = []
acts = [a]
for W in Ws:
z = matvec(W, a)
a = [act(v) for v in z]
zs.append(z)
acts.append(a)
fwd.append([rms(v) for v in acts])
g = [1.0] * width # d(sum of last activations)/d(last activations)
norms = [rms(g)]
for l in range(depth - 1, -1, -1):
dz = [gi * (1 - math.tanh(z) ** 2 if act is math.tanh else (sig(z) * (1 - sig(z)) if act is sig else (1.0 if z > 0 else 0.0))) for gi, z in zip(g, zs[l])]
g = [sum(Ws[l][i][j] * dz[i] for i in range(width)) for j in range(width)]
norms.append(rms(g))
bwd.append(norms[::-1])
mean = lambda rows, i: statistics.mean(r[i] for r in rows)
return [mean(fwd, i) for i in (1, 5, 10, 20)], mean(bwd, 0) / mean(bwd, 20), (mean(fwd, 20) / mean(fwd, 1)) ** (1 / 19)
relu = lambda v: max(0.0, v)
rows = [
("tanh, std 0.01", math.tanh, lambda n: 0.01),
("tanh, Xavier sqrt(1/n)", math.tanh, lambda n: math.sqrt(1 / n)),
("tanh, std 1.0", math.tanh, lambda n: 1.0),
("sigmoid, Xavier sqrt(1/n)", sig, lambda n: math.sqrt(1 / n)),
("ReLU, std 0.01", relu, lambda n: 0.01),
("ReLU, Xavier sqrt(1/n)", relu, lambda n: math.sqrt(1 / n)),
("ReLU, He sqrt(2/n)", relu, lambda n: math.sqrt(2 / n)),
("ReLU, 2x He sqrt(8/n)", relu, lambda n: math.sqrt(8 / n)),
]
print("activation rms at layers 1, 5, 10, 20 | gradient rms at input / at output | activation factor per layer | gradient factor per layer")
for name, act, sd in rows:
f, b, pl = deep(act, sd)
print("%-26s %s | %.2e | %.3f | %.3f" % (name, ["%.2e" % v for v in f], b, pl, b ** (1 / 20)))
print("same gradient ratio with weight seeds 0, 1, 2:")
for name, act, sd in rows:
print(" %-26s %s" % (name, ["%.1e" % deep(act, sd, seed=k)[1] for k in (0, 1, 2)]))
# ---- a small data set: two moons ----
def moons(n, noise, rng):
X, Y = [], []
for i in range(n):
c, t = i % 2, rng.uniform(0, math.pi)
px, py = (math.cos(t), math.sin(t)) if c == 0 else (1 - math.cos(t), 0.5 - math.sin(t))
X.append([px + rng.gauss(0, noise), py + rng.gauss(0, noise)])
Y.append(c)
return X, Y
def init(rng, H, d=2, k=2, out_scale=1.0):
return [[[rng.gauss(0, math.sqrt(2 / d)) for _ in range(d)] for _ in range(H)], [0.0] * H,
[[rng.gauss(0, math.sqrt(2 / H) * out_scale) for _ in range(H)] for _ in range(k)], [0.0] * k]
def evaluate(P, X, Y):
L, ok = 0.0, 0
for x, y in zip(X, Y):
p = forward(P, x)[3]
L -= math.log(max(p[y], 1e-12))
ok += p.index(max(p)) == y
return L / len(X), ok / len(X)
print("\n== 5. Initial loss and overfitting a tiny batch (two-moons data) ==")
rng = random.Random(3)
Xs, Ys = moons(200, 0.35, rng)
for scale in (1.0, 0.01):
print("initial loss on 200 points, output weights x%s: mean over 8 seeds %.3f" % (scale, statistics.fmean(evaluate(init(random.Random(s), 16, out_scale=scale), Xs, Ys)[0] for s in range(8))))
Xt, Yt = Xs[:4], Ys[:4]
Pt = init(random.Random(0), 16)
for ep in range(300):
for x, y in zip(Xt, Yt):
G = backward(Pt, x, y, forward(Pt, x))[0]
for (c, j), (g, k) in zip(cells(Pt), cells(G)):
c[j] -= 0.5 * g[k] / 4
print("4 points, 300 epochs, lr 0.5: loss %.4f, accuracy %.2f" % evaluate(Pt, Xt, Yt))
print("total %.1f s" % (time.time() - T0))What to look for: section 1 (the worked example, the gradient check and the three bugs), section 2 (stacked linear layers collapse, XOR, and the parameter count), section 3 (derivatives, saturation and GELU), section 4 (the table of initialisations and the three weight seeds), section 5 (initial loss and overfitting four points). In PyTorch the equivalents are nn.Linear, loss.backward(), torch.autograd.gradcheck and nn.init.kaiming_normal_.
Real-World Application
A sound first step with any new network: check that the initial loss is near , overfit a handful of examples, and gradient-check any layer you wrote yourself. When a deep network does not train, print the activation and gradient scale per layer before touching the learning rate: a scale that collapses or grows by a constant factor per layer points to initialisation or activation choice, as in the table above. The next lesson covers what keeps a run stable once the gradients flow.
Interview Perspective
Expect “derive backpropagation for a two-layer network”, “why do we need non-linear activations”, “what causes vanishing gradients and how do you fix them” and “why not initialise all weights to zero”. A strong answer writes the forward pass, goes backwards with the chain rule, names the mask and the transposed weights, and adds a check. A weak answer recites “use ReLU” without saying what it changes.
Provenance: Common industry pattern. These are standard fundamentals for ML roles, not a verified list for any named company.
Practice Questions
- Basic: Why can a network with ten layers and no activation functions not learn XOR?
- Intermediate: Write the backward pass for a 2-layer ReLU network with softmax cross-entropy, including the shape of every gradient.
- Intermediate: A 30-layer ReLU network is initialised with Xavier weights and the first layer’s gradient is a thousand times smaller than the last. What do you change, and what per-layer factor do you expect afterwards?
- Advanced: Your gradient check reports a relative error of 3e-3 on a 20-layer ReLU network. What do you do before declaring a bug?
- Product-Company (Generated practice): A teammate’s custom layer trains but the model is worse than a baseline. How do you decide whether the layer’s backward pass is correct?
Activity
Redo the worked example by hand with the label changed to class 0, then run the script’s section 1 with y = 0 and compare. Next, change the first bias to [0.0, 1.0] so both hidden units are active and find which gradient entries stop being zero. Finally, introduce a deliberate bug in the backward pass, predict whether the gradient check will catch it, and then run it.
Homework
Implement the pieces that make a small network checkable: a stable softmax cross-entropy, the forward and backward pass of a 2-layer ReLU network, and a central-difference gradient check with a relative-error measure. The code is in homework/; run the tests until they pass.
Quick Revision
- A network is stacked linear maps and activations; without the activation it collapses to one linear map, and XOR cannot be solved linearly.
- Backprop: , , , . Cache the forward values.
- Check new gradients with a central difference; relative error near or lower is good, above is probably a bug (deeper nets accumulate error). Check the initial loss against and overfit a tiny batch.
- Gradients are products of per-layer factors. Sigmoid is at most 0.25 per layer. He () for ReLU, Xavier () for roughly linear activations; equal weights never break symmetry.
Check yourself
- Walk-through: Without notes, derive and for the 2-layer ReLU network, then say how you would check the result.
- Variation: Replace ReLU with sigmoid in a 10-layer network. Which factor shrinks the gradient, by how much at best, and what two changes would you try?
- Common misconception: “Zero initialisation is fine because the gradients will differ”, and “ReLU never has vanishing gradients”.
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Further reading
The gradient-check and sanity-check section is a short checklist you can follow line by line before trusting a hand-written backward pass.
A Recipe for Training Neural Networks (opens in a new tab)Essential
A practitioner's order of operations for training a network: verify the loss at initialisation, overfit one batch, then regularise. It turns this lesson's debugging flow into a habit.
Computational graphs and the memory cost of backpropagation, with the same two-layer network and weight decay.
Research papers
The derivation behind the factor of two in He initialisation, plus the PReLU activation.
More for this module: Deep learning and transformers resources
Practice
Test what you just read. Quizzes and cards are grouped by module: Deep learning and transformers.
Check yourself12 questions on what this lesson set out to teach
Checking answers needs JavaScript. You can still read every question and option below.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.