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 , 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 layers maps an input through alternating affine maps and an elementwise activation function :
Training rarely feeds one example at a time. Stack a mini-batch of inputs as the rows of . A whole layer for the whole batch is then one matrix product, with the bias row broadcast to every example:
nn.Linear(n_in, n_out) stores a weight of shape (n_out, n_in) and computes .| Tensor | Shape () | Parameters |
|---|---|---|
| input | — | |
| and | and | |
| hidden , | each | — |
| and | and | |
| logits | — |
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()) # 203530The same network in PyTorch. The softmax is left out on purpose: the loss takes logits (Loss Functions & Maximum Likelihood).
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
, then , then : in total . Width enters squared: doubling both hidden widths to 1,024 would quadruple the middle layer to over a million weights.
Cost. A layer costs multiply–adds, about FLOPs. A forward pass therefore costs about two FLOPs per weight per example: 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 of the first layer computes . It compares the input with a template and responds when the match passes a threshold set by ; its level sets are hyperplanes, so it splits input space along one soft hyperplane. Reshape a trained digit classifier's first-layer weights into 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 ReLUs on a one-dimensional input has at most 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
Compose two layers with no activation between them:
By induction, any number of affine layers is a single affine map with . Worse, the product's rank is capped by the narrowest layer, so a deep linear network represents fewer functions than one wide linear layer:
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.
Let be continuous and piecewise linear, with breakpoints , slope left of and slope on , where . Claim:
Left of every ReLU term vanishes, so the right side equals there. The term is zero left of and adds slope to its right, so on every piece the slopes agree. Two continuous functions that agree on and have the same slope on every piece are equal.
The linear term costs two more units, , so hidden units always suffice. Two examples: the absolute value, and a "hat" of height 1 on :
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 is computed by some ReLU network with at most 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.
Which single-hidden-layer ReLU network computes exactly?
Show the answer
C.
For the first unit gives and the second ; for the first gives and the second . The sum is : one breakpoint where the slope jumps from to , a jump of shared by two units.
A zoo of activations
| Activation | Range | Character | ||
|---|---|---|---|---|
| sigmoid | saturates on both sides; outputs not zero-centered | |||
| tanh | zero-centered; saturates on both sides | |||
| ReLU | if , else | cheap; never saturates for ; exact zeros; units can die | ||
| Leaky ReLU | , | or | never exactly flat (Maas, Hannun & Ng, 2013); PReLU learns (He et al., 2015) | |
| ELU | if , else | or | negative outputs pull mean activations toward (Clevert et al., 2016) | |
| softplus | a smooth ReLU; saturates on the left | |||
| GELU | smooth, not monotone; used in BERT and the GPT models (Hendrycks & Gimpel, 2016) | |||
| SiLU (Swish) | smooth, not monotone, self-gated (Elfwing, Uchibe & Doya, 2018; Ramachandran, Zoph & Le, 2017) |
Saturation. For the sigmoid, by the AM–GM inequality, with equality only at . The backward pass multiplies the gradient by once per layer, so through sigmoid layers the activations' factors alone are at most , below for , 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, , share the sign of . 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).
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?
- Its weights get large gradients that push the pre-activation back up
- Its incoming weights and bias receive zero gradient, so it stays dead
- It turns into a linear unit
- 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 , and on every example. A first-layer unit's inputs are the fixed data, so nothing can change again. (Weight decay applied to both and only scales them down together, which keeps 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 classes, the softmax turns logits into a probability distribution:
| Target | Output function | Matching loss (next lesson) |
|---|---|---|
| a real number | identity | squared error |
| yes / no | sigmoid of one logit | binary cross-entropy |
| one of classes | softmax of logits | cross-entropy |
| any subset of labels | independent sigmoids | sum of binary cross-entropies |
| a count | of one output (a rate) | Poisson negative log-likelihood |
A classifier outputs the logits . What probability does the softmax give the first class, in percent?
Show the answer
66.5 %
. A logit gap of multiplies the odds by : the three classes get , and .
Key takeaways
- An MLP alternates affine maps and elementwise activations. With examples as rows, a layer is ; a layer from to units has parameters and costs about FLOPs.
- Without a nonlinearity, any depth collapses to one affine map whose rank is capped by the narrowest layer.
- One hidden layer of ReLUs builds any continuous piecewise-linear function of one variable with breakpoints, and every ReLU network is continuous and piecewise linear.
- Sigmoid and tanh saturate () 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 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.
In PyTorch, nn.Linear(300, 100) is applied to a batch of shape . What are the shapes of its weight and of its output?
- weight , output
- weight , output
- weight , output
- weight , output
Show the answer
C. weight , output
The weight has shape (out, in) , and the layer computes : . Examples stay in the rows.
How many parameters does a 100–50–50–1 MLP with biases have?
Show the answer
D.
.
Why do deep stacks of sigmoid layers tend to have vanishing gradients?
- The backward pass multiplies by at every layer, so the gradient shrinks geometrically with depth
- The sigmoid is not differentiable at
- Sigmoid outputs can be negative, which cancels gradients
- The sigmoid has no parameters, so it cannot learn
Show the answer
A. The backward pass multiplies by at every layer, so the gradient shrinks geometrically with depth
Each layer contributes a factor , and much less in the saturated tails, on top of the weights. Ten layers give at most from the activations alone.
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?
- Softmax for both
- 20 independent sigmoids for the first, softmax for the second
- Softmax over 1,000 classes for the first; 20 independent sigmoids for the second
- 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
- Activation Functions in Depth · ReLU, GELU, SiLU and gated units: saturation, dead neurons and what smoothness buys.
- Symmetries & Conservation Laws · Permutation and rescaling symmetries, and the quantities gradient flow conserves.
- Kolmogorov–Arnold Networks · Learnable functions on edges: the superposition theorem, KANs and how they compare with MLPs.
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).