Skip to content
BIASED

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 8×88 \times 8 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 l=1,…,Ll = 1, \dots, L of widths d1,…,dLd_1, \dots, d_L, with d0=dd_0 = d. Layer ll has a weight matrix Wl∈Rdl×dl−1W_l \in \mathbb R^{d_l \times d_{l-1}} and a bias bl∈Rdlb_l \in \mathbb R^{d_l}. It computes the pre-activation zlz_l and the activation hlh_l:

zl=Wlhl−1+bl,hl=φ(zl),h0=x.z_l = W_l h_{l-1} + b_l, \qquad h_l = \varphi(z_l), \qquad h_0 = x .

The activation function φ\varphi acts on each coordinate. In this topic φ\varphi is always an activation, not a kernel's feature map. The last layer has no activation: its output f(x)=zLf(x) = z_L 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:

W2(W1x+b1)+b2=(W2W1) x+(W2b1+b2).W_2 (W_1 x + b_1) + b_2 = (W_2 W_1)\, x + (W_2 b_1 + b_2) .

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 WL⋯W1W_L \cdots W_1. 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,

f(x)=W2 φ(W1x+b1)+b2.f(x) = W_2\, \varphi(W_1 x + b_1) + b_2 .

The output is a linear model on the features h=φ(W1x+b1)h = \varphi(W_1 x + b_1), and these features are learned too.

XOR. The four points (0,0),(0,1),(1,0),(1,1)(0,0), (0,1), (1,0), (1,1) with labels 0,1,1,00, 1, 1, 0 cannot be separated by a line. Suppose w1x1+w2x2+c>0w_1 x_1 + w_2 x_2 + c > 0 held exactly for the two points of class 1. Then w2+c>0w_2 + c > 0 and w1+c>0w_1 + c > 0, while c≤0c \le 0 and w1+w2+c≤0w_1 + w_2 + c \le 0. Adding the first two inequalities gives w1+w2+c>−c≥0w_1 + w_2 + c > -c \ge 0, a contradiction.

Two ReLU units are enough, with ReLU⁡(t)=max⁡(0,t)\operatorname{ReLU}(t) = \max(0, t). Take h1=ReLU⁡(x1+x2)h_1 = \operatorname{ReLU}(x_1 + x_2), h2=ReLU⁡(x1+x2−1)h_2 = \operatorname{ReLU}(x_1 + x_2 - 1) and f=h1−2h2f = h_1 - 2h_2:

xx x1+x2x_1 + x_2 h1h_1 h2h_2 ff
(0,0)(0, 0) 0 0 0 0
(0,1)(0, 1) 1 1 0 1
(1,0)(1, 0) 1 1 0 1
(1,1)(1, 1) 2 2 1 0

In the hidden coordinates (h1,h2)(h_1, h_2) the inputs become (0,0)(0,0), (1,0)(1,0), (1,0)(1,0) and (2,1)(2,1). Both points of class 1 land on the same spot, and a line such as h1−2h2=12h_1 - 2h_2 = \tfrac12 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 (±1,±1)(\pm 1, \pm 1), with standard deviation 0.30.3. 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 0.050.05, 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:

zl=Wlhl−1+bl,hl=φ(zl),l=1,…,L−1,f(x)=WLhL−1+bL.\begin{aligned} z_l &= W_l h_{l-1} + b_l, \qquad h_l = \varphi(z_l), \qquad l = 1, \dots, L-1, \\ f(x) &= W_L h_{L-1} + b_L . \end{aligned}

Each hidden unit computes φ(w⊤h+b)\varphi(w^\top h + b) for one row ww of its weight matrix: a linear model of the previous layer, followed by a fixed nonlinearity. With φ=σ\varphi = \sigma, 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 nn objects at once, stored as the rows of X∈Rn×dX \in \mathbb R^{n \times d}. Then every layer is one matrix product, with the bias added to every row:

Zl=Hl−1Wl⊤+1 bl⊤,H0=X.Z_l = H_{l-1} W_l^\top + \mathbf 1\, b_l^\top, \qquad H_0 = X .

