Simple Algorithm
Deep Learning · Representation · 22 min

Neurons, Layers & Activations

The multilayer perceptron as matrix algebra, and why nonlinearity makes depth matter.

A multilayer perceptron is matrix multiplications with a simple function applied in between. Write it down precisely and three facts fall out: the shapes and counts that set its cost, the reason the in-between function cannot be linear, and the trade-offs that made ReLU the default.

What you’ll learn

  • Write the forward pass of a multilayer perceptron for one example and for a mini-batch in matrix form, tracking every shape, and count its parameters and FLOPs.
  • Prove that a composition of affine layers is affine, and construct any continuous piecewise-linear function of one variable from a single hidden layer of ReLUs.
  • Compare sigmoid, tanh, ReLU, leaky ReLU, ELU, softplus, GELU and SiLU by range, derivative and saturation, and explain the bound σ′≤14\sigma'\le\tfrac14, dead units and zero-centered outputs.
  • Match the output layer (identity, sigmoid, softmax) to the type of target.

The forward pass in matrix form

A multilayer perceptron with LL layers maps an input x∈Rd\mathbf x\in\R^d through alternating affine maps and an elementwise activation function ϕ\phi:

h(0)=x,z(ℓ)=W(ℓ)h(ℓ−1)+b(ℓ),h(ℓ)=ϕ(z(ℓ)),fθ(x)=z(L)\mathbf h^{(0)}=\mathbf x,\qquad \mathbf z^{(\ell)}=W^{(\ell)}\mathbf h^{(\ell-1)}+\mathbf b^{(\ell)},\qquad \mathbf h^{(\ell)}=\phi\big(\mathbf z^{(\ell)}\big),\qquad f_{\boldsymbol\theta}(\mathbf x)=\mathbf z^{(L)}
W(ℓ)∈Rnℓ×nℓ−1W^{(\ell)}\in\R^{n_\ell\times n_{\ell-1}} and b(ℓ)∈Rnℓ\mathbf b^{(\ell)}\in\R^{n_\ell}, with n0=dn_0=d. Row ii of W(ℓ)W^{(\ell)} holds the incoming weights of unit ii, so Wij(ℓ)W^{(\ell)}_{ij} connects unit jj below to unit ii above. The vectors z(ℓ)\mathbf z^{(\ell)} are the pre-activations. The last layer has no ϕ\phi: its outputs, the logits, go to an output function and a loss (last step).

Training rarely feeds one example at a time. Stack a mini-batch of BB inputs as the rows of X∈RB×dX\in\R^{B\times d}. A whole layer for the whole batch is then one matrix product, with the bias row broadcast to every example:

H(0)=X,Z(ℓ)=H(ℓ−1) W(ℓ)⊤+1B b(ℓ)⊤∈RB×nℓ,H(ℓ)=ϕ(Z(ℓ))H^{(0)}=X,\qquad Z^{(\ell)}=H^{(\ell-1)}\,W^{(\ell)\top}+\mathbf 1_B\,\mathbf b^{(\ell)\top}\in\R^{B\times n_\ell},\qquad H^{(\ell)}=\phi\big(Z^{(\ell)}\big)
Row bb of Z(ℓ)Z^{(\ell)} is z(ℓ)\mathbf z^{(\ell)} for example bb. This is the layout PyTorch uses: nn.Linear(n_in, n_out) stores a weight of shape (n_out, n_in) and computes XW⊤+bXW^\top+\mathbf b.
TensorShape (B=64B=64)Parameters
input X=H(0)X=H^{(0)}64×78464\times784—
W(1)W^{(1)} and b(1)\mathbf b^{(1)}256×784256\times784 and 256256200,960200{,}960
hidden Z(1)Z^{(1)}, H(1)H^{(1)}64×25664\times256 each—
W(2)W^{(2)} and b(2)\mathbf b^{(2)}10×25610\times256 and 10102,5702{,}570
logits Z(2)Z^{(2)}64×1064\times10—
A 784–256–10 network for 28×2828\times28 digit images: 203,530203{,}530 parameters in all, 99% of them in the first layer. A layer from nℓ−1n_{\ell-1} to nℓn_\ell units has nℓ−1nℓ+nℓn_{\ell-1}n_\ell+n_\ell parameters.
python
import torch
import torch.nn as nn

model = nn.Sequential(
    nn.Flatten(),          # (64, 1, 28, 28) -> (64, 784)
    nn.Linear(784, 256),   # weight (256, 784), bias (256,)
    nn.ReLU(),
    nn.Linear(256, 10),    # weight (10, 256): one row of logits per class
)
x = torch.randn(64, 1, 28, 28)   # a mini-batch of 64 images
logits = model(x)                # shape (64, 10)
n_params = sum(p.numel() for p in model.parameters())   # 203530

