Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Multi-layer perceptrons

P4.340 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A hidden layer is the idea that lifts a model from straight-line boundaries to curved ones, and nearly every network in this course is a stack of such layers.

Before this: From neurons to the perceptron, The perceptron learning rule and the XOR problem, Matrices as data and as transformations, Matrix multiplication

After this lesson you can

  • Explain why a model with no hidden layer cannot solve XOR, and build a 2-2-1 network that does, with every number checked
  • Write the forward pass of a network with one hidden layer, name its parts, and count its parameters
  • Show that stacked layers without a squashing step collapse into one linear layer, and say what the squash adds
  • Describe how hidden layers bend the plane so the output unit can draw a straight line in the new space, and what that gives in the input plane

A single neuron draws one straight line (P4.1). That is why it fails on XOR (P4.2): no line puts the corners (0,0)(0,0) and (1,1)(1,1) on one side and (1,0)(1,0) and (0,1)(0,1) on the other. The fix is small. Let neurons read the outputs of other neurons. Two neurons draw two lines, and a third neuron looks at both.

This lesson builds that idea from the ground up: a network for XOR with weights you can check by hand, the general formulas, the reason a squashing step is essential, and what the extra layers do to the plane. A playground lets you train a small network and watch the space bend.

The idea: neurons that read neurons

Take the neuron of P4.1: it computes a weighted sum of its inputs, adds a bias, and applies a function. Now arrange neurons in layers:

  • The input layer is just the numbers x1,x2x_1, x_2. It does no computation.
  • A hidden layer is a layer of neurons that read the inputs. Their outputs are not the answer; they are passed on. Nobody sees them from outside, which is why they are called hidden.
  • The output layer is a neuron that reads the hidden outputs and gives the prediction y^\hat y.

A network with one hidden layer of two units and one output unit is called a 2-2-1 network: 2 inputs, 2 hidden units, 1 output. Information flows one way, from the inputs to the output, so this is a feed-forward network. Each neuron reads every output of the layer before it. A layer built like that is called fully connected or dense.

Building XOR by hand

Use the ReLU function ReLU(z)=max⁡(0,z)\mathrm{ReLU}(z)=\max(0,z) from P1.A1 as the squash of the hidden units. The two hidden units are

h1=ReLU(x1+x2),h2=ReLU(x1+x2−1).\begin{aligned} h_1&=\mathrm{ReLU}(x_1+x_2),\\ h_2&=\mathrm{ReLU}(x_1+x_2-1). \end{aligned}

The first unit tells how many inputs are on. The second is positive only when both are on. The output unit computes z=h1−2h2z=h_1-2h_2, and the prediction is class 1 when z>0.5z>0.5.

input (x1,x2)(x_1,x_2)hidden (h1,h2)(h_1,h_2)z=h1−2h2z=h_1-2h_2class
(0,0)(0,0)(0,0)(0,0)000
(1,0)(1,0)(1,0)(1,0)111
(0,1)(0,1)(1,0)(1,0)111
(1,1)(1,1)(2,1)(2,1)000

That is XOR, solved with weights you can read off. P4.2 solved it with three perceptrons (OR, NAND, AND); this is a different, smaller solution, and more than one set of weights works. The other way out in P4.2, adding the feature x1x2x_1x_2 by hand, is what a learned hidden layer does for itself. In weight-matrix form, W1=(1111)\mathbf{W}_1=\begin{pmatrix}1&1\\1&1\end{pmatrix} and b1=(0,−1)\mathbf{b}_1=(0,-1) for the hidden layer, and w2=(1,−2)\mathbf{w}_2=(1,-2) and b2=0b_2=0 for the output.

Now look at the hidden plane, with h1h_1 across and h2h_2 up. The four points land at (0,0)(0,0), (1,0)(1,0), (1,0)(1,0) and (2,1)(2,1). The two class-1 points sit on the same spot. The hidden layer has folded the plane so that the two far-apart corners land on top of each other. In the new plane the classes can be split by a straight line: h1−2h2=0.5h_1-2h_2=0.5 has (1,0)(1,0) on one side and (0,0)(0,0) and (2,1)(2,1) on the other.

