From linear models to networks
Why stacked linear layers need a nonlinearity, the multilayer perceptron with its shapes and activations, what universal approximation promises and what it does not, depth against width, learned features, output layers and losses.
Features someone designed
The topic Gradient boosting ended with the strongest tool of this course for tables: boosted trees, with stacking on top. It also ended at a limit: every model so far takes its features as given. Least squares and logistic regression fit a linear function of them. Kernels fix a nonlinear feature map before they see any data. Trees split on columns that someone prepared.
That works when a column already means something: an income, an age, a count of purchases. It fails for raw signals. Take handwritten digits: an image is 64 pixel brightnesses, and one pixel says almost nothing about the digit. What matters is a pattern across many pixels: a stroke, a loop, a corner. A threshold on one pixel rarely asks a good question. For decades such features of images, sound and text were designed by hand: edge histograms, spectral coefficients, counts of n-grams.
A neural network learns the feature map from the data, together with the linear model on top of it, by the same gradient descent as in the topic Gradient descent. This topic builds networks out of linear models, asks what they can represent, and sets up their outputs and losses. The next topic computes their gradients.
Notation. A network has layers of widths , with . Layer has a weight matrix and a bias . It computes the pre-activation and the activation :
The activation function acts on each coordinate. In this topic is always an activation, not a kernel's feature map. The last layer has no activation: its output is a prediction or a vector of logits.
Layer on layer
The first idea is to stack linear layers. It gains nothing, because two affine layers are one affine layer:
By induction, so is any number of them. Without a nonlinearity, depth adds parameters but not expressiveness. The stack is a linear model with the matrix . The rank of a product is at most the rank of each factor (see Matrices and linear systems in Mathematics for ML), so the rank is at most the smallest width. A narrow layer can only restrict the model.
A nonlinearity between the layers changes this. With one hidden layer,
The output is a linear model on the features , and these features are learned too.
XOR. The four points with labels cannot be separated by a line. Suppose held exactly for the two points of class 1. Then and , while and . Adding the first two inequalities gives , a contradiction.
Two ReLU units are enough, with . Take , and :
| 0 | 0 | 0 | 0 | |
| 1 | 1 | 0 | 1 | |
| 1 | 1 | 0 | 1 | |
| 2 | 2 | 1 | 0 |
In the hidden coordinates the inputs become , , and . Both points of class 1 land on the same spot, and a line such as separates the classes. The hidden layer has made the problem linear.
Features out of training
The XOR features above were designed by hand. Does training find such features by itself? Here is an experiment. Take 200 points in four clusters around , with standard deviation . Class 1 is where the two coordinates have different signs: XOR with noise. The network has two tanh hidden units and one output logit with a sigmoid. It is trained on the binary cross-entropy of the topic Logistic regression, with Adam from Stochastic and adaptive optimizers: step , 300 full-batch steps.
In a successful run, each hidden unit is a line that cuts one corner of the square off from the other three. The two units take two corners of the same class. In these coordinates the classes are linearly separable, just as in the hand-made solution. Nobody designed these features; the network found them by fitting.
Success is not guaranteed, though. From 10 random initializations, 5 runs classify at least 99 % of the points. The other 5 stop at 69–73 % accuracy. The data and the architecture are the same; only the starting point differs. The loss is not convex in the weights. The topic Convex sets and functions in Mathematics for ML showed why: swapping two hidden units gives the same function, so every good solution has copies, and the average of two copies is usually a worse network.
With four hidden units, all 10 runs classify every point correctly. Extra width costs parameters and buys an easier optimization problem. The practical lesson: check a network over several random seeds, not one.
The multilayer perceptron
Stacking such layers gives the multilayer perceptron (MLP), also called a fully connected or feed-forward network:
Each hidden unit computes for one row of its weight matrix: a linear model of the previous layer, followed by a fixed nonlinearity. With , a hidden unit has the form of a logistic regression. The analogy stops at the form: a hidden unit has no observed 0/1 target of its own, and its weights are trained jointly with the rest of the network.
In practice a network processes a minibatch of objects at once, stored as the rows of . Then every layer is one matrix product, with the bias added to every row:
PyTorch's nn.Linear(d_in, d_out) stores its weight with shape (d_out, d_in), the shape of here, and computes x @ W.T + b.
Shapes. A classifier of digit images into 10 classes, with widths :
| layer | weight | bias | parameters | output for a batch of 32 |
|---|---|---|---|---|
| input | ||||
| 1 | 128 | 8,320 | ||
| 2 | 64 | 8,256 | ||
| 3 (logits) | 10 | 650 |
The network has parameters, almost all of them in the weight matrices. The count grows with the product of neighbouring widths.
Activation functions
Four activations cover most practice:
| range | typical use | |||
|---|---|---|---|---|
| sigmoid | output probabilities, gates | |||
| tanh | recurrent networks | |||
| ReLU | for , for | default for hidden layers | ||
| GELU | Transformers |
Here and are the distribution function and the density of the standard normal (see Continuous distributions in Probability Theory). Three properties matter.
- Saturation. Sigmoid and tanh flatten for large , where their derivative is close to zero. A unit driven there passes almost no signal to its weights. In a stack of sigmoid layers, each layer contributes a factor of at most ; the topic Training deep networks deals with that.
- ReLU has slope exactly 1 wherever it is active, and it is cheap to compute. Its weakness is the other side: for both the output and the slope are exactly zero. A unit whose pre-activation is negative on every input is called dead.
- GELU multiplies by the probability that a standard normal variable falls below it. It is a smooth ReLU that lets small negative values through: its minimum is at . BERT and GPT-2 use it.
Which one you pick matters less than having a nonlinearity at all. The next block shows the single property a one-hidden-layer network really needs from its activation.
What one hidden layer can do
How much can one hidden layer represent? Let be any continuous sigmoidal function: as and as . Cybenko (1989) proved the following. For every continuous on the cube and every there are and parameters , such that the sum stays within of everywhere on the cube:
is an MLP with one hidden layer of units and a linear output. Hornik (1991) extended this to any bounded nonconstant activation on any compact set. Leshno et al. (1993) settled it for unbounded ones such as ReLU: one hidden layer approximates every continuous function on compact sets if and only if the activation is not a polynomial. A polynomial activation of degree fails because the whole network is then a polynomial of degree at most , however wide it is.
ReLU units as a broken line. In one dimension the construction is explicit. Put knots on , and let be the slope of the segment from to . The broken line through these points is
Unit switches on at the knot and changes the slope by . For the largest error on is , , and with units. The error falls like , as the interpolation bound with spacing predicts.
The theorem is about existence. It does not promise:
- a reasonable size. The broken-line construction tiles the input. With 16 knots per axis in dimensions it needs cells: the curse of dimensionality from the topic Nearest neighbours;
- that training finds the weights. The experiment with XOR showed runs that stop elsewhere;
- that a sample is enough. Approximating the true function and estimating it from noisy examples are different problems. A wide network can fit any training set, noise included: overfitting from Validation and overfitting;
- anything outside the region. Beyond the training inputs a ReLU network just continues linearly, which the data rarely does.
Depth versus width
If one hidden layer is universal, why use many? Because for some functions composition is far more efficient than addition. A one-dimensional example makes this exact. On take the tent
It equals for and for , with values in . The composition runs the tent up and down twice: 4 linear pieces. Each further composition doubles the count, so has pieces. As a network, has hidden layers of 2 ReLU units each (Telgarsky, 2016).
A network with one hidden layer of ReLU units computes on a line. It is linear between its break points , so it has at most pieces. To represent exactly it needs units. For that is 31 units against the deep network's 10; for it is against 40.
The general results go the same way. The number of linear regions of a ReLU network can grow exponentially with depth but only polynomially with width (Montúfar et al., 2014). Depth lets later layers reuse what earlier layers computed. In image networks, early layers detect edges and later layers combine them into parts and objects; the course Deep Learning shows this in detail.
Depth has a price. Every layer adds another factor to the gradient, and deep stacks are harder to optimize than shallow ones. The topic Training deep networks deals with that.
Output layer and loss
Any network reads the same way: its last layer is a linear model on the features computed below it. Take the two-moons data: 1000 points with noise , half held out for testing. Logistic regression on the raw coordinates reaches a test accuracy of . A network with ReLU reaches . A fresh logistic regression fitted on the network's 16 last-layer features also gives . Everything nonlinear happened in the feature map; the classifier on top is the logistic regression of earlier topics.
So the output layer and the loss are chosen just as for linear models. The network outputs the parameters of a distribution for , and the loss is the negative log-likelihood, as in the topic Maximum likelihood of Probability Theory. Classes are here.
| task | output units | output activation | model for | loss |
|---|---|---|---|---|
| regression | 1 (or ) | none | squared error | |
| two classes | 1 logit | sigmoid | binary cross-entropy | |
| classes | logits | softmax | cross-entropy | |
| labels | logits | sigmoids | independent Bernoullis | sum of binary cross-entropies |
The lower rows are the softmax and independent-sigmoid models of Multiclass and multilabel classification, now on learned features. Write for the logits. With and true class , the cross-entropy is
For example, the logits give with sum , so . If the true class is the first, the loss is .
PyTorch's losses (MSELoss, BCEWithLogitsLoss, CrossEntropyLoss) take logits, not probabilities. They compute as with . For the logits the naive overflows, while the shifted form gives the loss exactly. Apply a softmax in the model and a loss on its probabilities, and this protection is lost.
A network is now a composition of simple functions with many parameters: 17,226 even for the small digit classifier. Gradient descent needs the derivative of the loss with respect to every one of them at every step. Perturbing each parameter in turn would cost two forward passes per parameter. The next topic, Backpropagation, applies the chain rule from the loss backwards and gets all of them for the price of a few forward passes, whatever the number of parameters. Beyond this course, Deep Learning builds on the same layers: convolutions, which are linear layers with shared local weights, and the architectures made of them.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.