Simple Algorithm
Machine Learning · Descent · 22 min

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 p−y\mathbf p-\mathbf y.
  • 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 LL hidden layers of widths n1,…,nLn_1,\dots,n_L maps an input x∈Rd\mathbf x\in\R^d (write n0=dn_0=d) to kk output scores by alternating affine maps and an elementwise nonlinearity φ\varphi, the activation function:

h(0)=x,z(l)=W(l)h(l−1)+b(l),h(l)=φ(z(l))(l=1,…,L),\mathbf h^{(0)}=\mathbf x,\qquad \mathbf z^{(l)}=W^{(l)}\mathbf h^{(l-1)}+\mathbf b^{(l)},\qquad \mathbf h^{(l)}=\varphi\big(\mathbf z^{(l)}\big)\quad(l=1,\dots,L),
f(x)=W(L+1)h(L)+b(L+1)∈Rk,f(\mathbf x)=W^{(L+1)}\mathbf h^{(L)}+\mathbf b^{(L+1)}\in\R^k,

with W(l)∈Rnl×nl−1W^{(l)}\in\R^{n_l\times n_{l-1}} and b(l)∈Rnl\mathbf b^{(l)}\in\R^{n_l}. Row jj of W(l)W^{(l)} holds the incoming weights of neuron jj in layer ll. The vector z(l)\mathbf z^{(l)} is the layer's pre-activation, h(l)\mathbf h^{(l)} its activation, and the last layer has no φ\varphi of its own: the loss decides how its scores (the logits) are read.

For a mini-batch of BB examples stacked as the rows of X∈RB×dX\in\R^{B\times d}, as in a design matrix, every layer becomes one matrix–matrix product, H(l)=φ(H(l−1)W(l)⊤+1b(l)⊤)H^{(l)}=\varphi\big(H^{(l-1)}W^{(l)\top}+\mathbf 1\mathbf b^{(l)\top}\big) with H(0)=XH^{(0)}=X. That single shape, a big matrix multiply followed by an elementwise function, is what graphics processors are built to do fast.

python
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 28×2828\times28 images and 10 classes. The weights start Gaussian with variance 2/nl−12/n_{l-1}, the He initialization whose reason is given in Initialization & Signal Propagation.

Predict before you look

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 mm to nn units has mnmn weights and nn biases: 784⋅256+256=200,960784\cdot256+256=200{,}960, then 256⋅128+128=32,896256\cdot128+128=32{,}896, then 128⋅10+10=1,290128\cdot10+10=1{,}290, for a total of 235,146235{,}146. 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 2.3×1052.3\times10^5, so the parameter count also measures the compute.

Why the nonlinearity, and which one

DerivationAffine layers collapse
  1. W2(W1x+b1)+b2=(W2W1)⏟M x+(W2b1+b2)⏟cW_2\big(W_1\mathbf x+\mathbf b_1\big)+\mathbf b_2=\underbrace{(W_2W_1)}_{M}\,\mathbf x+\underbrace{(W_2\mathbf b_1+\mathbf b_2)}_{\mathbf c}

    Two affine layers with nothing between them form one affine layer:

  2. rank⁡M ≤ min⁡lnl\rank M\ \le\ \min_l n_l

    By induction, any depth of affine layers computes Mx+cM\mathbf x+\mathbf c with M=WL+1⋯W1M=W_{L+1}\cdots W_1. A narrow layer also caps the rank, since the rank of a product is at most the rank of each factor:

  3. {deep linear networks}={x↦Mx+c: rank⁡M≤min⁡lnl}\{\text{deep linear networks}\}=\{\mathbf x\mapsto M\mathbf x+\mathbf c:\ \rank M\le\min_l n_l\}

    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 φ\varphi.