Folding a sheet of paper is a fair picture: two marks far apart can be brought together. The picture breaks in one way. A paper fold keeps every distance on each side, while a ReLU flattens a whole half-plane onto a line, so information is lost on purpose.

Pulled back to the input plane, that straight line is two parallel lines, x1+x2=0.5x_1+x_2=0.5 and x1+x2=1.5x_1+x_2=1.5, with class 1 in the strip between them. The network is really a function of one number, s=x1+x2s=x_1+x_2. It gives 00 for s<0s<0, then ss for 0<s<10<s<1, then 2−s2-s for s>1s>1: a tent with its peak at s=1s=1. It is built from straight pieces, so the boundary is made of straight pieces too.

Go deeper The same network with step units: OR and AND

P4.1 and P4.2 use a step unit, which outputs 1 when its sum is above a threshold and 0 otherwise. With steps the XOR network reads like logic. Let h1=step(x1+x2−0.5)h_1=\text{step}(x_1+x_2-0.5) (this is OR: on when at least one input is on) and h2=step(x1+x2−1.5)h_2=\text{step}(x_1+x_2-1.5) (this is AND: on only when both are on). The hidden values are (0,0)(0,0), (1,0)(1,0), (1,0)(1,0) and (1,1)(1,1). The output h1−h2−0.5h_1-h_2-0.5 is −0.5-0.5, 0.50.5, 0.50.5 and −0.5-0.5, which gives XOR as “OR but not AND”. Both versions fold the plane. The ReLU version is closer to what training uses today, because a step has zero slope everywhere except at its jump, and gradient descent needs a slope (P4.4 and P4.8).

The general form

Write a one-hidden-layer network with dd inputs and mm hidden units in two lines:

h=f(W1x+b1),y^=g(W2h+b2).\begin{aligned} \mathbf{h}&=f(\mathbf{W}_1\mathbf{x}+\mathbf{b}_1),\\ \hat y&=g(\mathbf{W}_2\mathbf{h}+b_2). \end{aligned}

Here x\mathbf{x} has dd entries, W1\mathbf{W}_1 has mm rows and dd columns, and b1\mathbf{b}_1 and h\mathbf{h} have mm entries. The row jj of W1\mathbf{W}_1 holds the weights of hidden unit jj. The function ff is the hidden squash, applied to each entry on its own. The second line is the output layer: W2\mathbf{W}_2 has one row and mm columns, and gg is the output function. For XOR, d=m=2d=m=2.

Each line is a layer from P1.B5: a matrix, a shift, and a squash. In words, the network is “layer 1, then layer 2”:

y^=layer2(layer1(x)).\hat y=\text{layer}_2\big(\text{layer}_1(\mathbf{x})\big).

This is a composition of functions, the same idea as in P1.A1: each layer is a simple function, and stacking them builds a complicated one.

Here is one forward pass with small numbers, reusing the layer from P1.B5. Let W1=(1−121)\mathbf{W}_1=\begin{pmatrix}1&-1\\2&1\end{pmatrix}, b1=(1,−2)\mathbf{b}_1=(1,-2) and x=(1,2)\mathbf{x}=(1,2), with the sigmoid σ(z)=1/(1+e−z)\sigma(z)=1/(1+e^{-z}) from P1.A5 as the hidden squash. Then z=W1x+b1=(0,2)\mathbf{z}=\mathbf{W}_1\mathbf{x}+\mathbf{b}_1=(0,2) and h=σ(z)≈(0.5,0.881)\mathbf{h}=\sigma(\mathbf{z})\approx(0.5,0.881). Give the output unit w2=(2,−1)\mathbf{w}_2=(2,-1) and b2=0.3b_2=0.3, and let g=σg=\sigma. Then w2⋅h+b2≈0.419\mathbf{w}_2\cdot\mathbf{h}+b_2\approx0.419 and y^=σ(0.419)≈0.603\hat y=\sigma(0.419)\approx0.603. The network says “class 1 with probability 0.60”.

Counting parameters

