15  Lab 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\).

  1. Express \(z\) as a single affine map of \(x\) and identify its effective weight and bias.
  2. Does adding more affine layers change this conclusion?
  3. Explain why a linear threshold applied to this output cannot classify all four XOR inputs.

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.

15.2.2 Exercise 2 — Build a representation of XOR

For \(x=(x_1,x_2)^T\in\{0,1\}^2\), define

\[ W_1=\begin{bmatrix}1&1\\1&1\end{bmatrix},\quad b_1=\begin{bmatrix}0\\-1\end{bmatrix},\quad a=\operatorname{ReLU}(W_1x+b_1),\quad \hat y=\begin{bmatrix}1&-2\end{bmatrix}a. \]

  1. Complete the table for all four inputs.
  2. Explain what each hidden neuron detects and why \(\hat y\) equals XOR on these inputs.
  3. 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)\)
\(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

  1. Evaluate ReLU and its derivative at \(z=-1,0,2\) using our convention.
  2. Evaluate \(\sigma(0)\) and \(\sigma'(0)\) for \(\sigma(z)=1/(1+e^{-z})\).
  3. Evaluate \(\tanh(0)\) and \(\tanh'(0)\).
  4. Why does the derivative of ReLU at zero require a convention? What can happen to a ReLU neuron whose preactivation remains negative?

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\).

  1. Draw the graph \(x\to u\to v\to L\) and evaluate each node.
  2. Starting at \(\partial L/\partial L=1\), calculate \(\partial L/\partial v\), \(\partial L/\partial u\), and \(\partial L/\partial x\).
  3. Verify your answer by differentiating \(L(x)=(2x+3)^2/2\) directly.

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:

\[ x=\begin{bmatrix}1\\2\end{bmatrix},\ y=1,\quad W_1=\begin{bmatrix}1&-1\\2&1\end{bmatrix},\quad b_1=\begin{bmatrix}0\\-1\end{bmatrix},\quad W_2=\begin{bmatrix}0.5&-0.5\end{bmatrix},\ b_2=0. \]

Set \(h=W_1x+b_1\), \(a=\operatorname{ReLU}(h)\), \(\hat y=W_2a+b_2\), and \(L=\frac12(\hat y-y)^2\).

  1. Calculate \(h,a,\hat y,L\).
  2. 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)\).
  3. Calculate \(\nabla_{W_2}L,\nabla_{b_2}L,\nabla_{W_1}L,\nabla_{b_1}L\) and state their shapes.

\(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\).

\[ \nabla_{W_2}L=\delta_2a^T=\begin{bmatrix}0&-7.5\end{bmatrix},\quad \nabla_{b_2}L=-2.5, \] \[ \nabla_{W_1}L=\delta_1x^T=\begin{bmatrix}0&0\\1.25&2.5\end{bmatrix},\quad \nabla_{b_1}L=\begin{bmatrix}0\\1.25\end{bmatrix}. \]

Their shapes match \(W_2:(1,2)\), \(b_2:(1,)\), \(W_1:(2,2)\), and \(b_1:(2,)\), respectively.

15.3.3 Exercise 6 — One SGD update

Using Exercise 5 and learning rate \(\eta=0.1\):

  1. Update every parameter simultaneously from the old parameters and gradients.
  2. Run a new forward pass on the same observation and compare losses.
  3. Why is computing a gradient not itself an optimization step? Does one decreasing loss guarantee convergence?

\[ W_1'=\begin{bmatrix}1&-1\\1.875&0.75\end{bmatrix},\quad b_1'=\begin{bmatrix}0\\-1.125\end{bmatrix},\quad W_2'=\begin{bmatrix}0.5&0.25\end{bmatrix},\quad b_2'=0.25. \]

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.

15.4 Part C: Verification and interpretation

15.4.1 Exercise 7 — Check numerical gradients

A central finite-difference estimate is

\[g_{\mathrm{FD}}(\theta_i)=\frac{L(\theta_i+\varepsilon)-L(\theta_i-\varepsilon)}{2\varepsilon}.\]

Use the normalized discrepancy \(r=|g-g_{\mathrm{FD}}|/\max(1,|g|,|g_{\mathrm{FD}}|)\).

  1. Calculate \(r\) for \((g,g_{\mathrm{FD}})=(1.25,1.24999)\) and \((-7.5,-7.49)\).
  2. Which is the more suspicious discrepancy?
  3. Explain why an excessively small \(\varepsilon\) and a ReLU kink can make numerical checking unreliable.

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:

h = W1 @ x + b1
a = np.maximum(h, 0)
delta1 = (W2.T * delta2).reshape(-1)  # suspicious
grad_W1 = np.outer(x, delta1)        # suspicious

Identify both errors, give corrected lines, and explain why a shape check alone cannot catch every incorrect derivative.

delta1 = (W2.reshape(-1) * delta2) * (h > 0)
grad_W1 = np.outer(delta1, x)

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.

  1. Which architectures can express a nonlinear decision boundary? Which cannot solve XOR exactly on all four binary inputs using a single thresholded scalar output?
  2. What does increasing width change? Why does it not guarantee successful training?
  3. Explain why the Universal Approximation Theorem does not promise that SGD will find suitable weights with a fixed budget.

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 np
import matplotlib.pyplot as plt

X = 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, grads

def check_gradients(params, activation="tanh", eps=1e-5):
    _, analytic = loss_and_grads(params, X, Y, activation)
    errors = []
    for p, g in zip(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)))
    return max(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 _ in range(steps):
        loss, grads = loss_and_grads(params, X, Y)
        history.append(loss)
        for p, g in zip(params, grads):
            p -= lr * g
    return 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.]]
Two curves of mean squared-error loss over parameter updates for widths two and eight.
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

  1. W04-01: Why does an activation between affine layers matter?
  2. W04-02: Where is the chain rule applied in the hidden delta?
  3. W04-03: What independent evidence would convince you that your backward pass is correct?
  4. W04-04: Why can two networks with adequate capacity train differently?