The same network in PyTorch. The softmax is left out on purpose: the loss takes logits (Loss Functions & Maximum Likelihood).

Predict before you look

How many parameters does a 784–512–512–10 MLP (two hidden layers of 512, with biases) have? Answer in thousands.

Show the answer

670 thousand

784⋅512+512=401,920784\cdot512+512=401{,}920, then 512⋅512+512=262,656512\cdot512+512=262{,}656, then 512⋅10+10=5,130512\cdot10+10=5{,}130: in total 669,706669{,}706. Width enters squared: doubling both hidden widths to 1,024 would quadruple the middle layer to over a million weights.

Cost. A layer costs B nℓ−1nℓB\,n_{\ell-1}n_\ell multiply–adds, about 2Bnℓ−1nℓ2Bn_{\ell-1}n_\ell FLOPs. A forward pass therefore costs about two FLOPs per weight per example: 2×203,264≈4×1052\times203{,}264\approx4\times10^5 for the 784–256–10 network. The backward pass costs about twice as much again (Backpropagation & Automatic Differentiation). All of it is dense matrix multiplication, the operation GPUs are built for.

Hidden units are learned features

Unit ii of the first layer computes ϕ(wi⊤x+bi)\phi(\mathbf w_i^\top\mathbf x+b_i). It compares the input with a template wi\mathbf w_i and responds when the match passes a threshold set by bib_i; its level sets are hyperplanes, so it splits input space along one soft hyperplane. Reshape a trained digit classifier's first-layer weights into 28×2828\times28 images and you often see stroke- and blob-like templates. The next layer's units are templates over these features, and the output layer is a linear classifier on the last hidden layer. Training learns the features and the readout together.

Width or depth? Width adds templates at one level. Depth builds features of features, and lets later layers reuse what earlier ones computed. One hidden layer of nn ReLUs on a one-dimensional input has at most n+1n+1 linear pieces; composing layers can multiply the number of pieces, which is the root of depth's advantage (What Networks Can Represent).

Why the activation must be nonlinear

DerivationAffine layers collapse
  1. W(2)(W(1)x+b(1))+b(2)=W(2)W(1)⏟W x+W(2)b(1)+b(2)⏟bW^{(2)}\big(W^{(1)}\mathbf x+\mathbf b^{(1)}\big)+\mathbf b^{(2)}=\underbrace{W^{(2)}W^{(1)}}_{W}\,\mathbf x+\underbrace{W^{(2)}\mathbf b^{(1)}+\mathbf b^{(2)}}_{\mathbf b}

    Compose two layers with no activation between them:

  2. rank⁡(W(L)⋯W(1))≤min⁡{d, n1, …, nL}\rank\big(W^{(L)}\cdots W^{(1)}\big)\le\min\{d,\,n_1,\,\dots,\,n_L\}

    By induction, any number of affine layers is a single affine map Wx+bW\mathbf x+\mathbf b with W=W(L)⋯W(1)W=W^{(L)}\cdots W^{(1)}. Worse, the product's rank is capped by the narrowest layer, so a deep linear network represents fewer functions than one wide linear layer:

  3. The loss is still a nonconvex function of the factors, which makes deep linear networks a valuable model of training dynamics (Learning Dynamics of Deep Linear Networks), but they add nothing to expressivity.