The parameters are all the weights and biases, the numbers that training changes. A dense layer with ninn_{\text{in}} inputs and noutn_{\text{out}} units has nin noutn_{\text{in}}\,n_{\text{out}} weights and noutn_{\text{out}} biases:

nin nout+nout.n_{\text{in}}\,n_{\text{out}}+n_{\text{out}}.

The 2-2-1 network has (2⋅2+2)+(2⋅1+1)=6+3=9(2\cdot2+2)+(2\cdot1+1)=6+3=9 parameters. Now a network of realistic size: a picture of a handwritten digit with 28×28=78428\times28=784 pixels, a hidden layer of 128 units and 10 outputs, one per digit (a 784-128-10 network):

  • layer 1: 784⋅128+128=100,480784\cdot128+128=100{,}480
  • layer 2: 128⋅10+10=1,290128\cdot10+10=1{,}290
  • total: 101,770101{,}770

For comparison, softmax regression on the same pixels (P3.A8) has 784⋅10+10=7,850784\cdot10+10=7{,}850 parameters. The hidden layer makes the model about 13 times bigger.

Names you will meet

  • Unit and neuron mean the same thing here. Width is the number of units in a layer. Depth is the number of layers; a network with several hidden layers is called deep. People count layers differently, so state what you count: the 784-128-10 network has one hidden layer and two layers of weights.
  • Multi-layer perceptron (MLP) means a feed-forward network of dense layers. “Perceptron” is a historical word: the original perceptron used a step unit (P4.1). Modern MLPs use smooth or ReLU squashes (compared in P4.4), because those have a slope that gradient descent can follow. The name stayed.
  • How many hidden units? It is a free choice, called a hyperparameter (P3.A4, P4.23). The hidden layer can be narrower or wider than the input: 128 units after 784 inputs is a squeeze, and 4 units after 2 inputs is an expansion.
  • Hidden squash ff is the same for every hidden unit in a layer. The output function gg depends on the task, as the next section explains.

Why the squash is essential

What if we leave the squash out? Take P1.B6’s example: W1=(111−101)\mathbf{W}_1=\begin{pmatrix}1&1\\1&-1\\0&1\end{pmatrix} (3×23\times2), W2=(101011)\mathbf{W}_2=\begin{pmatrix}1&0&1\\0&1&1\end{pmatrix} (2×32\times3) and x=(1,2)\mathbf{x}=(1,2). Applying the layers one after the other gives W1x=(3,−1,2)\mathbf{W}_1\mathbf{x}=(3,-1,2) and then W2(3,−1,2)=(5,1)\mathbf{W}_2(3,-1,2)=(5,1). The single matrix

W2W1=(1210)\mathbf{W}_2\mathbf{W}_1=\begin{pmatrix}1&2\\1&0\end{pmatrix}

applied to x\mathbf{x} also gives (5,1)(5,1). The two layers are one layer. With biases the same holds: W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)\mathbf{W}_2(\mathbf{W}_1\mathbf{x}+\mathbf{b}_1)+\mathbf{b}_2=(\mathbf{W}_2\mathbf{W}_1)\mathbf{x}+(\mathbf{W}_2\mathbf{b}_1+\mathbf{b}_2), still one matrix and one bias. Ten stacked layers are also one. A straight-line model stays a straight-line model however deep you stack it, and it fails on XOR for the same reason as a single neuron.

Put a ReLU between the layers and the picture changes: ReLU(3,−1,2)=(3,0,2)\mathrm{ReLU}(3,-1,2)=(3,0,2), and W2(3,0,2)=(5,2)\mathbf{W}_2(3,0,2)=(5,2), which is not (5,1)(5,1). No single matrix reproduces that. The squash is what makes depth useful. P4.4 compares the squashes in detail; for this lesson ReLU, tanh and the sigmoid of P1.A5 are enough.

What hidden layers do to the plane

