4.1 Multilayer Perceptrons

In Chapter 3, softmax regression scored each garment category by taking an affine weighted sum of the input pixels, oj=∑i=1dxiwij+bjo_j = \sum_{i=1}^d x_i w_{ij} + b_j. That linear form bakes in two severe restrictions:

  1. Monotonicity: Increasing feature xix_i always pushes ojo_j in the same direction (up if wij>0w_{ij} > 0, down if wij<0w_{ij} \lt 0). Yet many real relationships are non-monotonic: human health risk rises whenever body temperature strays from 37∘C37^\circ\textrm{C} in either direction.
  2. No feature interactions: Increasing xix_i by one unit changes ojo_j by wijw_{ij} regardless of the values of every other coordinate. In an image, however, a bright pixel at (13,17)(13, 17) means completely different things depending on whether the neighboring pixels form a collar, a sleeve, or a handbag strap.

Figure 4.1.1 plots the temperature example. The best linear score rises with temperature throughout, so it rates a patient with hypothermia as the safest of all.

Figure 4.1.1:

Health risk against body temperature. The risk is lowest near 37∘C37^\circ\textrm{C} and rises on both sides, whereas a linear score can only rise or fall. The dashed line is the least-squares linear fit over the plotted range.

A multilayer perceptron (MLP) overcomes both limitations by inserting one or more hidden layers that transform raw inputs into learned intermediate representations, applying an affine map followed by a nonlinear activation function before a linear output layer makes the final prediction. In this section, we prove that no linear model can solve the four-point XOR problem, solve XOR explicitly with two ReLU hidden units, examine what functions shallow and deep networks can represent, and compare the activation functions used across modern deep learning.

4.1.1 Limits of Linear Models: The XOR Problem#

The starkest possible demonstration of feature interaction uses just four data points: the corners of the unit square {0,1}2\{0, 1\}^2 labeled by their exclusive-OR (XOR), where y=1y = 1 if and only if exactly one coordinate equals 11:

x1x_1x2x_2yy
000
011
101
110

Notice the interaction: flipping x1x_1 from 00 to 11 increases yy when x2=0x_2 = 0, but decreases yy when x2=1x_2 = 1.

Proposition. For all w1,w2,b∈Rw_1, w_2, b \in \mathbb{R}, the linear decision rule "predict class 1 if w1x1+w2x2+b>0w_1 x_1 + w_2 x_2 + b > 0" misclassifies at least one of the four XOR points.

Proof. Suppose for contradiction that some w1,w2,bw_1, w_2, b classify all four corners correctly. The two class-1 points (0,1)(0, 1) and (1,0)(1, 0) require w2+b>0w_2 + b > 0 and w1+b>0w_1 + b > 0, whose sum gives w1+w2+2b>0w_1 + w_2 + 2b > 0. Meanwhile, the two class-0 points (0,0)(0, 0) and (1,1)(1, 1) require b≤0b \leq 0 and w1+w2+b≤0w_1 + w_2 + b \leq 0, whose sum gives w1+w2+2b≤0w_1 + w_2 + 2b \leq 0, an immediate contradiction. ■\blacksquare

Geometrically, both diagonals of the unit square share the midpoint (1/2,1/2)(1/2, 1/2) (Figure 4.1.2), where any affine function equals the average of its values at either diagonal's endpoints, so no straight line can ever separate the two diagonals.

Figure 4.1.2:

The four XOR points, labeled by class. Each diagonal joins the two points of one class, and the two diagonals cross at (1/2,1/2)(1/2, 1/2), so no straight line separates the classes.

4.1.2 Hidden Layers#

4.1.2.1 The Model#

To escape linearity, an MLP inserts one or more hidden layers between the input features and the output layer (Figure 4.1.3). For a minibatch design matrix X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} (nn examples, dd input features), a single hidden layer of width hh holds weights W(1)∈Rd×h\mathbf{W}^{(1)} \in \mathbb{R}^{d \times h} and biases b(1)∈Rh\mathbf{b}^{(1)} \in \mathbb{R}^h, while the output layer holds weights W(2)∈Rh×q\mathbf{W}^{(2)} \in \mathbb{R}^{h \times q} and biases b(2)∈Rq\mathbf{b}^{(2)} \in \mathbb{R}^q. The two-layer (one-hidden-layer) MLP computes

