MLPs and universal approximation
Before this lesson: matrices as maps (linear algebra, lesson 01) and rank (linear algebra, lesson 02); logistic and softmax regression (ml-fundamentals track); functions, sets and the notation (foundations track). This is the first lesson of the track. Time: about 65 minutes, plus the notebook.
Why this matters #
Every architecture in this track is built from multilayer perceptrons (MLPs). The feed-forward block of a transformer is a two-layer MLP and holds about 2/3 of the weights of a standard block. Physics-informed neural networks (PINNs) and neural fields are MLPs that take coordinates as input, and the branch and trunk networks of DeepONet are usually MLPs. When someone asks "why can a network fit this?", the usual answer is the universal approximation theorem. You should know exactly how weak this answer is: it promises existence, nothing more. Depth separation is the first precise reason to prefer deep networks over wide ones.
1. Predict first #
2. The picture #
One unit is a hinge #
The rectified linear unit is . One unit with one input computes . The inside, , is zero at . On one side of this point the unit outputs 0; on the other side it outputs the straight line . We call this graph a hinge and the point its joint.
Example: has its joint at . For it is 0; for it is , a line with slope 2. If , the sides swap: is for and for .
A hidden layer adds hinges #
A network with one hidden layer of units and one output computes
Each term is a hinge scaled by its output weight . A sum of hinges is continuous and piecewise linear. Each unit adds at most one joint, so has at most joints and at most linear pieces. Between two joints nothing bends, so is a straight line there.
How to "connect the dots". Take four points: , , , . The straight lines between them have slopes , , . Build from left to right:
- Start at with a unit and output weight . Now the slope is , which is right on .
- At the slope must change from to . Add with output weight .
- At the slope must change from to . Add with output weight .
So . Check: , , . Each output weight is a change of slope. That is the whole idea of the construction in section 3. More points give more units and a closer fit to a smooth curve.
Fit with ReLU units. The aqua curve is the target ; the blue curve is the network ; the thin blue lines are its single units ; the violet knots set the weights; the magenta bar is the largest error. Predict first: if you double the number of units , by what factor does the largest error fall? Then move the slider from 2 to 4 to 8. Try , and the step, which is not continuous: its error never falls below . Outside the network is a straight line.
Depth folds, width only adds #
A second hidden layer applies hinges to the output of the first layer, not to . Suppose the first layer outputs a function that goes up and then down on . It folds the interval: two different inputs give the same value. Every hinge in the next layer then acts on both halves at the same time. So the pieces multiply from layer to layer, while inside one layer they only add.
The cleanest example is the tent map . On it is (up from 0 to 1); on it is (down from 1 to 0). It uses 2 units. Apply it twice: goes up and down twice, so it has 4 pieces. Each new layer of 2 units doubles the number of pieces.
Pieces multiply with depth. Move the slider . Top left: the deep network (blue) with hidden layers of 2 units has pieces. Top right: a network with one hidden layer and the same units (grey) can have at most pieces; here it passes through points of the aqua target . It is exact for and then fails (largest error in magenta). Bottom: pieces against units on a log scale; the yellow line is the current .
Without an activation nothing folds #
If we remove the activation, every layer is an affine map , and an affine map of an affine map is affine. Straight lines stay straight, parallel lines stay parallel, and the midpoint of a segment goes to the midpoint of its image. No number of layers changes this.
Three layers, with and without ReLU. A grid of inputs in goes through three layers . With "none", the image after every layer is a grid of parallelograms, and the readout shows the single affine map that does the same job. Switch to ReLU and look at layer 1 first: the parts of the plane where a unit is negative are flattened onto an axis. The yellow segment – (drag its ends in the input view) stays straight only without ReLU; the midpoint test measures the gap between the image of the midpoint and the midpoint of the images.
A one-hidden-layer ReLU network has 3 hidden units with joints at , and , and all output weights are nonzero. How many linear pieces does have on ?
Three joints cut the real line into 4 intervals, and is a straight line on each one. Pieces double only when a layer folds the input; inside one layer, each unit adds one joint, so units give at most pieces.
Where is the joint of , and on which side is it zero?
The inside is zero at , and it is negative for , where ReLU returns 0. With a negative input weight the flat side is on the right.
3. Definitions and main results #
The multilayer perceptron #
We use the row-vector convention of PyTorch. A mini-batch of inputs is a matrix , one example per row. For :
with weights , biases , the column of ones (it adds to every row), and an activation applied entry by entry. The last layer has no activation: is the output (the logits for classification, followed by a softmax in the loss; lesson 02).
- is the depth: the number of affine layers. (Do not mix it with the loss .)
- is the width of layer . Layers are the hidden layers.
- is the pre-activation and the activation of layer . Shapes: .
Parameter count. Layer has weights and biases, so
Example: has parameters.
Example: the transformer feed-forward block. With model width and hidden width , the block is . Its parameter count is . The attention projections have , and two LayerNorms have . So the feed-forward part is about of a block (lesson 11). For it has parameters.
How many parameters (weights and biases) does an MLP have?
Each layer has parameters: the "+1" is the bias of each output unit. and . The first option forgets the biases; the third multiplies the widths, which is not how layers combine.
Collapse without nonlinearity #
Proposition. If is the identity, the network is one affine map with , and .
Proof.
- Two layers: . This is affine, with weight and bias .
- Induction on : if the first layers are one affine map, adding layer is step 1 again.
- Rank: (linear algebra, lesson 01), and . So the product has rank at most the smallest width.
So a deep linear classifier is just softmax regression, possibly with a rank bottleneck. (Its training problem is still non-convex in , which is why deep linear networks are a useful model for studying optimization.)
The universal approximation theorem #
A set is compact if it is closed and bounded, for example a cube . The sup norm of an error is its largest absolute value over : . A small sup norm means the approximation is good everywhere on , not only on average.
Theorem (universal approximation; Leshno, Lin, Pinkus and Schocken, 1993). Let be continuous and not a polynomial. For every compact set , every continuous and every there are and , with
In words: one hidden layer is enough to approximate any continuous function on a compact set, to any accuracy, if the activation is not a polynomial. ReLU, tanh, the logistic sigmoid and GELU all qualify. Cybenko (1989) proved the first version for sigmoid-like , and Hornik (1991) for continuous, bounded, non-constant .
Why polynomials fail. If is a polynomial of degree , then each is a polynomial in of degree at most , and so is every sum of them, for any . These polynomials form a finite-dimensional subspace of the continuous functions. A finite-dimensional subspace is closed, so it cannot come arbitrarily close to functions outside it, such as on a cube.
Why is not a universal activation, even with very many hidden units?
More units give more polynomials of degree , and a sum of them is still a polynomial of degree . Such functions cannot approximate, for example, on . ReLU is also unbounded, and GELU is not monotone, yet both are universal: the real condition is "not a polynomial".
The 1-D ReLU case by construction #
For ReLU in one dimension we can prove the theorem with our own hands. The idea is the "connect the dots" construction of section 2.
Theorem (exact interpolation). Take knots with values , and let be the piecewise-linear interpolant (straight lines between the points). Let be the slope on , for . Then
equals on . It is a one-hidden-layer network with units: input weights 1, biases , output weights and , and output bias .
Proof.
- is continuous and piecewise linear, with joints only at .
- At every ReLU is zero, so .
- Take in an interval . The units with joints are active (each has slope 1), and the others are zero. So the slope of there is . The sum telescopes: every middle term cancels.
- and start at the same value and have the same slope on every interval, so they are equal on .
Theorem (approximation of any continuous on ). For every continuous and every there is a one-hidden-layer ReLU network with .
Proof.
- A continuous function on a closed, bounded interval is uniformly continuous: there is such that implies .
- Choose knots with spacing less than . Set and let be the interpolant. By the previous theorem, is a ReLU network.
- For , for some . Then , because is within of both knots.
Rate. For a twice-differentiable and knot spacing , the interpolation error is at most . Halve (twice the units) and the error falls by a factor 4. In dimensions, a grid of spacing has about cells, so a grid-based construction needs a number of units that grows exponentially with : the curse of dimensionality.
What the theorem does not give #
- Width. can be huge, exponential in in the worst case.
- Learnability. The weights exist; nothing says gradient descent finds them. For example, networks trained by gradient descent fit low frequencies first (spectral bias, Rahaman et al. 2019), so fine details can take very long to learn.
- Generalization. The theorem approximates a known . It says nothing about learning from finite, noisy samples (lesson 17).
- Outside . No control at all. Far from its joints, a ReLU network is affine.
Barron's theorem: a rate without the explicit
Barron (1993) gives a rate that does not show in the exponent. Let be the Fourier transform of and (finite for "smooth enough" functions). Then for every probability measure on the ball of radius there is a one-hidden-layer sigmoidal network with units and
The mean squared error falls like in any dimension. The catch: itself can grow quickly with for many functions, so the curse of dimensionality moves into the constant.
Depth separation #
Shallow, 1-D. ReLU units in one hidden layer give at most pieces (section 2).
Theorem (pieces of a deep ReLU network, 1-D input). A network with hidden layers of width has at most linear pieces.
Proof.
- After the first hidden layer, every unit output is piecewise linear in , with at most pieces in total (all joints together).
- Suppose that after layer all unit outputs are linear on each of pieces. A unit of layer computes of an affine combination of these outputs. On each piece, the combination is a linear function of , so the ReLU adds at most one joint inside that piece.
- The units of layer add at most joints inside each piece, which splits it into at most pieces. So after layer there are at most pieces.
- Start with (no layer yet) and repeat times: at most . The output layer is affine and adds no joint.
The tent map reaches exponential growth. maps onto twice (once going up, once going down). So every composition doubles the pieces: the -fold composition is a sawtooth with pieces. Its values are at . It uses hidden layers of 2 units ( units). A network with one hidden layer needs joints, so at least units, to represent it.
Telgarsky's theorem and a caveat
Telgarsky (2016) turns the sawtooth into an approximation result. For every there are functions computed by networks with layers and units per layer that networks with layers cannot approximate (in the sense, up to a fixed constant error) unless they have units. The proof counts oscillations: a shallow network cannot cross a level often enough.
A caveat (Prince, Understanding Deep Learning, §4.5): the regions of a deep network are strongly dependent on each other, because later layers reuse the same folds. More regions help only if the target has matching structure, such as composition, repetition or symmetry. "More regions" is not the same as "more useful capacity".
Answers to section 1. (1) Only affine maps , with at most the smallest width. The ten layers add nothing that one layer cannot do. (2) Network B. The tent-map construction gives pieces with 20 units, while A has at most pieces.
What does the universal approximation theorem guarantee for a continuous on ?
The theorem is a pure existence statement on a compact set. It gives no bound on the width, no statement about training, data or generalization, and no control outside the set.
4. Worked example #
Approximate on with a ReLU network.
Knots (spacing ). The values are . The slopes are and . The output weights are and , so
This is a network with two hidden units: input weights , biases , output weights , output bias 0.
- Values. . . . ✓
- Slopes. On only is active: slope 1. On both are active: slope . ✓
- Error. At : , , error . The bound is . It is reached at the midpoints and .
Knots (spacing ). The values are . The slopes are . The output weights are and the slope changes , , :
The largest error is : twice the units give a quarter of the error (the rate). This network has units and parameters (an input weight, a bias and an output weight per unit, plus the output bias).
5. In code #
PyTorch and NumPy check the counts, the collapse, the worked example and the tent map.
import numpy as np
import torch
from torch import nn
torch.manual_seed(0)
# 1. Parameter count of a transformer-style FFN, D = 1024, hidden width 4D.
ffn = nn.Sequential(nn.Linear(1024, 4096), nn.GELU(), nn.Linear(4096, 1024))
print(sum(p.numel() for p in ffn.parameters())) # 8393728 = 8 D^2 + 5 D
# 2. Without the nonlinearity, two layers are one affine map.
f1, f2 = nn.Linear(5, 7), nn.Linear(7, 3)
x = torch.randn(4, 5)
W = f2.weight @ f1.weight # PyTorch layout: (out, in)
b = f2.weight @ f1.bias + f2.bias
print(torch.allclose(f2(f1(x)), x @ W.T + b, atol=1e-6)) # True
# 3. The worked example: N(x) = relu(x) + 2 relu(x - 1) against x^2 on [0, 2].
xs = np.linspace(0, 2, 2001)
N = np.maximum(xs, 0) + 2 * np.maximum(xs - 1, 0)
print(np.abs(N - xs**2).max()) # 0.25 (at x = 0.5 and x = 1.5)
# 4. Depth: k compositions of the tent map t(x) = 2 relu(x) - 4 relu(x - 1/2).
t = lambda u: 2 * np.maximum(u, 0) - 4 * np.maximum(u - 0.5, 0)
grid = np.linspace(0, 1, 2**12 + 1) # dyadic grid: contains every joint
for k in (1, 3, 10):
y = grid.copy()
for _ in range(k):
y = t(y)
slopes = np.diff(y) / np.diff(grid)
pieces = 1 + np.count_nonzero(np.abs(np.diff(slopes)) > 1e-9)
print(k, 2 * k, pieces) # 1 2 2 / 3 6 8 / 10 20 1024
The FFN count is . The last loop prints 2, 8 and 1024 pieces for 2, 6 and 20 units.
6. Where it shows up #
- Transformers. Each block has the feed-forward MLP with weights, against for the attention projections (lesson 11). Mixture-of-experts layers replace this one MLP by many (lesson 15).
- Classifiers and regressors. An MLP on top of features is the standard "head" of a vision or language model; a linear probe is the special case with no hidden layer (lesson 14).
- ML for science. PINNs and neural fields are coordinate MLPs. The theorem says a solution can be represented; it does not say it can be learned. Spectral bias is why Fourier features (Tancik et al. 2020) or sine activations (SIREN, Sitzmann et al. 2020) are used for fields with fine scales.
- Operator learning. Chen and Chen (1995) proved a universal approximation theorem for nonlinear operators. It is the theory behind DeepONet (Lu et al. 2021).
- Architecture design. Depth against width is a design choice with a theory behind it: for a fixed parameter budget, deeper ReLU networks can produce far more linear regions (Prince, Fig. 4.7).
7. Common mistakes #
- Forgetting the biases in the parameter count. Each layer has parameters, not .
- Putting an activation on the output layer. The last layer outputs logits or real values; a ReLU there would make negative outputs impossible.
- "Universal approximation means a network can learn anything." It is an existence result: no width bound, no training guarantee, no statement about data.
- Dropping the conditions. A ReLU network cannot approximate or uniformly on all of : it is affine outside a bounded interval. The domain must be compact, and the target continuous.
- Stacking linear layers "for capacity". Without they collapse to one affine map, with rank at most the narrowest width.
- Counting regions as capacity. The many regions of a deep network depend strongly on each other.
8. Check yourself #
- How many parameters does an MLP with biases have?
Answer
. - Why does a polynomial activation fail the theorem?
Answer
With of degree , every one-hidden-layer network is a polynomial of degree at most , for any width. These polynomials form a finite-dimensional, closed subspace of the continuous functions on , which is not dense: it misses, for example, on an interval. - In the worked example, how many hidden units does the uniform grid need for a largest error of at most on ?
Answer
gives , so . Then cells and 100 hidden units. - Describe for the tent map on .
Answer
A sawtooth with 4 pieces: values at , slopes . - Can a ReLU network approximate uniformly on all of ?
Answer
No. Beyond its last joint the network is affine. If the slope there is nonzero, the error grows without bound. If it is zero, the network is a constant there, and . - A linear autoencoder has no activations. Which maps can it represent?
Answer
Only affine maps with . Trained with squared error on centered data, its best solution projects onto the top-64 principal subspace, as PCA does ([linear algebra, lesson 09](/linear-algebra/09-pca-randomized-svd/)).
State the universal approximation theorem (Leshno et al. 1993) with its conditions.
If is continuous and not a polynomial, then for every continuous on a compact and every , some one-hidden-layer network is within of everywhere on .
Why does an MLP without activations collapse to one layer?
An affine map of an affine map is affine: . By induction the whole network is with .
Where is the joint of ?
At , where . On one side the unit is 0, on the other it is the line .
At most how many linear pieces does a one-hidden-layer ReLU network with units have?
: each unit adds at most one joint.
In the interpolating ReLU network through knots with slopes , what is the output weight of the unit with joint ?
and : the change of slope at that knot. The slopes telescope.
How many linear pieces does the tent map composed times have, and how many ReLU units does it use?
pieces with hidden layers of 2 units, so units. One hidden layer would need at least units.
Count the parameters of the transformer feed-forward block .
, about 2/3 of a transformer block.
Name three things the universal approximation theorem does not give.
A bound on the width; a guarantee that training (gradient descent) finds the weights; anything about generalization from finite data (and nothing outside the compact set).
Piecewise-linear interpolation of a smooth with knot spacing : what is the error bound, and what happens when you double the number of units?
At most . Doubling the units halves , so the error falls by a factor 4.
What is the parameter count of an MLP with widths ?
: weights plus one bias per output unit in each layer.
9. Interview angle #
- "Why do we need nonlinearities?" — Without them, any depth collapses to one affine map, with rank at most the narrowest width.
- "State the universal approximation theorem. Why use deep networks then?" — One hidden layer with a non-polynomial activation approximates any continuous function on a compact set. It is existence only, with no width bound. Depth can be exponentially more efficient (the sawtooth), and in practice deep networks train and generalize better.
- "How many linear regions does a ReLU network have?" — In 1-D: at most for one layer of units, at most for layers of width ; the tent map reaches with units.
- "Count the parameters of this MLP." — . Do not forget the biases.
- "Can a ReLU network extrapolate ?" — No: far from its joints it is affine, so it grows linearly, not quadratically.
10. Practice #
The notebook for this lesson runs in Colab. It uses NumPy (PyTorch only for one optional check). Each exercise has a check cell and a folded solution:
mlp_forward: the forward pass of an MLP in the row convention, with the shapes of every layer.count_params: the parameter count, checked against the formula (and againstnn.Sequentialwhen PyTorch is installed).relu_interpolant: the weights of the one-hidden-layer network through given knots, checked to be exact on the knots.- The error of the interpolant of against the number of units: measure the slope on a log-log plot and compare it with the rate.
sawtooth: build as a deep network with units and count its pieces.
11. Watch and read #
- Michael Nielsen, Neural Networks and Deep Learning, chapter 4: A visual proof that neural nets can compute any function (free online book): the same construction with step-like units.
- Simon Prince, Understanding Deep Learning (free PDF): chapter 3 (shallow networks, universal approximation) and chapter 4, §4.5 (shallow against deep, linear regions). The notebooks for chapter 3 draw the regions of small networks.
- Matus Telgarsky, Benefits of depth in neural networks (2016): §1.1 and §3 (the triangle maps and the oscillation count).
- The theorem of section 3: Leshno, Lin, Pinkus and Schocken, "Multilayer feedforward networks with a nonpolynomial activation function can approximate any function", Neural Networks 6 (1993). The journal version is not free; chapter 3 of Prince's book above gives the statement and the references.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.