A layer does three things to every point of the plane, one after another:

  1. A linear map Wx\mathbf{W}\mathbf{x}: stretch, turn, shear (P1.B5). Straight lines stay straight, and the origin stays where it is.
  2. A shift +b+\mathbf{b}: slide the whole plane.
  3. A squash on each entry: tanh squeezes every coordinate into (−1,1)(-1,1), so far-away points are pulled into a box. ReLU sets negative coordinates to 00, which flattens the half-plane on one side of a line onto that line.

Steps 1 and 2 are the straight part. Step 3 is the bend. After a few layers, points that sat in a tangle can end up in separated groups. The output unit then does the simplest thing there is: it draws one straight line in the space of the last hidden layer. Take that straight line back to the input plane and it becomes the decision boundary of the whole network, which can be curved.

P3.B7 did something similar by hand. To separate two rings, it chose a lift, adding the coordinate x12+x22x_1^2+x_2^2, and then split the lifted data with a flat plane. A hidden layer is also a lift, x↦f(W1x+b1)\mathbf{x}\mapsto f(\mathbf{W}_1\mathbf{x}+\mathbf{b}_1), but its weights are learned from the data instead of fixed in advance. That is one main difference between kernel methods and neural networks: the lift is learned, not fixed in advance (a kernel’s width is still tuned, but its shape is chosen by hand). It is also the answer to the limit of softmax regression (P3.A8), which draws only straight boundaries: change the features, or let a network learn them.

The playground below trains a small network by gradient descent. The left plane shows the input points and the boundary. The right plane shows where the same points land after the last hidden layer, which always has two units so that it is a plane. It also shows the grid of lines from the left plane, bent by the layers, and the single straight line that the output unit draws.

Data:
Network:
Squash:
Learning rate η:
Input plane (x₁, x₂)
-2-2-1-1001122x₁x₂
Hidden plane (h₁, h₂), last hidden layer
−101−101h₁h₂
class 0 (blue) class 1 (pink) where the output is 0.5 grid lines (solid: x₁ constant, dashed: x₂ constant)
step = 0 of 2000
loss = 0.835
correct = 45%

This is the random starting network. The right-hand plane shows where the first guess sends each point. Press Play.

Made-up points, 80 per data set. Network: 2 → 2 → 1 (inputs, hidden units, output), η = 0.5, full-batch gradient descent on the cross-entropy loss. “New start” picks another random starting network. The right-hand plane is the output of the last hidden layer, which always has two units.

Playground: hidden layers warp the plane. Press Play and watch the right-hand plane pull the two classes apart until one straight line separates them. The same line, mapped back, is the boundary on the left. Blue circles are class 0 and pink triangles are class 1. The data are made up; the percentage is training accuracy.

Things to try, in order:

  1. Leave XOR, 2 → 2 → 1 and tanh, and press Play. The accuracy climbs to about 99 percent. In the right-hand plane the two classes move to opposite corners, and the boundary on the left bends into a band along the diagonal from top-left to bottom-right.
  2. Set the squash to none (linear) and train. The accuracy stays near 50 percent, because the whole network is one straight line, as the collapse above says. The right-hand plane is only a stretched, turned copy of the left one.
  3. Choose Circles with 2 → 2 → 1. It stalls at about 80 percent. Switch to 2 → 4 → 2 → 1: it reaches 100 percent, and the right-hand plane shows the inner ring pushed to one side of a line.
  4. Go back to XOR with 2 → 2 → 1 and press New start a few times. Some starts reach about 99 percent and some stall near 70 percent. Same network, same data, different random starting weights.
  5. Try ReLU. Its boundaries are made of straight pieces; tanh gives smooth ones. ReLU does not always train better: on XOR with 2 → 2 → 1 it stalls at 75 percent from all six starts, even though a network of that size and squash can solve XOR (you built one above). On Circles with 2 → 4 → 2 → 1, start 5, both units of the last hidden layer output 00 for every point, so the right-hand plane collapses to a single dot and nothing can be learned.
Go deeper Why two tanh units cannot enclose a disk