Activationφ(z)\varphi(z)φ′(z)\varphi'(z)RangeNotes
Sigmoid σ\sigma11+e−z\dfrac1{1+e^{-z}}σ(1−σ)≤14\sigma(1-\sigma)\le\tfrac14(0,1)(0,1)Saturates: σ′(5)≈0.0066\sigma'(5)\approx0.0066. Outputs are not centered at 0. Now used mainly for gates and binary outputs.
tanh⁡\tanh2σ(2z)−12\sigma(2z)-11−tanh⁡2z≤11-\tanh^2z\le1(−1,1)(-1,1)Zero-centered, slope 1 at the origin, but saturates too: tanh⁡′(3)≈0.0099\tanh'(3)\approx0.0099.
ReLUmax⁡(0,z)\max(0,z)11 if z>0z>0, 00 if z<0z<0[0,∞)[0,\infty)No saturation for z>0z>0, cheap, sparse activations. A unit whose pre-activation is negative on every input gets zero gradient ("dead").
Leaky ReLUmax⁡(αz,z)\max(\alpha z,z), α≈0.01\alpha\approx0.01α\alpha or 11R\RKeeps a small gradient for z<0z<0, so units cannot die.
GELUz Φ(z)z\,\Phi(z)Φ(z)+z ϕ(z)\Phi(z)+z\,\phi(z)[−0.17,∞)[-0.17,\infty)Smooth and slightly non-monotone (minimum ≈−0.170\approx-0.170 at z≈−0.75z\approx-0.75); Φ\Phi and ϕ\phi are the distribution function and density of N(0,1)\mathcal N(0,1). Common in transformers (Hendrycks & Gimpel, 2016).
ReLU's derivative at exactly 00 is undefined; software uses 00 (or any value in [0,1][0,1], a subgradient), which almost never matters because pre-activations are rarely exactly zero.
Check your understanding

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?

  1. They keep changing, because the loss still depends on them
  2. They receive zero gradient on every example, so they stop changing and the unit stays silent
  3. They grow until the unit switches back on
  4. 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 max⁡(0,z)=0\max(0,z)=0 with derivative 00 wherever z<0z<0, 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 yy given the logits z=f(x)\mathbf z=f(\mathbf x):

  • Regression: identity output and the squared loss 12∥y−z∥2\tfrac12\norm{\mathbf y-\mathbf z}^2, the negative log-likelihood of a Gaussian with fixed variance, up to constants.
  • Two classes (y∈{0,1}y\in\{0,1\}): p=σ(z)p=\sigma(z) and the log loss −ylog⁡p−(1−y)log⁡(1−p)-y\log p-(1-y)\log(1-p), the Bernoulli likelihood. On the last hidden layer's features this is exactly logistic regression.
  • kk classes: the softmax pj=ezj/∑iezip_j=e^{z_j}/\sum_ie^{z_i} and the cross-entropy −log⁡py-\log p_y, the categorical likelihood, with yy one-hot as y\mathbf y.
DerivationThe softmax cross-entropy gradient
  1. ℓ(z,y)=−log⁡ezy∑iezi=−zy+log⁡∑i=1kezi\ell(\mathbf z,y)=-\log\frac{e^{z_y}}{\sum_ie^{z_i}}=-z_y+\log\sum_{i=1}^ke^{z_i}

    Write the loss for true class yy directly in terms of the logits:

  2. ∂ℓ∂zj=−1{j=y}+ezj∑iezi=pj−yj\frac{\partial\ell}{\partial z_j}=-\mathbf 1\{j=y\}+\frac{e^{z_j}}{\sum_ie^{z_i}}=p_j-y_j

    Differentiate with respect to zjz_j. The first term gives −1-1 when j=yj=y and 0 otherwise; differentiating the log-sum-exp gives the softmax:

  3. ∂∂z12(σ(z)−y)2=(σ(z)−y) σ′(z):z=−10, y=1 ⇒ ≈−4.5×10−5  vs.  σ(z)−y≈−1\frac{\partial}{\partial z}\tfrac12\big(\sigma(z)-y\big)^2=\big(\sigma(z)-y\big)\,\sigma'(z):\qquad z=-10,\ y=1\ \Rightarrow\ \approx-4.5\times10^{-5}\ \text{ vs. }\ \sigma(z)-y\approx-1

    So ∇zℓ=p−y\nabla_{\mathbf z}\ell=\mathbf p-\mathbf y: prediction minus target. The same form holds for sigmoid with log loss (p−yp-y) and identity with squared loss (z−y\mathbf z-\mathbf y), because each pairs a likelihood with its canonical link (Generalized Linear Models). Contrast a sigmoid output trained with squared loss: an extra factor σ′(z)\sigma'(z) appears, and it is nearly zero whenever ∣z∣\abs z is large, including when the unit is confidently wrong:

Predict before you look

A three-class network outputs logits z=(2,1,0)\mathbf z=(2,1,0). What softmax probability does it give the first class, in percent?

Show the answer

67 %

e2≈7.389e^2\approx7.389, e1≈2.718e^1\approx2.718 and e0=1e^0=1 sum to 11.10711.107, so p≈(0.665,0.245,0.090)\mathbf p\approx(0.665,0.245,0.090). If the first class is correct, the loss is −ln⁡0.665≈0.408-\ln0.665\approx0.408 and the logit gradient is p−y≈(−0.335,0.245,0.090)\mathbf p-\mathbf y\approx(-0.335,0.245,0.090): 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 p\mathbf p unchanged, since softmax depends only on differences.