PyTorch's nn.Linear(d_in, d_out) stores its weight with shape (d_out, d_in), the shape of WlW_l here, and computes x @ W.T + b.

Shapes. A classifier of 8×88 \times 8 digit images into 10 classes, with widths 64→128→64→1064 \to 128 \to 64 \to 10:

layer weight WlW_l bias blb_l parameters output for a batch of 32
input 32×6432 \times 64
1 128×64128 \times 64 128 8,320 32×12832 \times 128
2 64×12864 \times 128 64 8,256 32×6432 \times 64
3 (logits) 10×6410 \times 64 10 650 32×1032 \times 10

The network has 17,22617{,}226 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:

φ(t)\varphi(t) φ′(t)\varphi'(t) range typical use
sigmoid σ(t)=11+e−t\sigma(t) = \dfrac{1}{1 + e^{-t}} σ(t) (1−σ(t))≤14\sigma(t)\,(1 - \sigma(t)) \le \tfrac14 (0,1)(0, 1) output probabilities, gates
tanh tanh⁡t=2σ(2t)−1\tanh t = 2\sigma(2t) - 1 1−tanh⁡2t≤11 - \tanh^2 t \le 1 (−1,1)(-1, 1) recurrent networks
ReLU max⁡(0,t)\max(0, t) 11 for t>0t > 0, 00 for t<0t < 0 [0,∞)[0, \infty) default for hidden layers
GELU t Φ(t)t\, \Phi(t) Φ(t)+t ϕ(t)\Phi(t) + t\, \phi(t) [−0.170,∞)[-0.170, \infty) Transformers

Here Φ\Phi and ϕ\phi 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 ∣t∣\lvert t \rvert, 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 14\tfrac14; 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 t<0t < 0 both the output and the slope are exactly zero. A unit whose pre-activation is negative on every input is called dead.
  • GELU multiplies tt by the probability Φ(t)\Phi(t) that a standard normal variable falls below it. It is a smooth ReLU that lets small negative values through: its minimum is −0.170-0.170 at t=−0.752t = -0.752. 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 σ\sigma be any continuous sigmoidal function: σ(t)→1\sigma(t) \to 1 as t→+∞t \to +\infty and σ(t)→0\sigma(t) \to 0 as t→−∞t \to -\infty. Cybenko (1989) proved the following. For every continuous gg on the cube [0,1]d[0,1]^d and every ε>0\varepsilon > 0 there are NN and parameters αj,βj∈R\alpha_j, \beta_j \in \mathbb R, wj∈Rdw_j \in \mathbb R^d such that the sum GG stays within ε\varepsilon of gg everywhere on the cube:

G(x)=∑j=1Nαj σ(wj⊤x+βj),max⁡x∈[0,1]d∣G(x)−g(x)∣<ε.G(x) = \sum_{j=1}^{N} \alpha_j\, \sigma(w_j^\top x + \beta_j), \qquad \max_{x \in [0,1]^d} \lvert G(x) - g(x) \rvert < \varepsilon .

GG is an MLP with one hidden layer of NN 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 kk fails because the whole network is then a polynomial of degree at most kk, however wide it is.

ReLU units as a broken line. In one dimension the construction is explicit. Put knots xk=k/Nx_k = k/N on [0,1][0, 1], and let sks_k be the slope of the segment from (xk,g(xk))(x_k, g(x_k)) to (xk+1,g(xk+1))(x_{k+1}, g(x_{k+1})). The broken line through these points is

g^(x)=g(0)+∑k=0N−1ck ReLU⁡(x−xk),c0=s0,  ck=sk−sk−1.\hat g(x) = g(0) + \sum_{k=0}^{N-1} c_k\, \operatorname{ReLU}(x - x_k), \qquad c_0 = s_0,\ \ c_k = s_k - s_{k-1} .