H=ϕ(XW(1)+b(1)),O=HW(2)+b(2),(4.1.1)\begin{aligned} \mathbf{H} &= \phi\left(\mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)}\right),\\ \mathbf{O} &= \mathbf{H}\mathbf{W}^{(2)} + \mathbf{b}^{(2)}, \end{aligned} \tag{4.1.1}

where biases broadcast across rows and the nonlinear activation function ϕ\phi acts elementwise on the pre-activations Z=XW(1)+b(1)\mathbf{Z} = \mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)} to produce the hidden activations H∈Rn×h\mathbf{H} \in \mathbb{R}^{n \times h}. Notice the parameter count: (d+1)h+(h+1)q(d + 1)h + (h + 1)q. On Fashion-MNIST (d=784,q=10d = 784, q = 10), a hidden layer of h=256h = 256 units has 785×256+257×10=203,530785 \times 256 + 257 \times 10 = 203{,}530 parameters, 26 times softmax regression's 7,8507{,}850.

Figure 4.1.3:

An MLP with 4 inputs, 1 hidden layer of 5 hidden units, and 3 outputs. Both parameterized layers are fully connected.

4.1.2.2 The Role of the Nonlinearity#

Why is the nonlinear activation ϕ\phi essential? Suppose we omitted ϕ\phi (setting ϕ(z)=z\phi(z) = z), so H=XW(1)+b(1)\mathbf{H} = \mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)}. Substituting H\mathbf{H} into the output equation collapses the two layers back into a single affine transformation:

O=(XW(1)+b(1))W(2)+b(2)=XW(1)W(2)⏟W+b(1)W(2)+b(2)⏟b.\mathbf{O} = \left(\mathbf{X}\mathbf{W}^{(1)} + \mathbf{b}^{(1)}\right)\mathbf{W}^{(2)} + \mathbf{b}^{(2)} = \mathbf{X}\underbrace{\mathbf{W}^{(1)}\mathbf{W}^{(2)}}_{\mathbf{W}} + \underbrace{\mathbf{b}^{(1)}\mathbf{W}^{(2)} + \mathbf{b}^{(2)}}_{\mathbf{b}}.

Without a nonlinearity, stacking any number of fully connected layers never expands the family of functions beyond a single linear layer (and if a hidden layer is narrower than min⁡(d,q)\min(d, q), it actually restricts W\mathbf{W} to low rank; see Exercise 1). Inserting an elementwise nonlinearity such as the rectified linear unit (ReLU),

ReLU(z)=max⁡(z,0),(4.1.2)\mathrm{ReLU}(z) = \max(z, 0), \tag{4.1.2}

prevents this algebraic collapse.

4.1.2.3 Solving XOR with Two ReLU Units#

With ReLU activations, a hidden layer of just h=2h = 2 units solves XOR cleanly (Goodfellow et al., 2016). Set

W(1)=(1111),b(1)=(0,−1),w(2)=(1,−2),b(2)=0.(4.1.3)\mathbf{W}^{(1)} = \begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}, \quad \mathbf{b}^{(1)} = (0, -1), \quad \mathbf{w}^{(2)} = (1, -2), \quad b^{(2)} = 0. \tag{4.1.3}

Both hidden units depend on the coordinate sum s=x1+x2s = x_1 + x_2: unit 1 computes h1=ReLU(s)=sh_1 = \mathrm{ReLU}(s) = s, while unit 2 computes h2=ReLU(s−1)h_2 = \mathrm{ReLU}(s - 1), turning on only when s=2s = 2 (at (1,1)(1, 1)) so that o=h1−2h2o = h_1 - 2h_2 subtracts 22 and folds the output back down to 00:

X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
W1, b1 = np.array([[1, 1], [1, 1]]), np.array([0, -1])
w2, b2 = np.array([1, -2]), 0
H = np.maximum(X @ W1 + b1, 0)  # hidden layer with ReLU
o = H @ w2 + b2  # output layer
for x, h, out in zip(X, H, o):
    print(f'x = {x}, h = {h}, o = {out}')
x = [0 0], h = [0 0], o = 0
x = [0 1], h = [1 0], o = 1
x = [1 0], h = [1 0], o = 1
x = [1 1], h = [2 1], o = 0

Look at the geometry in Figure 4.1.4: the hidden layer maps both class-1 corners (0,1)(0, 1) and (1,0)(1, 0) onto the exact same hidden point (1,0)(1, 0), allowing the straight line h1−2h2=1/2h_1 - 2h_2 = 1/2 in hidden space (right) to carve out the non-halfspace diagonal band 1/2<x1+x2<3/21/2 \lt x_1 + x_2 \lt 3/2 in input space (left).

