A single neuron draws one straight line (P4.1). That is why it fails on XOR (P4.2): no line puts the corners and on one side and and 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 . 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 .
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 from P1.A1 as the squash of the hidden units. The two hidden units are
The first unit tells how many inputs are on. The second is positive only when both are on. The output unit computes , and the prediction is class 1 when .
| input | hidden | class | |
|---|---|---|---|
| 0 | |||
| 1 | |||
| 1 | |||
| 0 |
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 by hand, is what a learned hidden layer does for itself. In weight-matrix form, and for the hidden layer, and and for the output.
Now look at the hidden plane, with across and up. The four points land at , , and . 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: has on one side and and 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, and , with class 1 in the strip between them. The network is really a function of one number, . It gives for , then for , then for : a tent with its peak at . 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 (this is OR: on when at least one input is on) and (this is AND: on only when both are on). The hidden values are , , and . The output is , , and , 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 inputs and hidden units in two lines:
Here has entries, has rows and columns, and and have entries. The row of holds the weights of hidden unit . The function is the hidden squash, applied to each entry on its own. The second line is the output layer: has one row and columns, and is the output function. For XOR, .
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”:
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 , and , with the sigmoid from P1.A5 as the hidden squash. Then and . Give the output unit and , and let . Then and . 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 inputs and units has weights and biases:
The 2-2-1 network has parameters. Now a network of realistic size: a picture of a handwritten digit with pixels, a hidden layer of 128 units and 10 outputs, one per digit (a 784-128-10 network):
- layer 1:
- layer 2:
- total:
For comparison, softmax regression on the same pixels (P3.A8) has 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 is the same for every hidden unit in a layer. The output function 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: (), () and . Applying the layers one after the other gives and then . The single matrix
applied to also gives . The two layers are one layer. With biases the same holds: , 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: , and , which is not . 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:
- A linear map : stretch, turn, shear (P1.B5). Straight lines stay straight, and the origin stays where it is.
- A shift : slide the whole plane.
- A squash on each entry: tanh squeezes every coordinate into , so far-away points are pulled into a box. ReLU sets negative coordinates to , 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 , and then split the lifted data with a flat plane. A hidden layer is also a lift, , 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.
Things to try, in order:
- 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.
- 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.
- 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.
- 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.
- 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 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 , where and are the two weighted sums. Write and . The expression is linear in , and the pair always lies strictly inside the square . 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 and can both take any values) far points exist whose 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 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 is zero. On one side the unit is on and passes its sum through; on the other it outputs . The lines cut the plane into regions, and inside each region every unit is either on or off, so the value 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 regions for lines. That is at most for units, for and for . The XOR network has only , because its two lines are parallel (both are a constant): the regions are , and , 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 between and . The tent function uses two hidden units. It rises from at to at , then falls back to at . 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: ReLU units on a line give at most 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 instead of the raw inputs.
- classes: output units followed by a softmax, like softmax regression (P3.A8), again applied to .
- 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 , both and fit a target of perfectly, but their midpoint gives loss at . 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 with . At , and it predicts , and . The swapped setting gives exactly the same predictions, so both have the same loss. Their midpoint predicts , and , a worse fit, with a mean squared error of 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 units can be reordered in ways, and each ordering is the same function. For that is settings, and for it is . For tanh there is a second symmetry: , 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 . That depends on only through the single number . The output then reads , which also moves in one direction as grows (or does not depend on at all). So the set where the network says “class 1” is one side of a line . 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
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
What to expect: the hidden values are , , , and the classes are . The two linear layers and the single matrix both give , and the ReLU version gives . The counts are and .
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.
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 , with 2 units , and with 3 and 8 units . 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 , 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 dense layers, with , each layer first computes
Every layer before the last squashes this, and the last applies the output function:
The number of parameters is the sum over layers of . With every layer is affine, and the composition is affine: .
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
Two dense layers with matrices and then have no squash between them. What single layer does the pair equal?
The first layer acts first, so the product is , and the biases combine into . The product in the other order is a different matrix, and usually does not even have matching shapes. Curved boundaries need a squash between the layers. Doubling the units does not describe a product of two matrices.
How many parameters (weights and biases) does a network with 10 inputs, a hidden layer of 5 units and 3 outputs have?
The hidden layer has parameters and the output layer has , which makes . The value 65 counts weights only and forgets the 8 biases. The value 58 forgets the weights of the output layer. The value 150 multiplies the three sizes together, which is not how layers count.
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?
The output unit is a neuron, so on the hidden values it computes a weighted sum and a threshold, which is one straight line. The curved boundary appears only when that line is carried back to the input plane through the bending layers, so the two pictures differ. The hidden units are the axes of the plane, not extra lines in it.
You want a network to predict a house price in dollars directly. Which output unit fits?
A price is a number on a wide scale, so the output must be able to take any value, and a plain linear unit does that. The sigmoid output cannot leave the interval from 0 to 1, so it cannot produce a price in dollars. A softmax gives class probabilities, which would turn the task into classification. A step unit outputs only two values.
Why is the loss of a network with hidden layers not convex?
Two settings with the same loss whose midpoint has a higher loss break the chord rule for convex functions, and swapped hidden units supply exactly such a pair. Logistic regression has a convex loss even when the data cannot be separated, so separability is not the cause. A random start is a property of the method, not of the loss. The number of parameters compared with the number of points does not decide convexity.
Exercises
- Feed the input to the XOR network of this lesson. What are the hidden values, the value , and the class?
Show answer
, so and . Then , so the class is 1. (The network is the tent in , and is its peak.) - How many parameters does a 4-8-8-3 network have?
Show answer
. - Let , and . Compute , then applied to , then .
Show answer
and . The product is , and it gives again. With ReLU, and , which is different, so the squash changed the function. - At most how many regions can a hidden layer of 4 ReLU units cut the input plane into?
Show answer
At most , when the four lines are in general position. If some are parallel, there are fewer. - Explain in two sentences why a network with a single hidden unit (a monotone squash) and one output unit cannot solve XOR.
Show answer
The hidden unit depends on the input only through one number , and the output is a monotone function of , so the “class 1” region is one side of a line , 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.