DerivationOne hidden layer of ReLUs builds any piecewise-linear function of one variable
  1. g(x)=g(t1)+s0 (x−t1)+∑i=1k (si−si−1) ReLU⁡(x−ti)g(x)=g(t_1)+s_0\,(x-t_1)+\sum_{i=1}^{k}\,(s_i-s_{i-1})\,\operatorname{ReLU}(x-t_i)

    Let g:R→Rg:\R\to\R be continuous and piecewise linear, with breakpoints t1<⋯<tkt_1<\dots<t_k, slope s0s_0 left of t1t_1 and slope sis_i on (ti,ti+1)(t_i,t_{i+1}), where tk+1=∞t_{k+1}=\infty. Claim:

  2. ddx[right side]x∈(tj, tj+1)=s0+∑i≤j(si−si−1)=sj\frac{d}{dx}\Big[\text{right side}\Big]_{x\in(t_j,\,t_{j+1})}=s_0+\sum_{i\le j}(s_i-s_{i-1})=s_j

    Left of t1t_1 every ReLU term vanishes, so the right side equals g(t1)+s0(x−t1)=g(x)g(t_1)+s_0(x-t_1)=g(x) there. The term (si−si−1)ReLU⁡(x−ti)(s_i-s_{i-1})\operatorname{ReLU}(x-t_i) is zero left of tit_i and adds slope si−si−1s_i-s_{i-1} to its right, so on every piece the slopes agree. Two continuous functions that agree on (−∞,t1](-\infty,t_1] and have the same slope on every piece are equal.

  3. ∣x∣=ReLU⁡(x)+ReLU⁡(−x),hat⁡(x)=ReLU⁡(x+1)−2ReLU⁡(x)+ReLU⁡(x−1)\abs{x}=\operatorname{ReLU}(x)+\operatorname{ReLU}(-x),\qquad \operatorname{hat}(x)=\operatorname{ReLU}(x+1)-2\operatorname{ReLU}(x)+\operatorname{ReLU}(x-1)

    The linear term costs two more units, x−t1=ReLU⁡(x−t1)−ReLU⁡(t1−x)x-t_1=\operatorname{ReLU}(x-t_1)-\operatorname{ReLU}(t_1-x), so k+2k+2 hidden units always suffice. Two examples: the absolute value, and a "hat" of height 1 on [−1,1][-1,1]:

The converse holds in every dimension. Affine maps, ReLU and composition all preserve continuity and piecewise linearity, so every ReLU network, of any depth, computes a continuous piecewise-linear function of its input, and every continuous piecewise-linear function Rn→R\R^n\to\R is computed by some ReLU network with at most ⌈log⁡2(n+1)⌉\lceil\log_2(n+1)\rceil hidden layers (Arora et al., 2018). Approximating a continuous function by its piecewise-linear interpolant then gives universal approximation in one dimension: the starting point of What Networks Can Represent.

Check your understanding

Which single-hidden-layer ReLU network computes f(x)=∣x−1∣f(x)=\abs{x-1} exactly?

  1. ReLU⁡(x−1)−ReLU⁡(1−x)\operatorname{ReLU}(x-1)-\operatorname{ReLU}(1-x)
  2. ReLU⁡(x)−ReLU⁡(x−1)\operatorname{ReLU}(x)-\operatorname{ReLU}(x-1)
  3. ReLU⁡(x−1)+ReLU⁡(1−x)\operatorname{ReLU}(x-1)+\operatorname{ReLU}(1-x)
  4. ReLU⁡(x−1)\operatorname{ReLU}(x-1)
Show the answer

C. ReLU⁡(x−1)+ReLU⁡(1−x)\operatorname{ReLU}(x-1)+\operatorname{ReLU}(1-x)

For x≥1x\ge1 the first unit gives x−1x-1 and the second 00; for x<1x<1 the first gives 00 and the second 1−x1-x. The sum is ∣x−1∣\abs{x-1}: one breakpoint where the slope jumps from −1-1 to +1+1, a jump of 22 shared by two units.

A zoo of activations

Activationϕ(z)\phi(z)ϕ′(z)\phi'(z)RangeCharacter
sigmoidσ(z)=11+e−z\sigma(z)=\dfrac1{1+e^{-z}}σ(1−σ)≤14\sigma(1-\sigma)\le\tfrac14(0,1)(0,1)saturates on both sides; outputs not zero-centered
tanhtanh⁡z=2σ(2z)−1\tanh z=2\sigma(2z)-11−tanh⁡2z≤11-\tanh^2z\le1(−1,1)(-1,1)zero-centered; saturates on both sides
ReLUmax⁡(0,z)\max(0,z)11 if z>0z>0, else 00[0,∞)[0,\infty)cheap; never saturates for z>0z>0; exact zeros; units can die
Leaky ReLUmax⁡(az,z)\max(az,z), a≈0.01a\approx0.0111 or aaR\Rnever exactly flat (Maas, Hannun & Ng, 2013); PReLU learns aa (He et al., 2015)
ELUzz if z>0z>0, else α(ez−1)\alpha(e^z-1)11 or αez\alpha e^z(−α,∞)(-\alpha,\infty)negative outputs pull mean activations toward 00 (Clevert et al., 2016)
softpluslog⁡(1+ez)\log(1+e^z)σ(z)\sigma(z)(0,∞)(0,\infty)a smooth ReLU; saturates on the left
GELUz Φ(z)z\,\Phi(z)Φ(z)+z Φ′(z)\Phi(z)+z\,\Phi'(z)≈[−0.17,∞)\approx[-0.17,\infty)smooth, not monotone; used in BERT and the GPT models (Hendrycks & Gimpel, 2016)
SiLU (Swish)z σ(z)z\,\sigma(z)σ(z)(1+z(1−σ(z)))\sigma(z)\big(1+z(1-\sigma(z))\big)≈[−0.28,∞)\approx[-0.28,\infty)smooth, not monotone, self-gated (Elfwing, Uchibe & Doya, 2018; Ramachandran, Zoph & Le, 2017)
Φ\Phi is the standard normal CDF. GELU and SiLU dip slightly below zero: their minima are −0.170-0.170 at z≈−0.75z\approx-0.75 and −0.278-0.278 at z≈−1.28z\approx-1.28.

