From Perceptrons to Deep Networks
Neurons, layers, activations and what networks can represent.
Alternate weighted sums with a simple nonlinearity, layer after layer, and you get a function flexible enough to fit almost anything. This lesson writes the multilayer perceptron down precisely: the forward pass in matrix form, the activations and why one is needed at all, the output layers and the losses that belong with them, the parameter count, and the theorem that says one hidden layer can approximate any continuous function, along with the fine print that limits what it promises.
What you’ll learn
- Express an MLP's forward pass as matrix products, for a single input and for a whole batch, and count its parameters and multiply–adds.
- Prove that a composition of affine layers is affine, and compare sigmoid, tanh, ReLU and GELU by range, derivative and saturation.
- Pair output layers with losses (identity with squared error, sigmoid or softmax with cross-entropy) and derive the softmax cross-entropy gradient .
- State the universal approximation theorem with its conditions, build any one-dimensional piecewise-linear function from ReLU units, and explain what depth adds and what the theorem leaves open.
Layers in matrix form
A multilayer perceptron with hidden layers of widths maps an input (write ) to output scores by alternating affine maps and an elementwise nonlinearity , the activation function:
with and . Row of holds the incoming weights of neuron in layer . The vector is the layer's pre-activation, its activation, and the last layer has no of its own: the loss decides how its scores (the logits) are read.
For a mini-batch of examples stacked as the rows of , as in a design matrix, every layer becomes one matrix–matrix product, with . That single shape, a big matrix multiply followed by an elementwise function, is what graphics processors are built to do fast.
import numpy as np
def init_mlp(sizes, rng):
"""sizes = [d, n1, ..., nL, k]; one (W, b) pair per layer."""
return [(rng.normal(0.0, np.sqrt(2.0 / m), size=(n, m)), np.zeros(n))
for m, n in zip(sizes[:-1], sizes[1:])]
def forward(params, X):
"""X has shape (B, d), one example per row; returns (B, k) logits."""
H = X
for W, b in params[:-1]:
H = np.maximum(0.0, H @ W.T + b) # affine map, then ReLU
W, b = params[-1]
return H @ W.T + b # output scores: no activation
rng = np.random.default_rng(0)
params = init_mlp([784, 256, 128, 10], rng)
logits = forward(params, rng.normal(size=(32, 784))) # shape (32, 10)A ReLU network for images and 10 classes. The weights start Gaussian with variance , the He initialization whose reason is given in Initialization & Signal Propagation.
How many parameters does the network above (layer sizes 784, 256, 128, 10, with biases) have? Answer in thousands.
Show the answer
235 thousand
A layer from to units has weights and biases: , then , then , for a total of . Over 85% of them sit in the first layer, because it touches every pixel. The forward pass costs one multiply–add per weight per example, about , so the parameter count also measures the compute.
Why the nonlinearity, and which one
Two affine layers with nothing between them form one affine layer:
By induction, any depth of affine layers computes with . A narrow layer also caps the rank, since the rank of a product is at most the rank of each factor:
So a deep linear network represents exactly the affine maps whose linear part has rank at most its narrowest width: depth adds no new functions, only a new parameterization (one that makes the training loss non-convex, a fact studied in its own right). Every gain in expressive power comes from .
| Activation | Range | Notes | ||
|---|---|---|---|---|
| Sigmoid | Saturates: . Outputs are not centered at 0. Now used mainly for gates and binary outputs. | |||
| Zero-centered, slope 1 at the origin, but saturates too: . | ||||
| ReLU | if , if | No saturation for , cheap, sparse activations. A unit whose pre-activation is negative on every input gets zero gradient ("dead"). | ||
| Leaky ReLU | , | or | Keeps a small gradient for , so units cannot die. | |
| GELU | Smooth and slightly non-monotone (minimum at ); and are the distribution function and density of . Common in transformers (Hendrycks & Gimpel, 2016). |
During training, one ReLU unit's pre-activation becomes negative for every training example. What happens to its incoming weights under gradient descent from then on?
- They keep changing, because the loss still depends on them
- They receive zero gradient on every example, so they stop changing and the unit stays silent
- They grow until the unit switches back on
- They are reset automatically to their initial values
Show the answer
B. They receive zero gradient on every example, so they stop changing and the unit stays silent
The unit's output is with derivative wherever , so the chain rule multiplies every gradient flowing into its weights by zero. Nothing pushes them back, so the unit is "dead". Leaky ReLU, careful initialization and moderate learning rates make this rarer.
Output layers and losses
The output layer and the loss are chosen together, as the negative log-likelihood of a probability model for given the logits :
- Regression: identity output and the squared loss , the negative log-likelihood of a Gaussian with fixed variance, up to constants.
- Two classes (): and the log loss , the Bernoulli likelihood. On the last hidden layer's features this is exactly logistic regression.
- classes: the softmax and the cross-entropy , the categorical likelihood, with one-hot as .
Write the loss for true class directly in terms of the logits:
Differentiate with respect to . The first term gives when and 0 otherwise; differentiating the log-sum-exp gives the softmax:
So : prediction minus target. The same form holds for sigmoid with log loss () and identity with squared loss (), because each pairs a likelihood with its canonical link (Generalized Linear Models). Contrast a sigmoid output trained with squared loss: an extra factor appears, and it is nearly zero whenever is large, including when the unit is confidently wrong:
A three-class network outputs logits . What softmax probability does it give the first class, in percent?
Show the answer
67 %
, and sum to , so . If the first class is correct, the loss is and the logit gradient is : a descent step raises the correct logit and lowers the others in proportion to their probabilities. Shifting all three logits by one constant would leave unchanged, since softmax depends only on differences.
What one hidden layer can represent
Why do polynomials fail? Suppose is a polynomial of degree . Then each unit , viewed as a function of , is a polynomial of degree or less, and finite sums of units stay in that class. They all live in one finite-dimensional space, which cannot approximate, say, on . Every other continuous activation escapes this trap; the proof is in Universal Approximation & Depth. For ReLU the escape is easy to see by construction:
Take knots , values , and slopes . One hidden layer of ReLU units and an output bias define
On only the first unit is active, which gives the first segment. The unit anchored at is zero to the left of its knot and from there on adds to the slope; it starts from 0, so stays continuous and passes through every :
Let interpolate a continuous at knots spaced apart. On each piece, is a weighted average of and , both within of . Uniform continuity makes , so one hidden layer of ReLUs approximates any continuous function on an interval:
Think first Using as few ReLU units as possible, write , and a triangular bump that rises from 0 at to 1 at and falls back to 0 at .
: two units. The bump is : three units, one per kink. Sums of shifted, scaled bumps are another route to universality, and the count makes the cost visible: one unit per kink in one dimension. In dimensions a grid of width- bumps has about cells, so this route needs at least that many units: the curse of dimensionality, which Barron's theorem (in the Convergence lesson) sidesteps for a special class of functions.
Depth versus width. The theorem bounds the error but not the width, and the width can be enormous. Depth can be exponentially more economical. The tent map rises from 0 to 1 and falls back on ; composing it times gives a sawtooth with linear pieces, built from only hidden units in layers. A single hidden layer of ReLUs in one dimension has at most kinks, so it needs at least units for the same function. Turning such examples into statements about approximation, and finding natural functions where depth provably helps, is the subject of Universal Approximation & Depth and The Geometry of ReLU Networks.
Depth has a price as well: gradients must pass back through every layer, and they can vanish or explode on the way (Backpropagation).
Hidden units as learned features
Read the network from the top: is a linear model (or, with a softmax, a multiclass logistic regression) on the features . Basis-function regression and kernel methods also fit a linear model on features, but those features are fixed in advance (Basis Functions & Generalized Linear Models, The Kernel Trick). A network fits the features and the readout jointly, so the representation adapts to the task. Visualizations of trained image classifiers typically find oriented edges and color contrasts in the first layer, and units tuned to textures, then object parts, then whole objects as depth increases (Representations, Transfer & Inductive Bias).
The parameterization has symmetries. Permuting the units of a hidden layer (the rows of and , together with the matching columns of ) leaves unchanged, so for generic weights, whose units are all distinct, a layer of width gives different parameter vectors computing the same function; for odd activations such as tanh, flipping the signs of one unit's incoming weights, bias and outgoing weights multiplies that by . The training loss therefore has many equivalent minima, which is one reason it is not convex: the minimizers of a convex function form a convex set, but the average of two permuted copies of a minimizer is generally not a minimizer.
A network has one hidden layer and one output unit, and every weight and bias, into and out of the hidden layer, starts at the same value, . What happens to the hidden units under gradient descent?
- They quickly specialize, because the data differ from example to example
- They receive identical gradients and stay identical forever, so the layer behaves like a single unit
- Their gradients are all zero, so nothing at all is learned
- They converge to the permutation-symmetric global minimum
Show the answer
B. They receive identical gradients and stay identical forever, so the layer behaves like a single unit
Identical units compute identical activations on every input, and because their outgoing weights are equal too, the chain rule hands each of them the same gradient. Identical updates preserve the tie, so the layer never uses more than one unit's worth of capacity. Random initialization breaks the symmetry. (Equal incoming weights alone would not trap the layer: different outgoing weights would send the units different gradients.)
Key takeaways
- An MLP alternates affine maps with an elementwise nonlinearity. For a mini-batch each layer is one matrix multiply, and a layer from to units has parameters.
- Without , any depth collapses to one affine map (of rank at most the narrowest width). ReLU does not saturate for positive inputs and is the default for hidden layers; sigmoid and tanh saturate; GELU is a smooth variant common in transformers.
- Output layer and loss come in likelihood pairs: identity with squared loss, sigmoid or softmax with cross-entropy, each with gradient "prediction minus target". Compute log-softmax with the maximum subtracted.
- One hidden layer with a continuous non-polynomial activation approximates any continuous function on a compact set, but the theorem bounds neither the width nor what training finds; depth can multiply linear pieces exponentially.
- The last hidden layer is a learned feature map under a linear readout. Permutation symmetry gives many equivalent minima and is why weights must start random.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A network maps 20 inputs through two hidden layers of 50 units to 3 output scores, with a bias on every unit. How many parameters does it have?
- 3,650
- 3,753
- 3,600
- 150,000
Show the answer
B. 3,753
, then , then : in total. Parameters add up layer by layer.
For one training example, a three-class network's softmax gives , but the label is class 3. Which vector is , the cross-entropy gradient at the logits?
Show the answer
C.
with , which gives . A descent step raises the label's logit and lowers the others in proportion to the probability they took, the second one most.
A binary classifier has a sigmoid output trained with the squared loss . Why does it recover slowly from confident mistakes, compared with the log loss?
- Its gradient carries a factor , which is nearly zero when is large, even when the prediction is wrong
- The squared loss is not differentiable at its minimum
- The squared loss is unbounded for wrong predictions
- The sigmoid cannot output probabilities near 0 or 1
Show the answer
A. Its gradient carries a factor , which is nearly zero when is large, even when the prediction is wrong
. At with it is about , while the log loss gives : the log term's slope cancels the saturation exactly.
The universal approximation theorem is stated on a compact set . Why can no one-hidden-layer ReLU network approximate uniformly on all of ?
- ReLU is not a universal activation
- Polynomial targets such as cannot be approximated by networks
- It can, given enough hidden units
- A finite ReLU network is piecewise linear, so it grows at most linearly as , and is unbounded for every such network
Show the answer
D. A finite ReLU network is piecewise linear, so it grows at most linearly as , and is unbounded for every such network
The theorem promises uniform approximation on each compact set, by a network that depends on the set. Any finite ReLU network is affine beyond its last kink, so ; on every bounded interval, though, the interpolation construction of this lesson gets as close to as you like. Nor does the theorem say how wide the network must be, or whether training will find it.
A network maps with identity activations (a linear autoencoder). Which functions can it represent?
- Any affine map from to
- Only the identity map
- Affine maps whose linear part has rank at most 10
- Some nonlinear maps, since it has two layers
Show the answer
C. Affine maps whose linear part has rank at most 10
It computes , an affine map with linear part , and a product through a 10-dimensional layer has rank at most 10. Every such map is reachable by factoring .
Go deeper
- Universal Approximation & Depth · What one hidden layer can do, and what depth buys.
- The Geometry of ReLU Networks · Piecewise-linear functions and counting linear regions.
- Infinite Width: NTK & Mean-Field Limits · When wide networks behave like kernels, and when they don’t.
Further reading
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (MIT Press, 2016), chapter 6.
- C. M. Bishop, Pattern Recognition and Machine Learning (Springer, 2006), chapter 5.
- M. Leshno, V. Ya. Lin, A. Pinkus & S. Schocken, "Multilayer feedforward networks with a nonpolynomial activation function can approximate any function," Neural Networks 6(6), 861–867 (1993).
- D. Hendrycks & K. Gimpel, "Gaussian error linear units (GELUs)," arXiv:1606.08415 (2016).