4.1 Multilayer Perceptrons
In Chapter 3, softmax regression scored each garment category by taking an affine weighted sum of the input pixels, . That linear form bakes in two severe restrictions:
- Monotonicity: Increasing feature always pushes in the same direction (up if , down if ). Yet many real relationships are non-monotonic: human health risk rises whenever body temperature strays from in either direction.
- No feature interactions: Increasing by one unit changes by regardless of the values of every other coordinate. In an image, however, a bright pixel at 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.
Health risk against body temperature. The risk is lowest near 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 labeled by their exclusive-OR (XOR), where if and only if exactly one coordinate equals :
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
Notice the interaction: flipping from to increases when , but decreases when .
Proposition. For all , the linear decision rule "predict class 1 if " misclassifies at least one of the four XOR points.
Proof. Suppose for contradiction that some classify all four corners correctly. The two class-1 points and require and , whose sum gives . Meanwhile, the two class-0 points and require and , whose sum gives , an immediate contradiction.
Geometrically, both diagonals of the unit square share the midpoint (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.
The four XOR points, labeled by class. Each diagonal joins the two points of one class, and the two diagonals cross at , 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 ( examples, input features), a single hidden layer of width holds weights and biases , while the output layer holds weights and biases . The two-layer (one-hidden-layer) MLP computes
where biases broadcast across rows and the nonlinear activation function acts elementwise on the pre-activations to produce the hidden activations . Notice the parameter count: . On Fashion-MNIST (), a hidden layer of units has parameters, 26 times softmax regression's .
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 essential? Suppose we omitted (setting ), so . Substituting into the output equation collapses the two layers back into a single affine transformation:
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 , it actually restricts to low rank; see Exercise 1). Inserting an elementwise nonlinearity such as the rectified linear unit (ReLU),
prevents this algebraic collapse.
4.1.2.3 Solving XOR with Two ReLU Units#
With ReLU activations, a hidden layer of just units solves XOR cleanly (Goodfellow et al., 2016). Set
Both hidden units depend on the coordinate sum : unit 1 computes , while unit 2 computes , turning on only when (at ) so that subtracts and folds the output back down to :
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 and onto the exact same hidden point , allowing the straight line in hidden space (right) to carve out the non-halfspace diagonal band in input space (left).
Solving XOR with two ReLU hidden units. Left: in input space , the network predicts class 1 inside the diagonal band . Right: in hidden space , the two class-1 points collapse onto , where a single line separates the classes.
4.1.2.4 Deeper Networks#
More generally, a -layer MLP stacks hidden layers above ,
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 ()? On the real line (), each ReLU hidden unit contributes a hinge that is flat to the left of its knot and changes slope by to the right (Figure 4.1.5). Summing hinges plus a constant produces any continuous piecewise-linear polyline with interior knots; since any continuous function on a closed bounded interval can be approximated uniformly to within any by a fine enough polyline, a single wide enough ReLU hidden layer approximates any continuous 1D function to arbitrary precision.
Approximating a smooth curve on an interval by a sum of ReLU hinges , one hidden unit per slope change.
The universal approximation theorem generalizes this fact to arbitrary input dimension : a single-hidden-layer MLP can approximate any continuous function on any compact subset of to arbitrary uniform accuracy using any continuous non-polynomial activation function (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 ), 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 computed by two ReLU units:
which rises from to on and falls back to on (Figure 4.1.6). Composing with itself folds in half at every layer: has linear pieces, has , and the -fold composition , computed by hidden layers of ReLU units ( total units), produces a sawtooth wave with linear pieces. Representing that same -piece sawtooth with a single hidden layer requires at least hidden units ( units in one layer vs. units across layers when ).
Composing the two-ReLU tent function with itself times doubles the number of linear segments at every layer, producing segments with only hidden units.
4.1.4 Activation Functions#
While almost any non-polynomial suffices for universal approximation, optimization via gradient descent depends critically on the derivative . For hidden unit with pre-activation and activation , the chain rule scales every incoming weight gradient by the local slope :
Wherever , gradient flow stalls. Figure 4.1.7 compares the four principal activations and their derivatives.
Four activation functions (left) and their derivatives (right): ReLU and GELU (top), sigmoid and (bottom).
- ReLU and Leaky ReLU: has derivative for and for (conventionally at ). Because its slope is identically across the entire positive half-line, active ReLU units never attenuate gradients as grows (Nair and Hinton, 2010; Glorot et al., 2011). If a unit's weights shift so that on every training input, however, its gradient vanishes permanently (a dead ReLU); leaky ReLU, with , keeps a small positive slope for so dead units can recover.
- GELU and SiLU (Swish): The Gaussian error linear unit (where is the standard normal CDF) and its cousin smooth out ReLU's kink at the origin (passing through with slope and a gentle negative dip near ) and serve as the default activations in modern Transformers (Hendrycks and Gimpel, 2016).
- Sigmoid and Tanh: The logistic sigmoid has derivative , while the zero-centered hyperbolic tangent (Exercise 3) has derivative . Both saturate to flat horizontal asymptotes () as grows beyond , and multiplying across layers shrinks gradients by at least (vanishing gradients, analyzed in Section 4.4). Today, sigmoid and 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 before the linear output layer; without a nonlinear activation , 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 hidden layers folds space repeatedly to create linear regions with units. Among activation functions, rectifiers such as ReLU () and GELU () maintain unit or near-unit slope on positive inputs, avoiding the tail saturation that attenuates gradients through deep stacks of sigmoid or units.
4.1.6 Exercises#
-
Linear networks. Without activation functions, stacking layers composes affine maps into another affine map. Consider such a network with input dimension , output dimension , and hidden widths . Show that it represents exactly the affine maps whose weight matrix has rank at most . Use this result to give an example in which adding a hidden layer to a linear model strictly shrinks its function class.
-
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.
- 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.
- Show that no network with a single ReLU hidden unit and a linear output classifies XOR correctly, for any threshold applied to its output.
-
Sigmoid and tanh. The two squashing functions are closely related.
- Show that .
- 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.
-
Depth and linear pieces. ● A one-hidden-layer ReLU network with hidden units on the real line has at most 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.
- Take three hidden units with input weights and and with joints at , , and . Choose output weights and an output bias so that the network's output takes the values at .
- Count the linear pieces of on , and of the -fold composition . Explain, in terms of how composing with folds the graph, why each composition multiplies the count rather than adding to it.
- The -fold composition is computed by a network with 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.
-
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.
- Let be continuous on and let . Show that a single hidden layer approximates the ridge function , which is constant along every line orthogonal to , uniformly on any compact subset of the plane.
- 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 and , with , form such a set.
- 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.