Module 2

Neural networks

One sigmoid unit draws one straight boundary. Wire a few of them into layers, put a bend between the layers, and the same recipe can carve out almost any shape.

Why it matters

The multi-layer perceptron is the first model in this course that learns its own features: the early layers reshape the input until the last layer, plain logistic regression, can separate it. Convolutional networks, LSTMs and transformers are all particular ways of wiring up the layer you meet here, and every transformer block contains a small MLP of exactly this kind.

The idea

From a neuron to a layer

A neuron takes a weighted sum of its inputs, adds a bias, and passes the result through a fixed non-linear function $\phi$, the activation:

$$a = \phi(w^{\top} x + b).$$

With $\phi = \sigma$ this is logistic regression from module 1. A layer is $m$ neurons reading the same input. Put their weight vectors side by side as the columns of a matrix $W \in \mathbb{R}^{d \times m}$, and stack a batch of $n$ inputs as the rows of $X \in \mathbb{R}^{n \times d}$. The whole layer, for the whole batch, is one line:

$$A = \phi(XW + b), \qquad A \in \mathbb{R}^{n \times m},$$

with $b \in \mathbb{R}^m$ added to every row and $\phi$ applied entry by entry.

Stacking layers

A multi-layer perceptron feeds each layer's output to the next. With $A^{(0)} = X$:

$$A^{(l)} = \phi\big(A^{(l-1)} W^{(l)} + b^{(l)}\big) \quad \text{for } l = 1, \dots, L-1, \qquad z = A^{(L-1)} W^{(L)} + b^{(L)}, \qquad p = \sigma(z).$$

The layers before the last are called hidden. The last step is logistic regression again, but on the features $A^{(L-1)}$ that the hidden layers compute, and the whole thing is trained with the cross-entropy loss from module 1. A layer mapping $n_{\text{in}}$ values to $n_{\text{out}}$ has $(n_{\text{in}} + 1)\, n_{\text{out}}$ parameters.

Why the bend is essential

Leave out $\phi$ and two layers collapse into one:

$$\big(XW^{(1)} + b^{(1)}\big) W^{(2)} + b^{(2)} = X \big(W^{(1)} W^{(2)}\big) + \big(b^{(1)} W^{(2)} + b^{(2)}\big).$$

A stack of linear layers is a linear layer, however deep. The non-linearity is what makes depth mean something. Three common choices:

Activation$\phi(z)$RangeSlope $\phi'(z)$
tanh$\tanh z$$(-1, 1)$$1 - \phi(z)^2$
sigmoid$1 / (1 + e^{-z})$$(0, 1)$$\phi(z)\,(1 - \phi(z))$
ReLU$\max(0, z)$$[0, \infty)$$1$ if $z \gt 0$, else $0$

What one unit cannot do

The classic example is XOR: the label is 1 for $(0,1)$ and $(1,0)$, and 0 for $(0,0)$ and $(1,1)$. Suppose a single unit separated them, with $w_1 x_1 + w_2 x_2 + b$ positive on the first pair and negative on the second. Adding the two positive cases gives $w_1 + w_2 + 2b \gt 0$; adding the two negative cases gives $w_1 + w_2 + 2b \lt 0$. No line does it. Two hidden units do, as you will show in the exercise.

How much can a network represent?

The universal approximation theorem says that a network with one hidden layer and a non-polynomial activation can approximate any continuous function on a closed, bounded region as closely as you like, given enough hidden units. It is a statement that good weights exist. It does not say how many units are needed, nor that gradient descent will find those weights, nor that the result will be right on data it has not seen.

Where the weights start

If every weight in a layer started equal, every unit would compute the same thing, receive the same gradient and stay identical forever. So weights start random. Their scale matters too: drawing them with standard deviation around $1/\sqrt{n_{\text{in}}}$ keeps the size of the signal roughly constant from layer to layer instead of exploding or dying out.

Live demo: a two-moons playground

Train a small network in your browser

What the network predicts at every point of the plane

class 1class 0background: predicted class, stronger colour = more confident

Training loss

200 points, trained on all of them at every step by gradient descent with momentum (module 4 explains momentum). Changing the architecture draws new random weights.

Try this

  1. Set hidden layers to 0 and train. This is logistic regression: the boundary is a straight line and the accuracy gets stuck well short of 100%.
  2. Set hidden layers to 3 and the activation to none (linear). Three layers, same straight line. Depth without a non-linearity buys nothing.
  3. With one hidden layer of tanh units, find the smallest number of units that gets above 99%. Press New random weights a few times before you decide: small networks sometimes get stuck.
  4. Switch to ReLU. Look closely at the boundary: it is made of straight pieces, because each ReLU unit is itself two straight pieces joined at a fold.

Exercise

Fit XOR with the fewest hidden units

Write the forward pass of a network with two inputs, one hidden layer of tanh units and a sigmoid output. Then set HIDDEN to the smallest number of hidden units that can get all four XOR cases right. A training function is provided; how it computes its gradients is the subject of module 3.

The tests train a network with your HIDDEN from ten different random starts and use your forward to score it. Small networks often get stuck, so one success in ten is enough.

Check yourself

How many parameters does a network with layer sizes 2 → 8 → 8 → 1 have?

$(2 + 1) \cdot 8 + (8 + 1) \cdot 8 + (8 + 1) \cdot 1 = 24 + 72 + 9 = 105$. The demo shows this count for whatever you build.

Why does a deep network with no activation function do no better than logistic regression?

Each layer is an affine map, and a composition of affine maps is affine. The whole stack equals one layer with weights $W^{(1)} W^{(2)} \cdots W^{(L)}$, so its decision boundary is still a straight line.

The universal approximation theorem says one hidden layer is enough. Name two things it does not promise.

Any two of: how many hidden units are needed (it can be impractically many); that gradient descent will find the right weights; that a network fitting the training data will be right on new data.

Where this leads

The training function you were handed contains three lines that compute gradients for both layers at once. Module 3 derives them, for any number of layers, and you will write them yourself.

Sources: I. Goodfellow, Y. Bengio and A. Courville, Deep Learning, MIT Press (2016), ch. 6; G. Cybenko, “Approximation by superpositions of a sigmoidal function”, Mathematics of Control, Signals and Systems 2 (1989); K. Hornik, “Approximation capabilities of multilayer feedforward networks”, Neural Networks 4 (1991); M. Leshno, V. Lin, A. Pinkus and S. Schocken, “Multilayer feedforward networks with a nonpolynomial activation function can approximate any function”, Neural Networks 6 (1993); X. Glorot and Y. Bengio, “Understanding the difficulty of training deep feedforward neural networks”, AISTATS (2010).