What one hidden layer can represent

Why do polynomials fail? Suppose φ\varphi is a polynomial of degree mm. Then each unit φ(w⊤x+b)\varphi(\mathbf w^\top\mathbf x+b), viewed as a function of x\mathbf x, is a polynomial of degree mm or less, and finite sums of units stay in that class. They all live in one finite-dimensional space, which cannot approximate, say, x1m+1x_1^{m+1} on [0,1]d[0,1]^d. Every other continuous activation escapes this trap; the proof is in Universal Approximation & Depth. For ReLU the escape is easy to see by construction:

DerivationReLU units build any one-dimensional piecewise-linear function
  1. g(x)=y0+s0 ReLU(x−t0)+∑i=1N−1(si−si−1) ReLU(x−ti)g(x)=y_0+s_0\,\mathrm{ReLU}(x-t_0)+\sum_{i=1}^{N-1}\big(s_i-s_{i-1}\big)\,\mathrm{ReLU}(x-t_i)

    Take knots t0<t1<⋯<tNt_0<t_1<\dots<t_N, values yiy_i, and slopes si=(yi+1−yi)/(ti+1−ti)s_i=(y_{i+1}-y_i)/(t_{i+1}-t_i). One hidden layer of NN ReLU units and an output bias define

  2. g(x)=yi+si (x−ti)for x∈[ti,ti+1]g(x)=y_i+s_i\,(x-t_i)\qquad\text{for }x\in[t_i,t_{i+1}]

    On [t0,t1][t_0,t_1] only the first unit is active, which gives the first segment. The unit anchored at tit_i is zero to the left of its knot and from there on adds si−si−1s_i-s_{i-1} to the slope; it starts from 0, so gg stays continuous and passes through every (ti,yi)(t_i,y_i):

  3. sup⁡x∈[t0,tN]∣f(x)−g(x)∣ ≤ ωf(h) → h→0  0\sup_{x\in[t_0,t_N]}\abs{f(x)-g(x)}\ \le\ \omega_f(h)\ \xrightarrow{\ h\to0\ }\ 0

    Let gg interpolate a continuous ff at knots spaced hh apart. On each piece, g(x)g(x) is a weighted average of f(ti)f(t_i) and f(ti+1)f(t_{i+1}), both within ωf(h)=sup⁡∣x−x′∣≤h∣f(x)−f(x′)∣\omega_f(h)=\sup_{\abs{x-x'}\le h}\abs{f(x)-f(x')} of f(x)f(x). Uniform continuity makes ωf(h)→0\omega_f(h)\to0, so one hidden layer of ReLUs approximates any continuous function on an interval:

Think first Using as few ReLU units as possible, write ∣x∣\abs x, and a triangular bump that rises from 0 at x=−1x=-1 to 1 at x=0x=0 and falls back to 0 at x=1x=1.

∣x∣=ReLU(x)+ReLU(−x)\abs x=\mathrm{ReLU}(x)+\mathrm{ReLU}(-x): two units. The bump is ReLU(x+1)−2 ReLU(x)+ReLU(x−1)\mathrm{ReLU}(x+1)-2\,\mathrm{ReLU}(x)+\mathrm{ReLU}(x-1): 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 dd dimensions a grid of width-hh bumps has about h−dh^{-d} 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 T(x)=2 ReLU(x)−4 ReLU(x−12)T(x)=2\,\mathrm{ReLU}(x)-4\,\mathrm{ReLU}(x-\tfrac12) rises from 0 to 1 and falls back on [0,1][0,1]; composing it kk times gives a sawtooth with 2k2^k linear pieces, built from only 2k2k hidden units in kk layers. A single hidden layer of mm ReLUs in one dimension has at most mm kinks, so it needs at least 2k−12^k-1 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: f(x)=W(L+1)h(L)(x)+b(L+1)f(\mathbf x)=W^{(L+1)}\mathbf h^{(L)}(\mathbf x)+\mathbf b^{(L+1)} is a linear model (or, with a softmax, a multiclass logistic regression) on the features h(L)(x)\mathbf h^{(L)}(\mathbf x). 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 W(l)W^{(l)} and b(l)\mathbf b^{(l)}, together with the matching columns of W(l+1)W^{(l+1)}) leaves ff unchanged, so for generic weights, whose units are all distinct, a layer of width nn gives n!n! 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 2n2^n. 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.

Check your understanding

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, 0.50.5. What happens to the hidden units under gradient descent?

  1. They quickly specialize, because the data differ from example to example
  2. They receive identical gradients and stay identical forever, so the layer behaves like a single unit
  3. Their gradients are all zero, so nothing at all is learned
  4. 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 W(l)h+b(l)W^{(l)}\mathbf h+\mathbf b^{(l)} with an elementwise nonlinearity. For a mini-batch each layer is one matrix multiply, and a layer from mm to nn units has mn+nmn+n parameters.
  • Without φ\varphi, 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.

