Neural-net foundations2 / 15

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 WW, and their biases into a vector b\mathbf{b}. Then the whole layer is one matrix multiplication, plus the bias, then the activation ϕ\phi applied to every entry:

h=ϕ(Wx+b).\mathbf{h} = \phi(W \mathbf{x} + \mathbf{b}).

Row jj of WW times x\mathbf{x}, plus bjb_j, is neuron jj's weighted sum. So a layer of 16 neurons reading 2 inputs has a 16×216 \times 2 weight matrix and 16 biases.

Worked example

A layer of two tanh neurons, on the point (0, 2)

  1. The weights are W=(10.251−0.25)W = \begin{pmatrix} 1 & 0.25 \\ 1 & -0.25 \end{pmatrix} and the biases are b=(1,−1)\mathbf{b} = (1, -1). 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 ℓ=1,2,…,L\ell = 1, 2, \dots, L, and call the input h(0)=x\mathbf{h}^{(0)} = \mathbf{x}. Each hidden layer computes

h(ℓ)=ϕ(W(ℓ)h(ℓ−1)+b(ℓ)),\mathbf{h}^{(\ell)} = \phi\big(W^{(\ell)} \mathbf{h}^{(\ell - 1)} + \mathbf{b}^{(\ell)}\big),

and the last layer stops before the bend:

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

In words: each layer takes the previous layer's output, multiplies by its weights, adds its bias and bends the result. The superscript (ℓ)(\ell) 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 z\mathbf{z} 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 z2−z1z_2 - z_1. 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.

−3−2−10123−3−2−10123x₁x₂
class 0 class 1grey lines: the input grid, carried along

The input

Two classes that no straight line can split: × sits in a wedge with ○ on both sides.

Step 0 of 4
A 2-2-2 tanh network moving the plane. Step through: the first layer tilts and stretches, tanh bends, and then one straight line splits the classes. The last step pulls that line back to the input, where it's a curve.

Things to notice:

  • After W(1)x+b(1)W^{(1)}\mathbf{x} + \mathbf{b}^{(1)}, 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 (−1,1)(-1, 1), 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

  1. The hidden layer gives h=(0.905,−0.905)\mathbf{h} = (0.905, -0.905), 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.

kmhourinputhidden (ReLU)output
+ weight− weightthicker = bigger

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.

on time late P = 0.5

The whole network on the 200 validation deliveries: 94.5% correct.

The trained 2-16-2 network. Tap a unit to see its own map. Below: the whole network's decision map on the validation deliveries.

Things to notice:

  • Every hidden unit's map is split by one straight line. A ReLU unit is on exactly where w⋅x+b>0\mathbf{w} \cdot \mathbf{x} + b > 0. 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.

on time late P = 0.5

Step 0 · training accuracy 21.0%

network 2-1-2 · 7 parameters
024681000.20.40.60.81steploss02468100%50%100%stepaccuracy
train 0.935 (21%)
Choose the number of hidden units and layers, then train. Top: the decision map. Bottom: loss and accuracy over training (for rush hour, solid is training and dashed is validation).

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 ReLU(x−1)−ReLU(x−2)\text{ReLU}(x - 1) - \text{ReLU}(x - 2):

  • For x<1x < 1, 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 x>2x > 2, 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 xx, each with its own weight and bias, is exactly a network with one hidden layer of ReLUs. So nn pieces need 2n2n hidden units. Try it:

0123456−101input xoutput

3 pieces = 6 ReLU units · largest gap 0.72

Dashed: the target. Solid: the network. Each piece is one ramp built from two ReLUs.

A wiggly curve (dashed) and a one-hidden-layer ReLU network built from ramps (solid). Each extra piece costs two hidden units and shrinks the largest gap.

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. Call super().__init__() first. Then assign each layer to self. Assigning it is what registers the layer's weights with the model.
  • forward runs the forward pass: it takes a batch of inputs and returns the logits.
The 2-16-2 network as an nn.Module
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:

The same network, with nn.Sequential
same_net = nn.Sequential(nn.Linear(2, 16), nn.ReLU(), nn.Linear(16, 2))  # the same network

Which is clearer?

  • nn.Sequential suits 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:

Every parameter, with its shape
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 + 2

The count by hand: the hidden layer has 2×16=322 \times 16 = 32 weights and 16 biases. The output layer has 16×2=3216 \times 2 = 32 weights and 2 biases. That's 32+16+32+2=8232 + 16 + 32 + 2 = 82. 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:

Cross-entropy wants logits
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.181

On the rush-hour data, the same 2-16-2 network trained both ways for 200 epochs gives:

VersionFinal training lossFinal validation accuracy
logits into F.cross_entropy0.31693.5%
softmax, then F.cross_entropy0.40591.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 P(late)=σ(z2−z1)P(\text{late}) = \sigma(z_2 - z_1), then z2−z1=log⁡(P(late)/P(on time))z_2 - z_1 = \log\big(P(\text{late}) / P(\text{on time})\big). A difference of 0 means even odds, and each extra 1 multiplies the odds by e≈2.7e \approx 2.7. In the worked example above, the difference 2.62 means odds of about e2.62≈14e^{2.62} \approx 14 to 1.

The cross-entropy loss needs log⁡\log 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 log⁡0\log 0 is −∞-\infty. 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

  1. Standardise with the training set's mean and standard deviation: (2−3.86)/2.25=−0.83(2 - 3.86) / 2.25 = -0.83 and (19−19.83)/1.60=−0.52(19 - 19.83) / 1.60 = -0.52. So x=(−0.83,−0.52)\mathbf{x} = (-0.83, -0.52).

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: h=ϕ(Wx+b)\mathbf{h} = \phi(W\mathbf{x} + \mathbf{b}), with one row of WW 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() and named_parameters(), nn.Tanh, and F.cross_entropy, which takes logits.