← All notes
Course chapters
On this page

Lesson 09 · Neural networks

Neural networks and training

Connect neurons into a network, count its parameters, and understand the loop that turns labelled examples into learned weights.

1. One neuron is not enough: connect a network

In the previous two lessons we built our fruit-guessing machine from its parts. Lesson 7 introduced the neuron: weighted sum, bias and activation. Lesson 8 showed why nonlinear activations let multiple layers represent more than one affine transformation.

Now put the parts together into a neural network, then ask how it learns.

Recall the arrangement from the end of Lesson 7. Give each fruit class a scoring neuron, put the neurons side by side, and use Softmax to convert their scores into a probability distribution. That row of scoring units is a layer. Revisit it below.

SmallLarge
Less redMore red
SourSweet
DryJuicy
z=Wx+b,p=softmax⁡(z)\mathbf{z}=W\mathbf{x}+\mathbf{b},\quad\mathbf{p}=\operatorname{softmax}(\mathbf{z})

Most likely fruit: Apple

AppleScore: 2.44 · 35.8%
BananaScore: 2.18 · 27.4%
WatermelonScore: 1.39 · 12.5%
LemonScore: 2.05 · 24.3%

Unrounded probabilities sum to one; displayed percentages may differ slightly due to rounding.

Experiment 9-A. Revisit one scoring layer: four fruit scores become a probability distribution through Softmax. Increase size and water content to favour watermelon. These illustrative parameters are fixed by hand; moving the inputs is inference, not training.

The important next step is to use one layer's output as the next layer's input. Connect several layers, with nonlinear activations between hidden layers, and we obtain a multilayer neural network.

  • The input layer receives the original features. Here it simply represents four input values, rather than four learnable transformations.
  • Hidden layers produce intermediate representations between the input and final prediction. “Hidden” means they are internal to the model, not that their values are impossible to inspect.
  • The output layer produces the scores or answers needed for the task. In this classifier, Softmax turns the final scores into probabilities over four mutually exclusive fruit classes.
Input features4 units
x1x_1
x2x_2
x3x_3
x4x_4
Hidden layer5 units
ff
ff
ff
ff
ff
Hidden layer5 units
ff
ff
ff
ff
ff
Class scores4 units
z1z_1
z2z_2
z3z_3
z4z_4
Hidden layers: h(l)=fl(Wlh(l−1)+bl)\text{Hidden layers: }\mathbf{h}^{(l)}=f_l(W_l\mathbf{h}^{(l-1)}+\mathbf{b}_l)
Output: p=softmax⁡(z)\text{Output: }\mathbf{p}=\operatorname{softmax}(\mathbf{z})
Figure 9-1. A fully connected classifier: four inputs, two hidden layers of five neurons each, and four class scores followed by Softmax. Connections represent weights; each non-input neuron also has a bias, omitted from the wiring for clarity.

The diagram is fully connected: every unit in a layer receives input from every unit in the preceding layer. Other neural architectures use different connectivity; this is our starting example, not a rule for every network.

The number of successive learnable layers describes the network's depth; the number of units in a layer describes its width. Counting conventions vary, so be explicit: this diagram has four feature columns and three learnable affine layers, two of which are hidden. The widths are:

4⟶5⟶5⟶4.4\longrightarrow5\longrightarrow5\longrightarrow4.

As Lesson 8 established, nonlinear hidden activations matter. If all those layers are affine with no intervening nonlinearity, the whole stack is still one effective affine transformation.

2. The whole network is one function with parameters

Do not let the wiring diagram make the network seem mysterious. Input features enter, each hidden layer applies an affine transformation and activation, and the result passes onwards.

For layer ll, write:

h(l)=fl(Wlh(l−1)+bl),h(0)=x.\mathbf{h}^{(l)}=f_l\left(W_l\mathbf{h}^{(l-1)}+\mathbf{b}_l\right), \qquad\mathbf{h}^{(0)}=\mathbf{x}.

The final layer uses the output operation appropriate to the task. Looking at the whole network from outside, it is one function:

y^=F(x;θ),θ={W1,b1,W2,b2,…}.\hat{\mathbf{y}}=F(\mathbf{x};\theta), \qquad \theta=\{W_1,\mathbf{b}_1,W_2,\mathbf{b}_2,\ldots\}.

The hat marks a prediction. The symbol θ\theta collects the learnable parameters: in this network, all the weights and biases. Fix their values and the function gives a prediction for each input. Change their values and you change the model's decision rule.

How many parameters are there?

A dense layer with nn inputs and mm outputs has an m×nm\times n weight matrix and one bias for each output:

Nparameters=mn+m.N_{\text{parameters}}=mn+m.

Count the small network in Figure 9-1:

Count the learnable parameters

Layer 1: 4 inputs → 5 outputs5×4+5=255\times4+5=25
Layer 2: 5 inputs → 5 outputs5×5+5=305\times5+5=30
Layer 3: 5 inputs → 4 outputs4×5+4=244\times5+4=24

Total: 79 learnable parameters

The first layer has 2020 weights and 55 biases; the second has 2525 weights and 55 biases; the third has 2020 weights and 44 biases:

(5⋅4+5)+(5⋅5+5)+(4⋅5+4)=25+30+24=79.(5\cdot4+5)+(5\cdot5+5)+(4\cdot5+4)=25+30+24=79.

Even this small network has 79 adjustable numbers. Larger models may have enormous parameter collections, but the underlying idea of fitting numerical parameters remains the same.

What determines the network's behaviour?

The architecture constrains which functions can be represented. The parameter values choose a particular function within those constraints. Feature definitions, preprocessing and the output interpretation also affect what the model does; parameters are not independent of those choices.

Within a fixed setup, changing the weights and biases changes the predictions. It can make the same architecture useful or useless for the fruit task.