Question 1

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?

  1. 3,650
  2. 3,753
  3. 3,600
  4. 150,000
Show the answer

B. 3,753

20⋅50+50=1,05020\cdot50+50=1{,}050, then 50⋅50+50=2,55050\cdot50+50=2{,}550, then 50⋅3+3=15350\cdot3+3=153: 3,7533{,}753 in total. Parameters add up layer by layer.

Question 2

For one training example, a three-class network's softmax gives p=(0.1,0.6,0.3)\mathbf p=(0.1,0.6,0.3), but the label is class 3. Which vector is ∇zℓ\nabla_{\mathbf z}\ell, the cross-entropy gradient at the logits?

  1. (0.1, −0.4, 0.3)(0.1,\,-0.4,\,0.3)
  2. (0, 0, −0.7)(0,\,0,\,-0.7)
  3. (0.1, 0.6, −0.7)(0.1,\,0.6,\,-0.7)
  4. (0.1, 0.6, 0.3)(0.1,\,0.6,\,0.3)
Show the answer

C. (0.1, 0.6, −0.7)(0.1,\,0.6,\,-0.7)

∇zℓ=p−y\nabla_{\mathbf z}\ell=\mathbf p-\mathbf y with y=(0,0,1)\mathbf y=(0,0,1), which gives (0.1, 0.6, −0.7)(0.1,\,0.6,\,-0.7). A descent step raises the label's logit and lowers the others in proportion to the probability they took, the second one most.

Question 3

A binary classifier has a sigmoid output trained with the squared loss 12(σ(z)−y)2\tfrac12(\sigma(z)-y)^2. Why does it recover slowly from confident mistakes, compared with the log loss?

  1. Its gradient carries a factor σ′(z)\sigma'(z), which is nearly zero when ∣z∣\abs z is large, even when the prediction is wrong
  2. The squared loss is not differentiable at its minimum
  3. The squared loss is unbounded for wrong predictions
  4. The sigmoid cannot output probabilities near 0 or 1
Show the answer

A. Its gradient carries a factor σ′(z)\sigma'(z), which is nearly zero when ∣z∣\abs z is large, even when the prediction is wrong

∂z12(σ(z)−y)2=(σ(z)−y)σ′(z)\partial_z\tfrac12(\sigma(z)-y)^2=(\sigma(z)-y)\sigma'(z). At z=−10z=-10 with y=1y=1 it is about −4.5×10−5-4.5\times10^{-5}, while the log loss gives σ(z)−y≈−1\sigma(z)-y\approx-1: the log term's slope cancels the saturation exactly.

Question 4

The universal approximation theorem is stated on a compact set KK. Why can no one-hidden-layer ReLU network approximate f(x)=x2f(x)=x^2 uniformly on all of R\R?

  1. ReLU is not a universal activation
  2. Polynomial targets such as x2x^2 cannot be approximated by networks
  3. It can, given enough hidden units
  4. A finite ReLU network is piecewise linear, so it grows at most linearly as ∣x∣→∞\abs x\to\infty, and x2−g(x)x^2-g(x) is unbounded for every such network gg
Show the answer

D. A finite ReLU network is piecewise linear, so it grows at most linearly as ∣x∣→∞\abs x\to\infty, and x2−g(x)x^2-g(x) is unbounded for every such network gg

The theorem promises uniform approximation on each compact set, by a network that depends on the set. Any finite ReLU network gg is affine beyond its last kink, so x2−g(x)→∞x^2-g(x)\to\infty; on every bounded interval, though, the interpolation construction of this lesson gets as close to x2x^2 as you like. Nor does the theorem say how wide the network must be, or whether training will find it.

Question 5

A network maps R100→R10→R100\R^{100}\to\R^{10}\to\R^{100} with identity activations (a linear autoencoder). Which functions can it represent?

  1. Any affine map from R100\R^{100} to R100\R^{100}
  2. Only the identity map
  3. Affine maps whose linear part has rank at most 10
  4. Some nonlinear maps, since it has two layers
Show the answer

C. Affine maps whose linear part has rank at most 10

It computes W2(W1x+b1)+b2W_2(W_1\mathbf x+\mathbf b_1)+\mathbf b_2, an affine map with linear part W2W1W_2W_1, and a product through a 10-dimensional layer has rank at most 10. Every such map is reachable by factoring M=W2W1M=W_2W_1.

Go deeper

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