Figure 4.1.4:

Solving XOR with two ReLU hidden units. Left: in input space (x1,x2)(x_1, x_2), the network predicts class 1 inside the diagonal band 1/2<x1+x2<3/21/2 \lt x_1 + x_2 \lt 3/2. Right: in hidden space (h1,h2)(h_1, h_2), the two class-1 points collapse onto (1,0)(1, 0), where a single line h1−2h2=1/2h_1 - 2h_2 = 1/2 separates the classes.

4.1.2.4 Deeper Networks#

More generally, a KK-layer MLP stacks K−1K - 1 hidden layers above H(0)=X\mathbf{H}^{(0)} = \mathbf{X},

H(k)=ϕ(H(k−1)W(k)+b(k))(k=1,…,K−1),O=H(K−1)W(K)+b(K),\begin{aligned} \mathbf{H}^{(k)} &= \phi\left(\mathbf{H}^{(k-1)}\mathbf{W}^{(k)} + \mathbf{b}^{(k)}\right) \quad (k = 1, \ldots, K-1), \\ \mathbf{O} &= \mathbf{H}^{(K-1)}\mathbf{W}^{(K)} + \mathbf{b}^{(K)}, \end{aligned}

building a compositional hierarchy of representations from raw inputs to class logits.

4.1.3 Expressive Power#

4.1.3.1 Universal Approximation#

How rich is the class of functions computable by a single hidden layer (K=2K = 2)? On the real line (d=1d = 1), each ReLU hidden unit aj ReLU(x−tj)a_j\,\mathrm{ReLU}(x - t_j) contributes a hinge that is flat to the left of its knot tjt_j and changes slope by aja_j to the right (Figure 4.1.5). Summing hh hinges plus a constant produces any continuous piecewise-linear polyline with hh interior knots; since any continuous function on a closed bounded interval [a,b][a, b] can be approximated uniformly to within any ϵ>0\epsilon > 0 by a fine enough polyline, a single wide enough ReLU hidden layer approximates any continuous 1D function to arbitrary precision.

Figure 4.1.5:

Approximating a smooth curve on an interval by a sum of ReLU hinges aj ReLU(x−tj)a_j\,\mathrm{ReLU}(x - t_j), one hidden unit per slope change.

The universal approximation theorem generalizes this fact to arbitrary input dimension dd: a single-hidden-layer MLP can approximate any continuous function on any compact subset of Rd\mathbb{R}^d to arbitrary uniform accuracy using any continuous non-polynomial activation function ϕ\phi (Cybenko, 1989; Leshno et al., 1993) (see Exercise 5 for a 2D proof via ridge functions and the Stone--Weierstrass theorem).

4.1.3.2 Depth and Space Folding#

If one hidden layer can already approximate anything, why build deep networks? Because universal approximation says nothing about how many units a single layer needs (which can grow exponentially in dd), nor whether gradient descent can learn or generalize from finite data.

Depth achieves exponential parameter efficiency by composing space-folding maps (Telgarsky, 2016). Consider the 1D tent function on [0,1][0, 1] computed by two ReLU units:

g(z)=2 ReLU(z)−4 ReLU(z−1/2),(4.1.4)g(z) = 2\,\mathrm{ReLU}(z) - 4\,\mathrm{ReLU}(z - 1/2), \tag{4.1.4}

which rises from 00 to 11 on [0,1/2][0, 1/2] and falls back to 00 on [1/2,1][1/2, 1] (Figure 4.1.6). Composing gg with itself folds [0,1][0, 1] in half at every layer: g∘gg \circ g has 44 linear pieces, g∘g∘gg \circ g \circ g has 88, and the mm-fold composition g∘mg^{\circ m}, computed by mm hidden layers of 22 ReLU units (2m2m total units), produces a sawtooth wave with 2m2^m linear pieces. Representing that same 2m2^m-piece sawtooth with a single hidden layer requires at least 2m−12^m - 1 hidden units (1,0231{,}023 units in one layer vs. 2020 units across 1010 layers when m=10m = 10).

Figure 4.1.6:

Composing the two-ReLU tent function gg with itself mm times doubles the number of linear segments at every layer, producing 2m2^m segments with only 2m2m hidden units.

4.1.4 Activation Functions#