Two tanh hidden units and a sigmoid output give a class-1 region {atanh⁡u+btanh⁡v+c>0}\{a\tanh u+b\tanh v+c>0\}, where uu and vv are the two weighted sums. Write t1=tanh⁡ut_1=\tanh u and t2=tanh⁡vt_2=\tanh v. The expression at1+bt2+ca t_1+b t_2+c is linear in (t1,t2)(t_1,t_2), and the pair (t1,t2)(t_1,t_2) always lies strictly inside the square (−1,1)2(-1,1)^2. A linear function on a square is largest at a corner. If the class-1 region were bounded, then far away in every direction the class is 0, and (when the two sums are independent, so that uu and vv can both take any values) far points exist whose (t1,t2)(t_1,t_2) lie as close as we like to each of the four corners. So the value at every corner, taken as a limit, is at most 0, and then at1+bt2+c≤0at_1+bt_2+c\le0 everywhere inside the square: the region is empty. (If the two sums depend on one direction only, the region is a strip, which is not bounded.) So no bounded class-1 region, a disk included, is possible with two such units. Three units can do it, and the playground shows the difference.

ReLU networks are made of flat pieces

With ReLU squashes, a network is built from straight pieces. Each hidden unit has a line in the input plane where its sum w⋅x+b\mathbf{w}\cdot\mathbf{x}+b is zero. On one side the unit is on and passes its sum through; on the other it outputs 00. The lines cut the plane into regions, and inside each region every unit is either on or off, so the value w2⋅h+b2\mathbf{w}_2\cdot\mathbf{h}+b_2 is a plain linear function there. Different regions have different linear functions, and the pieces join without a jump.

How many regions? Lines in general position (none parallel, no three through one point) cut the plane into at most 1+n+(n2)1+n+\binom n2 regions for nn lines. That is at most 44 for 22 units, 77 for 33 and 1111 for 44. The XOR network has only 33, because its two lines are parallel (both are x1+x2=x_1+x_2= a constant): the regions are s<0s<0, 0<s<10<s<1 and s>1s>1, the three pieces of the tent. More units give more pieces, which is how a wider layer draws a more detailed boundary.

Width versus depth

A wider layer adds lines side by side. A second layer works on the output of the first, so it can fold the folded plane again. Here is the smallest picture of that, on one input xx between 00 and 11. The tent function T(x)=2 ReLU(x)−4 ReLU(x−0.5)T(x)=2\,\mathrm{ReLU}(x)-4\,\mathrm{ReLU}(x-0.5) uses two hidden units. It rises from 00 at x=0x=0 to 11 at x=0.5x=0.5, then falls back to 00 at x=1x=1. Feed its output into another copy, and again:

  • one copy, 2 hidden units: 2 straight pieces
  • two copies in a row, 4 hidden units: 4 pieces
  • three copies in a row, 6 hidden units: 8 pieces

Compare this with a single hidden layer: nn ReLU units on a line give at most n+1n+1 pieces, so 6 units give at most 7. The deep stack, with the same number of units, reached 8, and each extra copy doubles the count. These weights were chosen by hand to show the effect. Training does not usually find such a perfect zig-zag, so treat this as a picture of what depth can do, not a promise of what it will do. Whether to go wide or deep is a design choice that depends on the problem and the data (P4.23). P4.11 shows what one wide hidden layer can reach, and P4.16 and P4.20 explain why very deep networks need extra care.

The output layer decides what the network predicts

The hidden layers are the same whatever the task. Only the output layer changes:

  • Two classes: one output unit with a sigmoid. Its output is the probability of class 1, the same as logistic regression (P3.A7) applied to the hidden values h\mathbf{h} instead of the raw inputs.
  • KK classes: KK output units followed by a softmax, like softmax regression (P3.A8), again applied to h\mathbf{h}.
  • A number (a price, a temperature): one output unit with no squash, so the answer can be any value.

So the last layer of a classifier is a logistic or softmax regression, and the layers before it are a feature extractor that is trained along with it. The 784-128-10 network above is this kind of classifier with 10 classes.

The loss is not convex

A model with no hidden layer, such as linear or logistic regression, has a convex loss, so gradient descent finds the best weights from any start (P1.F2). With hidden layers, that guarantee is gone, for two reasons that P1.F2 shows.