Saturation. For the sigmoid, σ′=σ(1−σ)≤(σ+(1−σ)2)2=14\sigma'=\sigma(1-\sigma)\le\big(\tfrac{\sigma+(1-\sigma)}{2}\big)^2=\tfrac14 by the AM–GM inequality, with equality only at z=0z=0. The backward pass multiplies the gradient by ϕ′(z)\phi'(z) once per layer, so through LL sigmoid layers the activations' factors alone are at most 4−L4^{-L}, below 10−610^{-6} for L=10L=10, and far smaller once units sit in the flat tails. This is a large part of the vanishing-gradient problem (Backpropagation & Gradient Flow). ReLU's slope is exactly 1 wherever it is active, which is why rectifiers made deep networks much easier to train (Glorot, Bordes & Bengio, 2011).

Dead units. A ReLU unit whose pre-activation is negative for every training input has zero gradient for all its incoming weights and its bias: it is a dead neuron, and gradient descent cannot revive it unless the layers below change its inputs. Large learning-rate steps that push a bias far negative are a common cause; leaky ReLU, ELU, GELU and SiLU never have an exactly zero slope.

Zero-centering. If every input to a unit is positive, as sigmoid outputs are, then for one example all the gradients of its incoming weights, δ hj\delta\,h_j, share the sign of δ=∂L/∂z\delta=\partial\loss/\partial z. A single update can only raise all those weights or lower them all, so reaching a mixed-sign target takes a zig-zag. That is why tanh trains better than the sigmoid in hidden layers (LeCun et al., 1998).

Check your understanding

After a large update, a ReLU unit in the first hidden layer has a negative pre-activation on every training example. What happens to it under further gradient descent?

  1. Its weights get large gradients that push the pre-activation back up
  2. Its incoming weights and bias receive zero gradient, so it stays dead
  3. It turns into a linear unit
  4. Its output becomes negative and keeps passing gradient
Show the answer

B. Its incoming weights and bias receive zero gradient, so it stays dead

The gradient of each incoming weight is δ⋅ReLU⁡′(z)⋅xj\delta\cdot\operatorname{ReLU}'(z)\cdot x_j, and ReLU⁡′(z)=0\operatorname{ReLU}'(z)=0 on every example. A first-layer unit's inputs are the fixed data, so nothing can change zz again. (Weight decay applied to both w\mathbf w and bb only scales them down together, which keeps zz negative.) Deeper units can occasionally revive when the layers below change their inputs.

Output layers, and what comes next

The last layer's output function must match the kind of target. For one of KK classes, the softmax turns KK logits into a probability distribution:

pk=softmax⁡(z)k=ezk∑j=1Kezj,softmax⁡(z+c1)=softmax⁡(z),K=2: p1=σ(z1−z2)p_k=\softmax(\mathbf z)_k=\frac{e^{z_k}}{\sum_{j=1}^Ke^{z_j}},\qquad \softmax(\mathbf z+c\mathbf 1)=\softmax(\mathbf z),\qquad K=2:\ p_1=\sigma(z_1-z_2)
Only differences of logits matter, and with two classes the softmax is a sigmoid of the logit difference.
TargetOutput functionMatching loss (next lesson)
a real numberidentitysquared error
yes / nosigmoid of one logitbinary cross-entropy
one of KK classessoftmax of KK logitscross-entropy
any subset of KK labelsKK independent sigmoidssum of KK binary cross-entropies
a count 0,1,2,…0,1,2,\dotsexp⁡\exp of one output (a rate)Poisson negative log-likelihood
Loss Functions & Maximum Likelihood derives every row from one principle: choose a distribution for yy and maximize the likelihood.
Predict before you look

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

Show the answer

66.5 %

e2/(e2+e1+e0)=7.39/11.11≈0.665e^2/(e^2+e^1+e^0)=7.39/11.11\approx0.665. A logit gap of 11 multiplies the odds by e≈2.7e\approx2.7: the three classes get 66.5%66.5\%, 24.5%24.5\% and 9.0%9.0\%.