Pause and think

A network can have thousands or millions of parameters. We cannot sensibly guess them all by hand. Where could useful parameter values come from?

I've thought about it — show the answerHide answer

Learn them from data. Make predictions on examples with known targets, measure the error with a loss function, and adjust the parameters to improve that objective. The usual mechanism is gradient-based optimisation: gradients describe how each parameter affects the loss, and an optimiser chooses the update.

The architecture and data still matter. Training is a method for finding useful parameter values, not a guarantee that any architecture or dataset will produce a good model.

3. Training: let data determine the parameters

At the start of training, weights are usually initialised with small random values chosen according to an initialisation scheme; biases may start at zero. These values have not yet been fitted to the task, so the network's predictions are typically poor.

In supervised learning, we have examples with known target labels. Training repeatedly adjusts the parameters to make predictions more useful according to a loss function.

Think back to manually increasing the redness weight and choosing a threshold in Lesson 7. We changed parameters to make a few examples classify correctly. Training automates this idea and applies it to many examples, using a repeatable numerical objective instead of intuition alone.

A batch of examples with target labels1 · Forward passCalculate predictions
y^=F(x;θ)\hat{\mathbf{y}}=F(\mathbf{x};\theta)
2 · LossMeasure prediction error
L(y^,y)L(\hat{\mathbf{y}},\mathbf{y})
3 · GradientsBackpropagate the loss
∇θL\nabla_\theta L
4 · UpdateTake an optimiser step
θ←θ−η∇θL\theta\leftarrow\theta-\eta\nabla_\theta L
Repeat · monitor training and held-out performance
Figure 9-2. One gradient-based training iteration: use a batch to make predictions, calculate the loss, compute parameter gradients and update the parameters. Repeat with more batches. A suitable update may reduce the objective, but every individual batch loss need not decrease.

The four steps

1. Forward pass. Feed a batch of inputs through the network to obtain predictions:

y^i=F(xi;θ).\hat{\mathbf{y}}_i=F(\mathbf{x}_i;\theta).

2. Calculate the loss. Compare predictions with the batch's targets. For a batch BB, a common objective averages the per-example losses:

LB(θ)=1∣B∣∑i∈Bℓ(F(xi;θ),yi).L_B(\theta)=\frac{1}{|B|}\sum_{i\in B}\ell\left(F(\mathbf{x}_i;\theta),\mathbf{y}_i\right).

The loss converts “how wrong were the predictions?” into a number we can optimise. Its form depends on the task.

3. Compute gradients. Use backpropagation to calculate the derivatives of the loss with respect to the parameters:

∇θLB.\nabla_\theta L_B.

Each component tells us how a small change in one parameter would change the loss locally. Backpropagation computes these derivatives efficiently; it does not itself decide the learning rate or perform the optimiser's update.

4. Update parameters. A basic gradient-descent step is:

θ←θ−η∇θLB,η>0.\theta\leftarrow\theta-\eta\nabla_\theta L_B, \qquad\eta>0.

The learning rate η\eta controls the step size. More sophisticated optimisers modify how the gradients are used. Repeat the process with further batches.

A pass through the training dataset is an epoch. One parameter update is an iteration or training step; many iterations may occur within an epoch.

The goal is to improve the objective over training. Individual batch losses can fluctuate, and updates with an unsuitable learning rate can make things worse. Stop according to a training plan and evaluation evidence, rather than assuming every step must improve or that training loss should reach zero.

A map of the next lessons

Each part of this loop will receive its own explanation:

  • Loss functions — Lesson 10: turn prediction errors into a comparable numerical objective.
  • Softmax — Lesson 11: understand how class scores become a probability distribution.
  • Gradient descent and optimisers — Lesson 12: use gradients to choose parameter updates and step sizes.
  • Backpropagation — Lesson 13: efficiently compute the loss derivatives through the network.

Training and inference are different

Training adjusts parameters. In this supervised example it uses target labels, a loss, gradients and optimiser updates. These additional computations and stored intermediate values usually make it more expensive than an ordinary forward pass.

Inference uses the fitted parameters to make predictions on new inputs. The parameters normally remain fixed during inference; an ordinary prediction does not run an optimiser update.

That also explains the experiment at the start of this lesson: moving its sliders changes the inputs, while its hand-picked weights remain fixed. It demonstrates inference, not learning. We will introduce actual parameter updates in the optimisation lessons.

A chatbot generating a response similarly uses a trained model to predict outputs; generation alone does not imply that its weights are being updated by your conversation.

Check performance beyond the training examples

A network can improve its training loss while performing poorly on new data. That is why we evaluate on held-out examples. Validation data helps guide model choices; a separate test set assesses the final setup. This checks generalisation rather than only how well the model fits the examples used for updates.

4. What you have discovered

A neural network connects layers so that one layer's output becomes the next one's input. Nonlinear hidden activations make this more expressive than a single affine transformation.

The whole network is a parameterised function:

y^=F(x;θ).\hat{\mathbf{y}}=F(\mathbf{x};\theta).
  • Architecture: input features, hidden layers, outputs, connectivity, depth and width.
  • Parameters: weights and biases. The dense 4→5→5→44\to5\to5\to4 example has 79 of them.
  • Supervised training: fit parameters using examples with known targets.
  • Training loop: forward pass, calculate loss, compute gradients, update parameters, then repeat.
  • Inference: predict with fitted parameters, normally without changing them.
  • Generalisation: evaluate on held-out data; low training loss alone is insufficient.

This gives us the overall picture. Next we will zoom in on the loop's second step: how do we measure prediction error with a loss function?

Check your understanding

1. What does training a neural network mean in this supervised-learning example?
2. What is the correct order of a standard gradient-based training iteration?