Weights multiply. In the tiny model y^=w1w2x\hat y=w_1w_2x, both (w1,w2)=(1,2)(w_1,w_2)=(1,2) and (−1,−2)(-1,-2) fit a target of 2x2x perfectly, but their midpoint (0,0)(0,0) gives loss 44 at x=1x=1. A convex loss cannot do that.

The same function has many settings. Swapping two hidden units changes nothing, because a sum does not care about order. Take y^=a1tanh⁡(w1x)+a2tanh⁡(w2x)\hat y=a_1\tanh(w_1x)+a_2\tanh(w_2x) with (a1,w1,a2,w2)=(1.5,0.7,−0.4,2.0)(a_1,w_1,a_2,w_2)=(1.5,0.7,-0.4,2.0). At x=−1x=-1, 0.50.5 and 22 it predicts −0.521-0.521, 0.2000.200 and 0.9280.928. The swapped setting (−0.4,2.0,1.5,0.7)(-0.4,2.0,1.5,0.7) gives exactly the same predictions, so both have the same loss. Their midpoint (0.55,1.35,0.55,1.35)(0.55,1.35,0.55,1.35) predicts −0.961-0.961, 0.6470.647 and 1.0901.090, a worse fit, with a mean squared error of 0.1400.140 against the other two. So the loss is not convex.

In practice this means the starting weights (and, with mini-batches, the order of the data) decide where training ends. The New start button showed the first part. Gradient descent still finds good solutions for large networks, but no theorem says it will find the best one. P4.12 covers how to choose starting weights.

Go deeper Counting the copies of one network

A hidden layer with nn units can be reordered in n!n! ways, and each ordering is the same function. For n=3n=3 that is 66 settings, and for n=10n=10 it is 3,628,8003{,}628{,}800. For tanh there is a second symmetry: tanh⁡(−z)=−tanh⁡(z)\tanh(-z)=-\tanh(z), so negating one unit’s incoming weights and bias and also its outgoing weight changes nothing. All these settings sit at the same height of the loss landscape, which is one more reason the landscape is not a single bowl.

Go deeper Why one hidden unit is not enough for XOR

A hidden unit with a monotone squash, such as ReLU, tanh or the sigmoid, outputs f(w⋅x+b)f(\mathbf{w}\cdot\mathbf{x}+b). That depends on x\mathbf{x} only through the single number s=w⋅x+bs=\mathbf{w}\cdot\mathbf{x}+b. The output then reads a f(s)+ca\,f(s)+c, which also moves in one direction as ss grows (or does not depend on ss at all). So the set where the network says “class 1” is one side of a line s=constants=\text{constant}. XOR needs more than a half-plane, so one hidden unit with a monotone squash cannot do it, and two are enough.

Training itself, finding the weights, is gradient descent with backpropagation. P4.7 gives the intuition, P4.8 works through the numbers, and P4.10 builds a full network from scratch. The code below shows it in a few lines with no explanation yet, so you can see that it is short.

Try it: the network in code

Try it: XOR by hand, the collapse, and counting parameters

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

What to expect: the hidden values are (0,0)(0,0), (1,0)(1,0), (1,0)(1,0), (2,1)(2,1) and the classes are 0,1,1,00,1,1,0. The two linear layers and the single matrix both give (5,1)(5,1), and the ReLU version gives (5,2)(5,2). The counts are 99 and 101770101770.

Now a network that learns. The next cell makes 200 made-up points on two rings (the inner ring is class 1), trains a network with one tanh hidden layer by plain gradient descent, and prints the training accuracy for different widths. The two lines marked “gradient” are backpropagation written out by hand for this one network; P4.8 explains where they come from.

Try it: train a tiny network on two rings

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

What to expect: with 1 hidden unit the accuracy is 0.7050.705, with 2 units 0.8200.820, and with 3 and 8 units 1.0001.000. These are accuracies on the training points, and the data have no separate test set, so they say how well the network fits those points, not how it would do on new ones (P3.A4). A single unit draws a straight boundary and cannot separate rings. After the swap the output changes by about 10−1610^{-16}, rounding error that is not exactly zero in floating point. Running it takes a few seconds.

