15Lab 4: Feed-forward Networks and Backpropagation
Nonlinear representations, derivatives, and verification
Author
Noel Danz
15.1 How to use this sheet
These exercises are voluntary practice for Lesson 4. Start with paper and pencil; use the optional computer investigation to verify your reasoning. Allow approximately 60–90 minutes for Exercises 1–9 and another 45–75 minutes for the programming investigation. Try each problem before expanding its solution. The classroom implementation task may be maintained separately; this sheet is self-contained.
Part
Exercises
Focus
A
1–3
Affine maps, XOR, activations
B
4–6
Computation graphs, backpropagation, SGD
C
7–9
Gradient checks, debugging, capacity
Optional
Computer investigation
Train and compare NumPy MLPs
Conventions. Observations are column vectors. A two-layer MLP has one hidden affine layer and one output affine layer. For a single observation, use \(L=\frac12(\hat y-y)^2\) unless specified otherwise; for a dataset, use the mean of the per-observation losses. ReLU is \(\max(0,z)\) and its derivative at zero is taken as \(0\) in these exercises. SGD uses \(\theta\leftarrow\theta-\eta\nabla_\theta L\). The numerical examples use a linear output, not a sigmoid output.
15.2 Part A: Nonlinear representations
15.2.1 Exercise 1 — Why affine compositions are insufficient
Consider \(h=W_1x+b_1\) and \(z=W_2h+b_2\).
Express \(z\) as a single affine map of \(x\) and identify its effective weight and bias.
Does adding more affine layers change this conclusion?
Explain why a linear threshold applied to this output cannot classify all four XOR inputs.
NoteWorked solution 1
Substitution gives \(z=(W_2W_1)x+(W_2b_1+b_2)\). The same argument applies recursively to any number of affine layers. A threshold of a scalar affine function yields a single linear decision boundary. XOR requires opposite corners of a square to have the same label, which no single line can separate.
Explain what each hidden neuron detects and why \(\hat y\) equals XOR on these inputs.
Is the output necessarily a probability for arbitrary real-valued inputs?
\(x\)
\(a_1\)
\(a_2\)
\(\hat y\)
\((0,0)\)
\((0,1)\)
\((1,0)\)
\((1,1)\)
NoteWorked solution 2
\(x\)
\(a_1\)
\(a_2\)
\(\hat y\)
\((0,0)\)
0
0
0
\((0,1)\)
1
0
1
\((1,0)\)
1
0
1
\((1,1)\)
2
1
0
The first neuron detects positive input sum; the second detects input sum exceeding one. Their combination implements XOR on binary inputs. The linear output is not constrained to \([0,1]\) outside these four points.
15.2.3 Exercise 3 — Activations and local derivatives
Evaluate ReLU and its derivative at \(z=-1,0,2\) using our convention.
Evaluate \(\sigma(0)\) and \(\sigma'(0)\) for \(\sigma(z)=1/(1+e^{-z})\).
Evaluate \(\tanh(0)\) and \(\tanh'(0)\).
Why does the derivative of ReLU at zero require a convention? What can happen to a ReLU neuron whose preactivation remains negative?
NoteWorked solution 3
ReLU values are \((0,0,2)\) and selected derivatives \((0,0,1)\). Sigmoid has \(\sigma(0)=1/2\) and \(\sigma'(0)=\sigma(0)(1-\sigma(0))=1/4\). Tanh has value \(0\) and derivative \(1-\tanh^2(0)=1\). ReLU is not classically differentiable at zero; frameworks select a subgradient, commonly zero. A consistently inactive neuron receives zero gradient through its ReLU activation for those examples.
15.3 Part B: Backpropagation by hand
15.3.1 Exercise 4 — Trace a scalar computation graph
Let \(u=2x\), \(v=u+3\), and \(L=v^2/2\) with \(x=1\).
Draw the graph \(x\to u\to v\to L\) and evaluate each node.
Starting at \(\partial L/\partial L=1\), calculate \(\partial L/\partial v\), \(\partial L/\partial u\), and \(\partial L/\partial x\).
Verify your answer by differentiating \(L(x)=(2x+3)^2/2\) directly.
NoteWorked solution 4
At \(x=1\), \(u=2\), \(v=5\), and \(L=12.5\). Reverse-mode derivatives are \(\partial L/\partial v=v=5\), \(\partial L/\partial u=5(1)=5\), and \(\partial L/\partial x=5(2)=10\). Direct differentiation yields \(2(2x+3)\), also \(10\) at \(x=1\).
15.3.2 Exercise 5 — Complete a two-layer backward pass
Use the numerical network from the concepts chapter:
Set \(h=W_1x+b_1\), \(a=\operatorname{ReLU}(h)\), \(\hat y=W_2a+b_2\), and \(L=\frac12(\hat y-y)^2\).
Calculate \(h,a,\hat y,L\).
Calculate the output delta \(\delta_2=\partial L/\partial\hat y\) and hidden delta \(\delta_1=(W_2^T\delta_2)\odot\operatorname{ReLU}'(h)\).
Calculate \(\nabla_{W_2}L,\nabla_{b_2}L,\nabla_{W_1}L,\nabla_{b_1}L\) and state their shapes.
NoteWorked solution 5
\(h=(-1,3)^T\), \(a=(0,3)^T\), \(\hat y=-1.5\), and \(L=3.125\). The output delta is \(\delta_2=-2.5\). Since \(W_2^T\delta_2=(-1.25,1.25)^T\) and the ReLU derivative is \((0,1)^T\), \(\delta_1=(0,1.25)^T\).
The updated hidden preactivation is \((-1,2.25)^T\), so \(\hat y'=0.25(2.25)+0.25=0.8125\) and \(L'=\frac12(0.8125-1)^2=0.017578125\). Backpropagation calculates gradients; SGD uses them to modify parameters. A single improvement does not guarantee future improvement or convergence.
Use the normalized discrepancy \(r=|g-g_{\mathrm{FD}}|/\max(1,|g|,|g_{\mathrm{FD}}|)\).
Calculate \(r\) for \((g,g_{\mathrm{FD}})=(1.25,1.24999)\) and \((-7.5,-7.49)\).
Which is the more suspicious discrepancy?
Explain why an excessively small \(\varepsilon\) and a ReLU kink can make numerical checking unreliable.
NoteWorked solution 7
The errors are \(10^{-5}/1.25=8\times10^{-6}\) and \(0.01/7.5\approx1.33\times10^{-3}\). The second discrepancy is larger. Small steps amplify floating-point cancellation; finite differences across a nondifferentiable point need not agree with the implementation’s selected subgradient. Check several step sizes away from kinks.
15.4.2 Exercise 8 — Find two backward-pass bugs
Assume \(x\) has shape \((d,)\), \(W_1\) has shape \((m,d)\), \(W_2\) has shape \((1,m)\), and delta2 is a scalar. The following code contains two mistakes:
The first line omitted the activation derivative. The second transposed the required outer product, producing \((d,m)\) instead of \((m,d)\) (which can silently pass a shape test when \(d=m\)). Numerical gradient checks help detect mathematically incorrect gradients even when shapes agree.
15.4.3 Exercise 9 — Reason about capacity
Compare (i) a linear classifier, (ii) a width-one ReLU hidden layer, (iii) a width-eight ReLU MLP, and (iv) a width-eight tanh MLP.
Which architectures can express a nonlinear decision boundary? Which cannot solve XOR exactly on all four binary inputs using a single thresholded scalar output?
What does increasing width change? Why does it not guarantee successful training?
Explain why the Universal Approximation Theorem does not promise that SGD will find suitable weights with a fixed budget.
NoteWorked solution 9
A linear classifier has an affine boundary and cannot solve XOR. A width-one ReLU model with an affine output and one threshold also cannot assign positive labels to both opposite XOR corners while rejecting the other two; its thresholded response depends on a single affine projection. Wider ReLU and tanh networks can represent nonlinear boundaries and, with suitable parameters, solve XOR. Width increases possible representations and parameter count, not guaranteed optimization quality or generalization. Universal approximation is an existence statement under its assumptions, not a convergence or finite-budget guarantee.
15.5 Optional computer investigation
This investigation uses only NumPy and Matplotlib. The network uses the same column-vector convention as the paper exercises; each input is a column of X. Check the gradients before training. The example trains with full-batch gradients; if you adapt it to sample-wise SGD, shuffle the sample order each epoch.
import numpy as npimport matplotlib.pyplot as pltX = np.array([[0., 0., 1., 1.], [0., 1., 0., 1.]])Y = np.array([[0., 1., 1., 0.]])def initialize(width, seed=9): rng = np.random.default_rng(seed)return [rng.normal(0, 0.5, (width, 2)), np.zeros((width, 1)), rng.normal(0, 0.5, (1, width)), np.zeros((1, 1))]def forward(params, x, activation="tanh"): w1, b1, w2, b2 = params h = w1 @ x + b1 a = np.tanh(h) if activation =="tanh"else np.maximum(h, 0)return w2 @ a + b2, (h, a)def loss_and_grads(params, x, y, activation="tanh"): pred, (h, a) = forward(params, x, activation) err = pred - y n = x.shape[1] loss = np.sum(err **2) / (2* n) d2 = err / n da = (1- a **2) if activation =="tanh"else (h >0) d1 = (params[2].T @ d2) * da grads = [d1 @ x.T, np.sum(d1, axis=1, keepdims=True), d2 @ a.T, np.sum(d2, axis=1, keepdims=True)]return loss, gradsdef check_gradients(params, activation="tanh", eps=1e-5): _, analytic = loss_and_grads(params, X, Y, activation) errors = []for p, g inzip(params, analytic):for idx in np.ndindex(p.shape): old = p[idx] p[idx] = old + eps lp = loss_and_grads(params, X, Y, activation)[0] p[idx] = old - eps lm = loss_and_grads(params, X, Y, activation)[0] p[idx] = old numeric = (lp - lm) / (2* eps) errors.append(abs(g[idx] - numeric) /max(1., abs(g[idx]), abs(numeric)))returnmax(errors)params = initialize(8)error = check_gradients(params)print("Maximum normalized gradient discrepancy:", error)assert error <1e-6
Maximum normalized gradient discrepancy: 1.5538459408048766e-11
Experiment. Predict whether changing hidden width from 2 to 8 improves XOR fit at a fixed training budget. Record the independent variable, initialization seed, optimizer, learning rate, steps, and final mean loss. Use several seeds before interpreting an architectural difference.
def train(width, seed=9, steps=4000, lr=0.1): params = initialize(width, seed) history = []for _ inrange(steps): loss, grads = loss_and_grads(params, X, Y) history.append(loss)for p, g inzip(params, grads): p -= lr * greturn params, np.asarray(history)fig, ax = plt.subplots(figsize=(7, 3.5))for width in (2, 8): fitted, history = train(width)print(f"width={width}: final loss={history[-1]:.6f}, predictions={forward(fitted, X)[0].round(3)}") ax.plot(history, label=f"width {width}")ax.set(xlabel="parameter updates", ylabel="mean half-squared error")ax.legend()plt.tight_layout()plt.show()
width=2: final loss=0.000000, predictions=[[0. 1. 1. 0.]]
width=8: final loss=0.000000, predictions=[[0. 1. 1. 0.]]
Figure 15.1: Training loss for two hidden widths under a fixed full-batch SGD budget.
To inspect the learned boundary, evaluate the fitted model on a dense grid of two-dimensional inputs and plot a contour at output \(0.5\). Since this is a squared-error model with an unconstrained output, treat \(0.5\) as a decision threshold, not a calibrated probability. Try a ReLU hidden activation, checking gradients away from kinks, or compare several initialization seeds with all other settings unchanged.
15.6 Expected observations
The numerical gradient discrepancy should be small for smooth tanh and moderate finite-difference steps. The loss should generally decrease during stable full-batch training, but neither architecture nor any single seed is guaranteed to reach a particular accuracy within the budget. Greater width changes expressive capacity and optimization behavior; a single run does not establish a general ranking. A learned XOR decision boundary is nonlinear when the four corners are classified correctly.
15.7 Check your understanding
W04-01: Why does an activation between affine layers matter?
W04-02: Where is the chain rule applied in the hidden delta?
W04-03: What independent evidence would convince you that your backward pass is correct?
W04-04: Why can two networks with adequate capacity train differently?