Unit kk switches on at the knot xkx_k and changes the slope by ckc_k. For g(x)=sin⁡2πxg(x) = \sin 2\pi x the largest error on [0,1][0, 1] is 0.21050.2105, 0.07040.0704, 0.01880.0188 and 0.00480.0048 with N=4,8,16,32N = 4, 8, 16, 32 units. The error falls like 1/N21/N^2, as the interpolation bound 18h2max⁡∣g′′∣\tfrac18 h^2 \max \lvert g'' \rvert with spacing h=1/Nh = 1/N 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 d=10d = 10 dimensions it needs 1610≈1.1⋅101216^{10} \approx 1.1 \cdot 10^{12} 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 nn 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 [0,1][0, 1] take the tent

g(x)=2ReLU⁡(x)−4ReLU⁡(x−12).g(x) = 2\operatorname{ReLU}(x) - 4\operatorname{ReLU}\big(x - \tfrac12\big) .

It equals 2x2x for x≤12x \le \tfrac12 and 2−2x2 - 2x for x≥12x \ge \tfrac12, with values in [0,1][0, 1]. The composition g∘gg \circ g runs the tent up and down twice: 4 linear pieces. Each further composition doubles the count, so gk=g∘⋯∘gg^k = g \circ \dots \circ g has 2k2^k pieces. As a network, gkg^k has kk hidden layers of 2 ReLU units each (Telgarsky, 2016).

A network with one hidden layer of mm ReLU units computes c+∑j=1majReLU⁡(wjx+βj)c + \sum_{j=1}^m a_j \operatorname{ReLU}(w_j x + \beta_j) on a line. It is linear between its mm break points −βj/wj-\beta_j / w_j, so it has at most m+1m + 1 pieces. To represent gkg^k exactly it needs m≥2k−1m \ge 2^k - 1 units. For k=5k = 5 that is 31 units against the deep network's 10; for k=20k = 20 it is 1,048,5751{,}048{,}575 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 hL−1(x)h_{L-1}(x) computed below it. Take the two-moons data: 1000 points with noise 0.20.2, half held out for testing. Logistic regression on the raw coordinates reaches a test accuracy of 0.8480.848. A network 2→16→16→12 \to 16 \to 16 \to 1 with ReLU reaches 0.9580.958. A fresh logistic regression fitted on the network's 16 last-layer features also gives 0.9580.958. 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 yy, and the loss is the negative log-likelihood, as in the topic Maximum likelihood of Probability Theory. Classes are {0,1}\{0, 1\} here.

task output units output activation model for yy loss
regression 1 (or kk) none N(f(x),σ2)\mathcal N(f(x), \sigma^2) squared error
two classes 1 logit sigmoid Bernoulli(σ(f(x)))\mathrm{Bernoulli}(\sigma(f(x))) binary cross-entropy
KK classes KK logits softmax Categorical(softmax⁡f(x))\mathrm{Categorical}(\operatorname{softmax} f(x)) cross-entropy
KK labels KK logits KK sigmoids KK independent Bernoullis sum of KK binary cross-entropies

The lower rows are the softmax and independent-sigmoid models of Multiclass and multilabel classification, now on learned features. Write z=zLz = z_L for the logits. With pk=ezk/∑jezjp_k = e^{z_k} / \sum_j e^{z_j} and true class yy, the cross-entropy is

−log⁡py=−zy+log⁡∑j=1Kezj.-\log p_y = -z_y + \log \sum_{j=1}^{K} e^{z_j} .

For example, the logits z=(2,1,−1)z = (2, 1, -1) give ez=(7.389,2.718,0.368)e^z = (7.389, 2.718, 0.368) with sum 10.47510.475, so p=(0.705,0.259,0.035)p = (0.705, 0.259, 0.035). If the true class is the first, the loss is −log⁡0.705=0.349-\log 0.705 = 0.349.

PyTorch's losses (MSELoss, BCEWithLogitsLoss, CrossEntropyLoss) take logits, not probabilities. They compute log⁡∑jezj\log \sum_j e^{z_j} as m+log⁡∑jezj−mm + \log \sum_j e^{z_j - m} with m=max⁡jzjm = \max_j z_j. For the logits (1000,0)(1000, 0) the naive e1000e^{1000} 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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.