Depth: three ways to see it

Intuition

A hidden layer is a bank of detectors. Each unit asks one question about the input, such as “is the sum of the two inputs above 1?”, and answers with a number. The next layer does not see the raw input any more. It sees the list of answers and combines them. If the questions are well chosen, the answers make the task easy, and a single straight line is enough. Training is the search for good questions.

Stacking is like an assembly line. The first layer finds simple patterns, and the next layer combines those into more complex ones. Where this picture breaks: nothing forces a unit to ask a question a person would recognise, so the detectors of a trained network are usually not readable one by one.

Math

For a network with LlayersL_{\text{layers}} dense layers, with h(0)=x\mathbf{h}^{(0)}=\mathbf{x}, each layer ℓ=1,…,Llayers\ell=1,\dots,L_{\text{layers}} first computes

z(ℓ)=W(ℓ)h(ℓ−1)+b(ℓ).\mathbf{z}^{(\ell)}=\mathbf{W}^{(\ell)}\mathbf{h}^{(\ell-1)}+\mathbf{b}^{(\ell)}.

Every layer before the last squashes this, and the last applies the output function:

h(ℓ)=f(z(ℓ))  for ℓ<Llayers,y^=g(z(Llayers)).\begin{aligned} \mathbf{h}^{(\ell)}&=f\big(\mathbf{z}^{(\ell)}\big)\ \text{ for }\ell<L_{\text{layers}},\\ \hat y&=g\big(\mathbf{z}^{(L_{\text{layers}})}\big). \end{aligned}

The number of parameters is the sum over layers of nℓ−1nℓ+nℓn_{\ell-1}n_\ell+n_\ell. With f(z)=zf(z)=z every layer is affine, and the composition is affine: x↦W(2)W(1)x+(W(2)b(1)+b(2))\mathbf{x}\mapsto\mathbf{W}^{(2)}\mathbf{W}^{(1)}\mathbf{x}+\big(\mathbf{W}^{(2)}\mathbf{b}^{(1)}+\mathbf{b}^{(2)}\big).

Code

The same two networks in PyTorch (P2.6, P2.7). The first is the 784-128-10 classifier, and the second is the XOR network with the weights of this lesson.

import torch
import torch.nn as nn

net = nn.Sequential(nn.Linear(784, 128), nn.ReLU(), nn.Linear(128, 10))
print(sum(p.numel() for p in net.parameters()))   # 101770

xor = nn.Sequential(nn.Linear(2, 2), nn.ReLU(), nn.Linear(2, 1))
with torch.no_grad():
    xor[0].weight.copy_(torch.tensor([[1., 1.], [1., 1.]]))
    xor[0].bias.copy_(torch.tensor([0., -1.]))
    xor[2].weight.copy_(torch.tensor([[1., -2.]]))
    xor[2].bias.zero_()
corners = torch.tensor([[0., 0.], [1., 0.], [0., 1.], [1., 1.]])
print(xor(corners).flatten())   # tensor([0., 1., 1., 0.])

On the machine used for this lesson (PyTorch 2.9) the first line prints 101770 and the second prints tensor([0., 1., 1., 0.], grad_fn=<ViewBackward0>).

Common mistakes

Quiz

Check your understanding

  1. Two dense layers with matrices W1\mathbf{W}_1 and then W2\mathbf{W}_2 have no squash between them. What single layer does the pair equal?

  2. How many parameters (weights and biases) does a network with 10 inputs, a hidden layer of 5 units and 3 outputs have?

  3. A trained 2-2-1 network is cut open, and you look at the plane of the two hidden values. What does the output unit draw there?

  4. You want a network to predict a house price in dollars directly. Which output unit fits?

  5. Why is the loss of a network with hidden layers not convex?