Key takeaways

  • An MLP alternates affine maps and elementwise activations. With examples as rows, a layer is Z=HW⊤+1b⊤Z=HW^\top+\mathbf 1\mathbf b^\top; a layer from nℓ−1n_{\ell-1} to nℓn_\ell units has nℓ−1nℓ+nℓn_{\ell-1}n_\ell+n_\ell parameters and costs about 2Bnℓ−1nℓ2Bn_{\ell-1}n_\ell FLOPs.
  • Without a nonlinearity, any depth collapses to one affine map whose rank is capped by the narrowest layer.
  • One hidden layer of k+2k+2 ReLUs builds any continuous piecewise-linear function of one variable with kk breakpoints, and every ReLU network is continuous and piecewise linear.
  • Sigmoid and tanh saturate (σ′≤14\sigma'\le\tfrac14) and the sigmoid is not zero-centered; ReLU never saturates for positive inputs but can die; leaky ReLU, ELU, GELU and SiLU are leaky or smooth variants.
  • The output function matches the target: identity for real values, sigmoid for yes/no, softmax for one of KK classes, independent sigmoids for multi-label.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

In PyTorch, nn.Linear(300, 100) is applied to a batch XX of shape (32,300)(32, 300). What are the shapes of its weight and of its output?

  1. weight (300,100)(300, 100), output (32,100)(32, 100)
  2. weight (100,300)(100, 300), output (100,32)(100, 32)
  3. weight (100,300)(100, 300), output (32,100)(32, 100)
  4. weight (300,100)(300, 100), output (300,32)(300, 32)
Show the answer

C. weight (100,300)(100, 300), output (32,100)(32, 100)

The weight has shape (out, in) =(100,300)=(100,300), and the layer computes XW⊤+bXW^\top+\mathbf b: (32×300)(300×100)=(32×100)(32\times300)(300\times100)=(32\times100). Examples stay in the rows.

Question 2

How many parameters does a 100–50–50–1 MLP with biases have?

  1. 201201
  2. 7,5507{,}550
  3. 250,000250{,}000
  4. 7,6517{,}651
Show the answer

D. 7,6517{,}651

(100⋅50+50)+(50⋅50+50)+(50⋅1+1)=5,050+2,550+51=7,651(100\cdot50+50)+(50\cdot50+50)+(50\cdot1+1)=5{,}050+2{,}550+51=7{,}651.

Question 3

Why do deep stacks of sigmoid layers tend to have vanishing gradients?

  1. The backward pass multiplies by σ′(z)≤14\sigma'(z)\le\tfrac14 at every layer, so the gradient shrinks geometrically with depth
  2. The sigmoid is not differentiable at 00
  3. Sigmoid outputs can be negative, which cancels gradients
  4. The sigmoid has no parameters, so it cannot learn
Show the answer

A. The backward pass multiplies by σ′(z)≤14\sigma'(z)\le\tfrac14 at every layer, so the gradient shrinks geometrically with depth

Each layer contributes a factor σ′(z)≤14\sigma'(z)\le\tfrac14, and much less in the saturated tails, on top of the weights. Ten layers give at most 4−10≈10−64^{-10}\approx10^{-6} from the activations alone.

Question 4

One model predicts which of 1,000 classes an image shows. Another predicts which of 20 tags apply to an image, where any number of tags can apply at once. Which output layers fit?

  1. Softmax for both
  2. 20 independent sigmoids for the first, softmax for the second
  3. Softmax over 1,000 classes for the first; 20 independent sigmoids for the second
  4. Identity outputs with squared error for both
Show the answer

C. Softmax over 1,000 classes for the first; 20 independent sigmoids for the second

A softmax makes the classes compete for one unit of probability, right when exactly one class is true. Independent tags need one probability each, so each gets its own sigmoid.

Go deeper

Further reading

  • I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, ch. 6 (MIT Press, 2016).
  • S. J. D. Prince, Understanding Deep Learning, ch. 3–4 (MIT Press, 2023).
  • X. Glorot, A. Bordes & Y. Bengio, "Deep sparse rectifier neural networks," AISTATS (2011).
  • R. Arora, A. Basu, P. Mianjy & A. Mukherjee, "Understanding deep neural networks with rectified linear units," ICLR (2018).
  • Y. LeCun, L. Bottou, G. B. Orr & K.-R. Müller, "Efficient BackProp," in Neural Networks: Tricks of the Trade (Springer, 1998).