Lesson 2 · Building networks
Feedforward networks
The problem
In the last lesson, one neuron drew one straight line through the rush-hour deliveries and got 76% right. The late trips around 19:00 form a dip that no straight line can follow.
The lesson ended with a network of 16 neurons and a ReLU after each. Trained on the same data, a network like that gets about 94% right. This lesson shows how. You'll see what layers of neurons do to the data and how to read a trained network. Then you'll find out how big a network needs to be, and how to build one in PyTorch.
Layers
A layer is many neurons side by side, all reading the same inputs. Each neuron has its own weights and bias. Stack their weights as the rows of a matrix , and their biases into a vector . Then the whole layer is one matrix multiplication, plus the bias, then the activation applied to every entry:
Row of times , plus , is neuron 's weighted sum. So a layer of 16 neurons reading 2 inputs has a weight matrix and 16 biases.
Worked example
A layer of two tanh neurons, on the point (0, 2)
The weights are and the biases are . Each row is one neuron.
Now feed one layer's output into the next. A network of layers stacked like this is a multilayer perceptron (MLP), also called a feedforward network. Information only flows forward, from the inputs to the output. Every layer except the last is a hidden layer. Its outputs are used inside the network but never shown as the answer.
We name networks by their layer sizes. A 2-16-2 network has 2 inputs, one hidden layer of 16 neurons and 2 outputs. The course's default network, 2-16-16-2, has two hidden layers of 16.
The maths
Number the layers , and call the input . Each hidden layer computes
and the last layer stops before the bend:
In words: each layer takes the previous layer's output, multiplies by its weights, adds its bias and bends the result. The superscript only says which layer a symbol belongs to; it isn't a power. Computing all of this, layer by layer from the input to the output, is the forward pass.
The last layer has no activation. Its outputs are the logits: one raw score per class, any real number. Softmax turns them into probabilities. For two classes, the probability of class 2 is the sigmoid of . So the last layer is softmax regression, run on the hidden layer's outputs instead of on the raw inputs.
How layers bend space
Why does this help? Watch a tiny network, 2-2-2 with tanh, on a made-up set of points that no straight line can split. Its weights were picked by hand so that each step is easy to see; training finds weights that do the same kind of thing. Each step moves every point, and the grey grid lines move with them. It's the grid picture from linear transformations, with a bend added.
The input
Two classes that no straight line can split: × sits in a wedge with ○ on both sides.
Things to notice:
- After , grid lines are still straight and evenly spaced. A linear step can only tilt, stretch and slide the plane, so the ○ groups are still on both sides of the ×s.
- After tanh, every coordinate is squashed into , and the grid lines bend. Points far to the left are pushed into one corner, and points far to the right into the opposite corner. The ×s end up in a third corner.
- One straight cut now separates the classes. The output layer draws it.
- Back in the input plane, that straight cut is a curve wrapped around the ×s.
This is the main idea of the lesson. The hidden layers move the points until a straight cut works. Then the last layer makes that cut.
Worked example
The point (0, 2), all the way through
The hidden layer gives , as worked out above. That's near the bottom-right corner, where the ×s gather.
Reading a trained network
Back to the deliveries. Here is a 2-16-2 ReLU network, trained on the rush-hour data. It used the course's defaults: AdamW, learning rate 0.01, batches of 32, 200 epochs and seed 0. Line thickness is the size of each weight, and the line style is its sign. Tap or hover a hidden unit to see where it's on, meaning its weighted sum is above 0, so ReLU passes it through.
Tap or hover a unit. A hidden unit's map shows where it is on (shaded ×) and off (shaded ○); its edge is always a straight line.
The whole network on the 200 validation deliveries: 94.5% correct.
Things to notice:
- Every hidden unit's map is split by one straight line. A ReLU unit is on exactly where . That's a half-plane, the same straight cut a single neuron makes.
- The output combines the pieces. It adds up the 16 bent pieces with its own weights. A sum of hinges along 16 different lines can bend wherever it needs to, so the boundary follows the 19:00 dip.
- A couple of units do almost nothing. They are off for every training delivery, so they never pass anything on. Lesson 6 explains how units end up like this.
With the weights from its best epoch, the network gets 94.5% of the validation deliveries right, against 76% for one neuron.
Width and depth
How many units does a network need? It depends on the shape you need to draw. The zone data makes this sharp. Road works block a round zone near the shop, and every delivery into it is late.
Predict first
A 2-1-2 network: one hidden ReLU unit. Can it learn the zone's round boundary?
The playground below starts on the zone data with 1 hidden unit. Press train. Then try 2, 3 and 16 units. Switch to the rush-hour data and try more layers.
Step 0 · training accuracy 21.0%
Things to notice:
- 1 unit draws one straight line, and here it ends up saying "on time" everywhere: 79%.
- 2 units make a bent line with two straight parts, which can cut off only part of the zone: about 84%.
- 3 units can fence in the zone as a rough triangle: about 93%. Some starting weights get stuck with a unit that never switches on. Press "New starting weights" to see it happen.
- 16 units give a smooth, round boundary: about 96%.
- On the rush-hour data, a second or third layer bends the boundary with fewer units per layer. Each layer combines the previous layer's pieces into more complex pieces.
More units and more layers give the network more capacity: it can draw more shapes. That cuts both ways. A flexible network can also follow the noise in its training data, which is overfitting. Lesson 7 deals with that.
How far does width go? Take any continuous function on a bounded range of inputs. A network with a single hidden layer, if it's wide enough, can get as close to it as you like.
This is called universal approximation. It says such a network exists. It doesn't say how many units you need, or whether training will find the right weights.
DeeperWhy a wide enough network can fit anythingTwo ReLUs make a ramp. Enough ramps join the dots of any curve. · 4 min
Take a curve of one input, and pick some points along it. Join the dots with straight pieces. With enough pieces, the copy is as close to the curve as you like.
Every straight piece can be built from two ReLUs. Take :
- For , both are 0, so the result is 0.
- Between 1 and 2, only the first is on, so the result rises from 0 to 1.
- For , both are on, and the result stays at 1.
That's a ramp: flat, then rising, then flat. Multiply it by a slope to make it rise by any amount. Add one ramp per piece, and the sum climbs and falls in step with the curve.
A sum of ReLUs of , each with its own weight and bias, is exactly a network with one hidden layer of ReLUs. So pieces need hidden units. Try it:
3 pieces = 6 ReLU units · largest gap 0.72
Dashed: the target. Solid: the network. Each piece is one ramp built from two ReLUs.
The same idea works with more inputs, using bumps in place of ramps, but it needs far more units. That's one reason depth helps in practice: deep networks can build complex shapes from fewer units, by reusing pieces made in earlier layers.
Building networks in PyTorch
nn.Module is the base class for every PyTorch model. You subclass it and write two methods:
__init__creates the layers. Callsuper().__init__()first. Then assign each layer toself. Assigning it is what registers the layer's weights with the model.forwardruns the forward pass: it takes a batch of inputs and returns the logits.
class LateNet(nn.Module):
"""A 2-16-2 network: two inputs (km, hour), 16 hidden ReLU units, two logits (on time, late)."""
def __init__(self, hidden: int = 16) -> None:
super().__init__() # always first: sets up the parameter bookkeeping
self.hidden = nn.Linear(2, hidden) # assigning a layer registers its weights
self.out = nn.Linear(hidden, 2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
h = F.relu(self.hidden(x)) # (batch, 2) → (batch, 16)
return self.out(h) # (batch, 16) → (batch, 2): logits, no softmax
torch.manual_seed(0)
net = LateNet()
x = torch.tensor([[0.5, -0.3]]) # one delivery, already standardised shape (1, 2)
print(net(x)) # two logits; call the model, not net.forward(x)Call the model like a function, net(x). Don't call net.forward(x) directly: calling the model runs forward plus some PyTorch bookkeeping, such as hooks, that a direct call skips. The input is a batch, one delivery per row, so x has shape (batch, 2) even for one delivery.
The same network fits on one line with nn.Sequential:
same_net = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 2)) # the same networkWhich is clearer?
nn.Sequentialsuits a plain chain of layers, where each output goes straight into the next.- A subclass suits anything else: skipping a layer, using an input twice, returning more than one thing, or printing a value while you debug. Later lessons need these.
Counting parameters
model.parameters() finds every learnable tensor inside a model, no matter how deeply its layers are nested. Optimisers use it to know what to update. named_parameters() gives each one's name too:
for name, p in net.named_parameters():
print(f"{name:14} {tuple(p.shape)}")
# hidden.weight (16, 2)
# hidden.bias (16,)
# out.weight (2, 16)
# out.bias (2,)
print(sum(p.numel() for p in net.parameters())) # 82 = 2·16 + 16 + 16·2 + 2The count by hand: the hidden layer has weights and 16 biases. The output layer has weights and 2 biases. That's . The shapes follow nn.Linear's rule: the weight is (out, in), one row per neuron.
Logits and the loss
Networks output logits, not probabilities, and PyTorch's loss expects exactly that. F.cross_entropy applies the softmax itself, then the cross-entropy loss. Adding your own softmax at the end of the network is a classic bug: the code runs, nothing warns you, and training gets worse.
Predict first
You end your network with a softmax, and still train it with F.cross_entropy. What happens?
Here is the bug on two deliveries, side by side:
logits = torch.tensor([[2.0, -1.0], [0.5, 1.5]]) # two deliveries' scores shape (2, 2)
target = torch.tensor([0, 1]) # on time, late
right = F.cross_entropy(logits, target) # cross_entropy does the softmax itself
wrong = F.cross_entropy(logits.softmax(dim=1), target) # softmax twice: a silent bug
print(f"{right.item():.3f} {wrong.item():.3f}") # 0.181 0.414 logits = model(x)
- loss = F.cross_entropy(logits.softmax(dim=1), y) # softmax twice: loss 0.414
+ loss = F.cross_entropy(logits, y) # softmax once, inside: 0.181On the rush-hour data, the same 2-16-2 network trained both ways for 200 epochs gives:
| Version | Final training loss | Final validation accuracy |
|---|---|---|
logits into F.cross_entropy | 0.316 | 93.5% |
softmax, then F.cross_entropy | 0.405 | 91.5% |
The buggy version still learns, which makes the bug easy to miss. Apply softmax only when you need probabilities to read or report, outside the loss.
DigressionLogits, probabilities and why the loss wants logitsLogits are log-odds, and the loss computes the log of a softmax in one safe step. · 2 min
For two classes, the difference of the logits is the log of the odds. If , then . A difference of 0 means even odds, and each extra 1 multiplies the odds by . In the worked example above, the difference 2.62 means odds of about to 1.
The cross-entropy loss needs of the softmax. Computing the softmax first and then its log can fail in float32. A confident wrong answer gives a probability that rounds to 0, and is . F.cross_entropy computes the log-softmax in one step, with the logsumexp trick, so it never takes the log of a rounded 0. The primer's numbers and stability lesson shows this in detail.
Putting it together
Follow one delivery through the trained 2-16-2 network: 2 km, sent at 19:00. The single neuron from Lesson 1 calls it on time. But it's in the dip, where the rule says it will be late.
Worked example
A 2 km delivery at 19:00, through the trained network
Standardise with the training set's mean and standard deviation: and . So .
Every part of the lesson is in those steps. Each layer is a matrix multiply, a bias and a bend. The hidden units each cut the plane once, and which ones are on depends on where the delivery is. The output layer is a straight cut in the hidden layer's coordinates, and its logits go into softmax only when you want a probability. How the network found these weights is backpropagation, the next lesson.
Common misconceptions
"Each hidden unit learns a meaningful feature, like 'rush hour'." Sometimes a unit matches an idea you can name. Nothing makes it do so. Here, each unit is one straight cut, and the meaning is in how the output combines them.
"End the network with a softmax before the loss." F.cross_entropy applies its own softmax. Give it logits.
"Wider is always better." More units give more capacity. They also cost more to train and can overfit the training data. Training can also leave some units unused.
"Universal approximation means training will find a good network." It only says a good network exists, possibly an enormous one. Whether training finds it is a separate question.
Recap
- A layer is many neurons reading the same inputs: , with one row of per neuron.
- An MLP stacks layers. The forward pass runs them in order, and the last layer outputs logits, with no activation.
- Hidden layers move and bend the data until one straight cut separates the classes. Back in the input space, that cut is a curve.
- Each ReLU unit cuts the plane with one straight line. More units and layers give more pieces, so more flexible boundaries: 1 unit can't fence in a zone, 3 can.
- PyTorch names in this lesson:
nn.Module(__init__,forward),nn.Sequential,model.parameters()andnamed_parameters(),nn.Tanh, andF.cross_entropy, which takes logits.