Exercises

  1. Feed the input (0.5,0.5)(0.5,0.5) to the XOR network of this lesson. What are the hidden values, the value zz, and the class?
    Show answerx1+x2=1x_1+x_2=1, so h1=ReLU(1)=1h_1=\mathrm{ReLU}(1)=1 and h2=ReLU(0)=0h_2=\mathrm{ReLU}(0)=0. Then z=1−0=1>0.5z=1-0=1>0.5, so the class is 1. (The network is the tent in s=x1+x2s=x_1+x_2, and s=1s=1 is its peak.)
  2. How many parameters does a 4-8-8-3 network have?
    Show answer(4⋅8+8)+(8⋅8+8)+(8⋅3+3)=40+72+27=139(4\cdot8+8)+(8\cdot8+8)+(8\cdot3+3)=40+72+27=139.
  3. Let W1=(2011)\mathbf{W}_1=\begin{pmatrix}2&0\\1&1\end{pmatrix}, W2=(1−103)\mathbf{W}_2=\begin{pmatrix}1&-1\\0&3\end{pmatrix} and x=(−1,2)\mathbf{x}=(-1,2). Compute W2(W1x)\mathbf{W}_2(\mathbf{W}_1\mathbf{x}), then W2W1\mathbf{W}_2\mathbf{W}_1 applied to x\mathbf{x}, then W2 ReLU(W1x)\mathbf{W}_2\,\mathrm{ReLU}(\mathbf{W}_1\mathbf{x}).
    Show answerW1x=(−2,1)\mathbf{W}_1\mathbf{x}=(-2,1) and W2(−2,1)=(−3,3)\mathbf{W}_2(-2,1)=(-3,3). The product is W2W1=(1−133)\mathbf{W}_2\mathbf{W}_1=\begin{pmatrix}1&-1\\3&3\end{pmatrix}, and it gives (−3,3)(-3,3) again. With ReLU, ReLU(−2,1)=(0,1)\mathrm{ReLU}(-2,1)=(0,1) and W2(0,1)=(−1,3)\mathbf{W}_2(0,1)=(-1,3), which is different, so the squash changed the function.
  4. At most how many regions can a hidden layer of 4 ReLU units cut the input plane into?
    Show answerAt most 1+4+(42)=1+4+6=111+4+\binom42=1+4+6=11, when the four lines are in general position. If some are parallel, there are fewer.
  5. Explain in two sentences why a network with a single hidden unit (a monotone squash) and one output unit cannot solve XOR.
    Show answerThe hidden unit depends on the input only through one number s=w⋅x+bs=\mathbf{w}\cdot\mathbf{x}+b, and the output is a monotone function of ss, so the “class 1” region is one side of a line s=constants=\text{constant}, a half-plane. XOR needs the two opposite corners of class 1 separated from the two corners of class 0, which no half-plane does.

Key takeaways

  • A hidden layer is a layer of neurons whose outputs feed another layer. One neuron draws one straight line; a neuron that reads the outputs of other neurons can combine several lines.
  • A layer computes an affine map and then a squash on each entry: h=f(W1x+b1)\mathbf{h}=f(\mathbf{W}_1\mathbf{x}+\mathbf{b}_1). The output is y^=g(W2h+b2)\hat y=g(\mathbf{W}_2\mathbf{h}+b_2). The whole network is the first layer followed by the second.
  • A 2-2-1 network with ReLU units solves XOR: the hidden layer folds the plane so that the two class-1 points land on one spot, and one straight line in the hidden space separates the classes.
  • Layers without a squash multiply into one matrix: W2W1\mathbf{W}_2\mathbf{W}_1. Ten of them are still one linear layer. The squash is what makes depth useful.
  • Each hidden layer bends the space and the output unit draws one straight line in the last hidden space. In the input plane that line becomes a curve (tanh) or a bent line made of straight pieces (ReLU).
  • A layer with ninn_{\text{in}} inputs and noutn_{\text{out}} units has ninnout+noutn_{\text{in}}n_{\text{out}}+n_{\text{out}} parameters. A 784-128-10 network has 101,770.
  • The output head decides what the network predicts: one sigmoid unit for two classes, softmax for several, one linear unit for a number.
  • With hidden layers the loss is not convex: swapping two hidden units gives the same function, so different starts can end in different places.
Found a mistake? Tell us