Skip to content
AriadneTechnology

The Middle Ring · Chamber 5 of 8

Training Your First Network

Stack neurons into layers, conquer XOR and learn why doing well on training data is not the goal.

30 min 60 XP + 5 questions + 2 challengesMathLabCode

In this chamber you will

  • Explain how hidden layers create new features
  • Write the training loop from memory
  • Use cross-entropy for classification
  • Diagnose overfitting with train, validation and test splits

From one neuron to a network

A layer is a group of neurons that all read the same inputs. Feed one layer's outputs into the next and you have a multilayer perceptron (MLP). The layers in the middle are called hidden because we never see their outputs directly.

For binary classification with one hidden layer:

h=ϕ(W1x+b1),p^=σ(w2⊤h+b2)\mathbf{h} = \phi(W_1\mathbf{x} + \mathbf{b}_1), \qquad \hat{p} = \sigma\big(\mathbf{w}_2^\top\mathbf{h} + b_2\big)

Each hidden unit learns a feature, a new way of looking at the input. The output neuron then draws its straight line in feature space instead of input space. That's the whole trick: the hidden layer transforms the problem until it becomes linearly separable.

Solving XOR by hand

Here is a classic construction (it appears in Goodfellow, Bengio and Courville's Deep Learning, §6.1) that solves XOR with two ReLU hidden units:

h1=ReLU(x1+x2),h2=ReLU(x1+x2−1),y^=h1−2h2h_1 = \mathrm{ReLU}(x_1 + x_2), \qquad h_2 = \mathrm{ReLU}(x_1 + x_2 - 1), \qquad \hat{y} = h_1 - 2h_2
x1x_1x2x_2h1h_1h2h_2y^\hat{y}
00000
01101
10101
11210

Look at what the hidden layer did. It mapped (0,1)(0,1) and (1,0)(1,0) to the same hidden point, (h1,h2)=(1,0)(h_1, h_2) = (1, 0). In hidden space the problem is no longer XOR at all: a straight line finishes the job.

Quick check +20 XP

Why can a network with one hidden layer solve XOR when a single neuron cannot?

The training loop

Every neural network you'll ever train, from this toy to a large language model, runs the same four-beat loop:

1. Forward passpredict ŷ = f(x)2. Lossscore ℒ(ŷ, y)3. Backward passcompute ∇ℒ4. Updateθ ← θ − η∇ℒrepeat for many epochs(one epoch = one pass over the data)

In PyTorch it reads almost exactly like the diagram:

Python
import torch
from torch import nn

# X: float tensor of shape (n, 2); y: float tensor of shape (n, 1) with 0/1 labels
model = nn.Sequential(nn.Linear(2, 4), nn.Tanh(), nn.Linear(4, 1))
loss_fn = nn.BCEWithLogitsLoss()     # sigmoid + cross-entropy, numerically stable
opt = torch.optim.SGD(model.parameters(), lr=0.3)

for epoch in range(1000):
    logits = model(X)                # 1. forward pass
    loss = loss_fn(logits, y)        # 2. loss
    opt.zero_grad()
    loss.backward()                  # 3. backward pass (Chamber 4)
    opt.step()                       # 4. update (Chamber 2)

Cross-entropy: the classification loss

Squared error works for regression, but for probabilities there's a better choice. If the network predicts p^i\hat{p}_i for the probability that example ii has label yi=1y_i = 1, the binary cross-entropy is

L=−1n∑i=1n[yilog⁡p^i+(1−yi)log⁡(1−p^i)]\mathcal{L} = -\frac{1}{n}\sum_{i=1}^{n}\Big[y_i \log \hat{p}_i + (1 - y_i)\log\big(1 - \hat{p}_i\big)\Big]
  • Confident and right costs almost nothing: −log⁡(0.99)≈0.01-\log(0.99) \approx 0.01.
  • Confident and wrong is brutal: −log⁡(0.01)≈4.6-\log(0.01) \approx 4.6.
  • It's the negative log-likelihood of the data under the model, the same "loss as likelihood" idea from Chamber 1's research lens.

And it pairs beautifully with a sigmoid output. The gradient with respect to the output neuron's pre-activation zz is simply p^−y\hat{p} - y: prediction minus truth.

Why is the gradient just p̂ − y?

With p^=σ(z)\hat{p} = \sigma(z) and ℓ=−[ylog⁡p^+(1−y)log⁡(1−p^)]\ell = -\big[y\log\hat{p} + (1-y)\log(1-\hat{p})\big], apply the chain rule:

∂ℓ∂z=(−yp^+1−y1−p^)⏟∂ℓ/∂p^⋅p^(1−p^)⏟∂p^/∂z=−y(1−p^)+(1−y)p^=p^−y\frac{\partial \ell}{\partial z} = \underbrace{\left(-\frac{y}{\hat{p}} + \frac{1-y}{1-\hat{p}}\right)}_{\partial \ell / \partial \hat{p}} \cdot \underbrace{\hat{p}(1-\hat{p})}_{\partial \hat{p} / \partial z} = -y(1-\hat{p}) + (1-y)\hat{p} = \hat{p} - y

The sigmoid's slope cancels exactly, so saturated sigmoids don't kill the gradient at the output. That's a big part of why this pairing is standard.

Train it yourself

This is a real neural network, trained live in your browser with the backprop you derived in the last chamber. Colour shows the network's confidence. Watch the boundary bend.

Interactive lab

Neural network trainer

Pick a dataset and an architecture, press play and watch gradient descent bend the decision boundary. Colour shows the network's confidence. Circled points are currently misclassified. Every Reset draws a new random seed.
Hidden layers
Units per layer4
Activation

epoch

0

loss

NaN

accuracy

0%

Architecture 2 → 4 → 1 · seed 1 · 0 parameters

Training loss (log scale)

10.10.010.001
Challenge: Conquer XORTrain a network to 100% accuracy on XOR.+50 XP
Challenge: Tame the spiralTrain a network to at least 95% accuracy on the spiral.+60 XP

Things to try:

  1. XOR with 1 hidden unit. However long you train, it stays stuck: one hidden unit can only draw one line.
  2. XOR with 2 hidden units. Surprise: on this data it almost always fails. The hand-built solution above handles four corner points, but here the points fill whole quadrants, and two units struggle to wall off two opposite quadrants. Try 3 and 4 units, with several seeds each.
  3. Circle. Watch the boundary curl into a loop.
  4. Spiral. The legendary challenge. Two hidden layers, 8 units, tanh, learning rate 0.3, and some patience.
  5. Break it. Push the learning rate to 3 with ReLU and watch training fall apart.

Generalisation: the real exam

A network with enough units can drive its training loss towards zero, even on random labels. So a low training loss proves little. What matters is performance on data the model has never seen, and measuring that honestly requires discipline:

  • Training set: used to fit the weights.
  • Validation set: used to make decisions such as learning rate, architecture and when to stop.
  • Test set: touched once, at the very end, to estimate performance on truly unseen data.

Overfitting shows up as a widening gap: training loss keeps falling while validation loss turns upwards. The model is memorising noise. Underfitting is the opposite: both losses stay high because the model is too simple or undertrained.

Standard remedies for overfitting:

  • More data: often the most reliable fix.
  • Early stopping: keep the checkpoint with the best validation loss.
  • Weight decay (L2 regularisation), which penalises large weights: Ltotal=L+λ∥θ∥22\mathcal{L}_{\text{total}} = \mathcal{L} + \lambda \lVert\theta\rVert_2^2.
  • Dropout, which randomly silences units during training so no single unit can be relied on too much.

Key takeaways

  • Hidden layers learn features that make hard problems linearly separable. That's how networks beat XOR.
  • Training is a loop: forward → loss → backward → update, repeated over many epochs.
  • Cross-entropy is the standard classification loss. With a sigmoid output its gradient is simply p^−y\hat{p} - y.
  • The goal is generalisation. Use train, validation and test splits properly, and watch for overfitting.

Checkpoint

Prove it to the labyrinth

Answer every question to clear this chamber. First-try answers earn the most XP.

0/4
Question 1 of 4 +20 XP

Training loss keeps dropping, but validation loss started rising 20 epochs ago. What is most likely happening?

Question 2 of 4 +20 XP

What is the validation set for?

Question 3 of 4 +20 XP

A classifier outputs p^=0.9\hat{p} = 0.9 for an example labelled y=1y = 1. Using natural logs, what is the cross-entropy loss −log⁡p^-\log \hat{p}? (two decimal places are fine)

Question 4 of 4 +20 XP

What goes wrong if you initialise every weight of a hidden layer to exactly zero?

End of the chamber

Clear this chamber

  • Questions in this chamber (0/5 solved)Next unsolved
  • Bonus: Conquer XOR (+50 XP)
  • Bonus: Tame the spiral (+60 XP)
+60 XPMultilayer PerceptronCross-EntropyOverfittingTrain / Val / Test