While almost any non-polynomial ϕ\phi suffices for universal approximation, optimization via gradient descent depends critically on the derivative ϕ′(z)\phi'(z). For hidden unit jj with pre-activation zj=∑ixiwij(1)+bj(1)z_j = \sum_i x_i w^{(1)}_{ij} + b^{(1)}_j and activation hj=ϕ(zj)h_j = \phi(z_j), the chain rule scales every incoming weight gradient by the local slope ϕ′(zj)\phi'(z_j):

∂l∂wij(1)=∂l∂hj ϕ′(zj) xi.(4.1.5)\frac{\partial l}{\partial w^{(1)}_{ij}} = \frac{\partial l}{\partial h_j}\,\phi'(z_j)\,x_i. \tag{4.1.5}

Wherever ϕ′(zj)≈0\phi'(z_j) \approx 0, gradient flow stalls. Figure 4.1.7 compares the four principal activations and their derivatives.

Figure 4.1.7:

Four activation functions ϕ(z)\phi(z) (left) and their derivatives ϕ′(z)\phi'(z) (right): ReLU and GELU (top), sigmoid and tanh⁡\tanh (bottom).

  • ReLU and Leaky ReLU: ReLU(z)=max⁡(z,0)\mathrm{ReLU}(z) = \max(z, 0) has derivative 11 for z>0z > 0 and 00 for z<0z \lt 0 (conventionally 00 at z=0z = 0). Because its slope is identically 11 across the entire positive half-line, active ReLU units never attenuate gradients as zz grows (Nair and Hinton, 2010; Glorot et al., 2011). If a unit's weights shift so that z<0z \lt 0 on every training input, however, its gradient vanishes permanently (a dead ReLU); leaky ReLU, max⁡(z,αz)\max(z, \alpha z) with α≈0.01\alpha \approx 0.01, keeps a small positive slope for z<0z \lt 0 so dead units can recover.
  • GELU and SiLU (Swish): The Gaussian error linear unit GELU(z)=z Φ(z)\mathrm{GELU}(z) = z\,\Phi(z) (where Φ\Phi is the standard normal CDF) and its cousin SiLU(z)=z σ(z)\mathrm{SiLU}(z) = z\,\sigma(z) smooth out ReLU's kink at the origin (passing through z=0z = 0 with slope 1/21/2 and a gentle negative dip near z≈−0.75z \approx -0.75) and serve as the default activations in modern Transformers (Hendrycks and Gimpel, 2016).
  • Sigmoid and Tanh: The logistic sigmoid σ(z)=1/(1+e−z)∈(0,1)\sigma(z) = 1/(1 + e^{-z}) \in (0, 1) has derivative σ′(z)=σ(z)(1−σ(z))≤1/4\sigma'(z) = \sigma(z)(1 - \sigma(z)) \leq 1/4, while the zero-centered hyperbolic tangent tanh⁡(z)=(1−e−2z)/(1+e−2z)=2σ(2z)−1∈(−1,1)\tanh(z) = (1 - e^{-2z})/(1 + e^{-2z}) = 2\sigma(2z) - 1 \in (-1, 1) (Exercise 3) has derivative 1−tanh⁡2(z)≤11 - \tanh^2(z) \leq 1. Both saturate to flat horizontal asymptotes (ϕ′(z)→0\phi'(z) \to 0) as ∣z∣|z| grows beyond ∼3\sim 3, and multiplying σ′(z)≤1/4\sigma'(z) \leq 1/4 across KK layers shrinks gradients by at least 4−K4^{-K} (vanishing gradients, analyzed in Section 4.4). Today, sigmoid and tanh⁡\tanh are used primarily as bounded gates and state squashers in recurrent architectures (Chapter 12).

4.1.5 Summary#

Linear models are monotonic in every coordinate and cannot capture feature interactions such as XOR. Multilayer perceptrons overcome both limitations by inserting hidden layers H(k)=ϕ(H(k−1)W(k)+b(k))\mathbf{H}^{(k)} = \phi(\mathbf{H}^{(k-1)}\mathbf{W}^{(k)} + \mathbf{b}^{(k)}) before the linear output layer; without a nonlinear activation ϕ\phi, stacked affine transformations collapse into a single linear map. A single sufficiently wide hidden layer with any continuous non-polynomial activation can approximate any continuous function on a compact set, whereas composing mm hidden layers folds space repeatedly to create 2m2^m linear regions with O(m)O(m) units. Among activation functions, rectifiers such as ReLU (max⁡(z,0)\max(z, 0)) and GELU (zΦ(z)z\Phi(z)) maintain unit or near-unit slope on positive inputs, avoiding the tail saturation that attenuates gradients through deep stacks of sigmoid or tanh⁡\tanh units.

4.1.6 Exercises#

  1. Linear networks. Without activation functions, stacking layers composes affine maps into another affine map. Consider such a network with input dimension dd, output dimension qq, and hidden widths h1,…,hK−1h_1, \ldots, h_{K-1}. Show that it represents exactly the affine maps XW+b\mathbf{X}\mathbf{W} + \mathbf{b} whose weight matrix W\mathbf{W} has rank at most min⁡(h1,…,hK−1)\min(h_1, \ldots, h_{K-1}). Use this result to give an example in which adding a hidden layer to a linear model strictly shrinks its function class.

  2. XOR by hand. Figure 4.1.4 shows a two-unit ReLU network that computes XOR by mapping the two inputs of class 1 to the same hidden point.

    1. Find weights for a two-unit ReLU network that also computes XOR but maps the two inputs of class 1 to distinct hidden points, and verify it on the four inputs.
    2. Show that no network with a single ReLU hidden unit and a linear output classifies XOR correctly, for any threshold applied to its output.
  3. Sigmoid and tanh. The two squashing functions are closely related.

    1. Show that tanh⁡(z)=2σ(2z)−1\tanh(z) = 2\sigma(2z) - 1.
    2. Show that for every MLP with tanh hidden activations there is an MLP of the same architecture with sigmoid hidden activations that computes the same function, and conversely. State how the weights and biases change.
  4. Depth and linear pieces. ● A one-hidden-layer ReLU network with hh hidden units on the real line has at most h+1h + 1 linear pieces, while each composition with the two-unit tent of Figure 4.1.6 doubles the number of pieces. This problem makes the gain from depth exact for a network with three units per layer.

    1. Take three hidden units ReLU(wjx+bj)\mathrm{ReLU}(w_j x + b_j) with input weights w1=w2=1w_1 = w_2 = 1 and w3=−1w_3 = -1 and with joints −bj/wj-b_j/w_j at 1/61/6, 2/62/6, and 4/64/6. Choose output weights and an output bias so that the network's output ff takes the values 0,1,0,1,00, 1, 0, 1, 0 at x=0,1/6,2/6,4/6,1x = 0, 1/6, 2/6, 4/6, 1.
    2. Count the linear pieces of f∘ff \circ f on [0,1][0, 1], and of the mm-fold composition f∘⋯∘ff \circ \cdots \circ f. Explain, in terms of how composing with ff folds the graph, why each composition multiplies the count rather than adding to it.
    3. The mm-fold composition is computed by a network with mm hidden layers of three units each. How many hidden units would a network with a single hidden layer need to represent the same function? Compare the parameter counts of the two networks.

    Adapted from Simon Prince, Understanding Deep Learning, Problem 4.8.

  5. One hidden layer suffices. ● On the real line, a single hidden layer approximates a continuous function by a polyline, one hinge per joint. In the plane there are no joints to place, and the proof needs another idea: functions that vary along one direction only.

    1. Let ψ\psi be continuous on R\mathbb{R} and let w∈R2\mathbf{w} \in \mathbb{R}^2. Show that a single hidden layer approximates the ridge function ψ(w⊤x)\psi(\mathbf{w}^\top \mathbf{x}), which is constant along every line orthogonal to w\mathbf{w}, uniformly on any compact subset of the plane.
    2. The Stone–Weierstrass theorem states the following. Let a set of continuous functions on a compact set be closed under sums, products, and scalar multiples, contain the constants, and contain, for any two distinct points, a function that takes different values at them. Then every continuous function on the compact set is a uniform limit of functions in the set. Show that the finite linear combinations of cos⁡(ω⊤x)\cos(\boldsymbol{\omega}^\top \mathbf{x}) and sin⁡(ω⊤x)\sin(\boldsymbol{\omega}^\top \mathbf{x}), with ω∈R2\boldsymbol{\omega} \in \mathbb{R}^2, form such a set.
    3. Conclude that a single hidden layer approximates any continuous function on a compact subset of the plane.

    Adapted from Michael Nielsen, Neural Networks and Deep Learning, Chapter 4.

Discussions