From neurons to perceptrons
McCulloch and Pitts described an idealised neuron that sums weighted binary inputs and fires when the sum exceeds a threshold, and showed that networks of such units can compute logical functions [1]. Rosenblatt's perceptron added learning: After each example, the weights move in the direction that corrects a wrong output, w = w + eta (y - y_hat) x [2]. If the two classes can be separated by a straight line, or a hyperplane in more dimensions, the rule finds a separating line in a finite number of steps.
Minsky and Papert analysed what single-layer perceptrons cannot do [3]. The exclusive or, XOR, is the classic example: The points (0, 0) and (1, 1) belong to one class and (0, 1) and (1, 0) to the other, and no straight line separates them. Engineering data are full of such interactions, for example when a fault appears only if temperature is high and speed is low. The remedy is a hidden layer that transforms the inputs into a space where the classes become separable.
Check your understanding. Why can a single perceptron not learn XOR?
Formulas: The threshold neuron and the perceptron rule
A threshold neuron multiplies its inputs by weights and fires when the weighted sum reaches a threshold [1]. Writing the threshold as a negative bias , the perceptron computes a score and a binary output :
The output changes where , so the decision boundary is a straight line for two inputs and a plane or hyperplane for more. The weight vector is perpendicular to the boundary, and an input lies at the distance from it. Part A of the interactive lab shows this boundary for a single neuron with adjustable weights, bias and activation.
Rosenblatt's learning rule visits the training examples one at a time [2]. For an example with the target , the output and the error , it changes every weight and the bias with a learning rate :
A correct output gives and no change, a missed positive example gives , and a false alarm gives . Inserting the new weights into the score of the same input shows why the rule corrects mistakes:
The score of the input rises after a missed positive and falls after a false alarm, although one correction may not be enough to change the output. If a hyperplane separates the two classes, the perceptron convergence theorem guarantees that the corrections stop after a finite number of mistakes. If no hyperplane separates them, every pass through the data contains a mistake, and the weights never settle [3].
Worked example: A perceptron learns the AND function
A two-hand control releases a press only when both of its buttons are pressed, which is the AND function of two binary inputs. A perceptron starts with and . Its scores for the inputs (0, 0), (0, 1), (1, 0) and (1, 1) are 0.1, 0.6, 0.6 and 1.1, so it fires for every input. It learns with and visits the examples in this order, with the targets 0, 0, 0 and 1.
Step 1. Input (0, 0), target 0. The score is , so and , a false alarm. The inputs are zero, so only the bias changes:
Step 2. Input (0, 1), target 0. The score is , another false alarm with :
By the formula above, the score of this input falls by , from 0.4 to exactly 0, which still fires. One correction is not enough here.
Step 3. Input (1, 0), target 0. The score is , a third false alarm:
Step 4. Input (1, 1), target 1. The score is , so , and nothing changes.
Step 5. The second pass. With and , every example is classified correctly, so training stops after a full pass without a mistake:
| Input | Score | Output | Target |
|---|---|---|---|
| (0, 0) | 0 | 0 | |
| (0, 1) | 0 | 0 | |
| (1, 0) | 0 | 0 | |
| (1, 1) | 1 | 1 |
The boundary , or , leaves only (1, 1) on the firing side. Part B of the interactive lab replays these steps and tries other functions.
Worked example: Why the exclusive or needs a hidden layer
Step 1. No single perceptron computes it. Suppose that weights and a bias computed the exclusive or, XOR. The outputs 0 for (0, 0) and (1, 1) and the outputs 1 for (0, 1) and (1, 0) would require, in this order,
Adding the last two inequalities gives , while adding the first two gives . Both cannot hold, so no such weights exist [3].
Step 2. Two hidden units. The network of the notebook has a hidden unit with both weights equal to 1 and the bias −0.5, which computes OR, and a hidden unit with both weights equal to 1 and the bias −1.5, which computes AND. With step activations, the hidden layer gives
| 0 | 0 | 0 | 0 | ||
| 0 | 1 | 1 | 0 | ||
| 1 | 0 | 1 | 0 | ||
| 1 | 1 | 1 | 1 |
Step 3. The output unit. The output unit has the weights 1 and −1 and the bias −0.5:
| Input | XOR | ||||
|---|---|---|---|---|---|
| (0, 0) | 0 | 0 | 0 | 0 | |
| (0, 1) | 1 | 0 | 1 | 1 | |
| (1, 0) | 1 | 0 | 1 | 1 | |
| (1, 1) | 1 | 1 | 0 | 0 |
Step 4. What the hidden layer does. In the plane of , the four inputs become three points: (0, 0) for the input (0, 0), (1, 0) for both (0, 1) and (1, 0), and (1, 1) for the input (1, 1). The line separates the point (1, 0) from the other two, so the output unit, an ordinary perceptron, finishes the job. The hidden layer has transformed the inputs into a space in which the classes are linearly separable. Part B of the lab shows the perceptron rule failing on XOR, and Part C trains a network that finds such a transformation by itself.
Multilayer networks and backpropagation
A multilayer perceptron stacks layers of units. Each unit computes a weighted sum of the outputs of the previous layer and applies a nonlinear activation function: the logistic sigmoid, the hyperbolic tangent, or the rectified linear unit, ReLU, which returns max(0, z) and eases the training of deep networks [4]. Without nonlinear activations, any stack of layers collapses into one linear map. With them, a network with one sufficiently wide hidden layer can approximate any continuous function on a bounded domain to any accuracy [5, 6], although the theorem says nothing about how many units are needed or whether training finds them.
Training minimises a loss, such as the mean squared error for regression or the cross-entropy for classification, by gradient descent. Backpropagation computes the gradient of the loss with respect to every weight efficiently by applying the chain rule layer by layer from the output back to the input [7]. Each weight then moves a small step against its gradient. Modern frameworks such as PyTorch record the operations of the forward pass and compute these gradients automatically [8].
Animation: A small network learns a curved boundary
A network with one hidden layer is trained by gradient descent on points from two classes. Change the number of hidden units and the learning rate, and watch the boundary bend while the loss falls.
Check your understanding. What does backpropagation compute?
Formulas: Layers, activation functions and backpropagation
A layer receives the outputs of the previous layer, where is the input. Each unit of the layer forms a weighted sum with its weights and its bias and applies an activation function :
The weight connects unit of layer to unit of layer . The common activation functions are the logistic sigmoid, the hyperbolic tangent and the rectified linear unit [4, 9]:
Backpropagation needs their derivatives. For the sigmoid, the quotient rule and give
and for the other two
with the value 0 used in practice at . The sigmoid has its largest slope, 0.25, at , and the slopes of the sigmoid and of tanh approach zero for large , where the unit saturates. ReLU passes the gradient unchanged wherever the unit is active.
Without an activation function, two layers with the weight matrices and the bias vectors collapse into a single linear map:
Stacking more linear layers adds nothing. With a nonlinear activation, one hidden layer of units computes
and Cybenko and Hornik and colleagues proved that such sums with sigmoid-shaped activations approximate any continuous function on a bounded domain as closely as desired when is large enough [5, 6].
Training minimises a loss averaged over the training examples, usually the mean squared error for regression and, for an output probability , the cross-entropy of Week 8:
Backpropagation computes the derivative of the loss with respect to every weight with the chain rule [7]. The central quantity is the error signal of each unit, the sensitivity of the loss to the weighted sum of the unit. For an output unit,
and a hidden unit of layer , whose output feeds the units of layer , collects the error signals of these units through the connecting weights:
The gradient of a weight is the error signal of the unit that the weight enters times the activation that it carries, and the gradient of a bias is the error signal itself:
The error signals are computed from the output backwards, which gives the method its name, and then every parameter takes a gradient descent step . For a sigmoid output with the cross-entropy of one example, the output error signal becomes very simple:
This is the error signal at the output of the notebook's network. Frameworks such as PyTorch record the operations of the forward pass and apply the chain rule automatically [8].
Worked example: One backpropagation step by hand
A network with two inputs, two sigmoid hidden units and one sigmoid output receives the example with the target . Hidden unit has the weights and the bias , and the output unit has the weights and the bias :
| Unit | Weights | Bias |
|---|---|---|
| Hidden unit 1 | , | |
| Hidden unit 2 | , | |
| Output unit | , |
The loss of the example is , where the factor 1/2 cancels the 2 of the derivative, and the learning rate is . For this network, the formulas of backpropagation read
All values are rounded to six decimals, and every later step uses the rounded values.
Step 1. Forward pass through the hidden layer.
Step 2. Output and loss.
Step 3. Error signal of the output. The derivative of the loss is , and the slope of the sigmoid is , so
Step 4. Gradients of the output unit.
and .
Step 5. Error signals of the hidden units. The slopes of the hidden units are and . The output error travels back through the output weights as they were before the update:
The second hidden unit receives a positive error signal because its output weight is negative: Increasing its weighted sum would lower and raise the loss.
Step 6. Gradients of the hidden units. With and :
| Parameter | Gradient |
|---|---|
Step 7. The update. Every parameter moves against its gradient with :
| Parameter | Old value | Gradient | New value |
|---|---|---|---|
| 0.4 | −0.009477 | ||
| −0.2 | −0.018954 | ||
| 0.1 | −0.018954 | ||
| 0.3 | 0.006117 | ||
| 0.6 | 0.012234 | ||
| −0.1 | 0.012234 | ||
| 0.7 | −0.057001 | ||
| −0.5 | −0.071336 | ||
| 0.2 | −0.108577 |
Step 8. The effect. A forward pass with the new parameters, with the products rounded to six decimals, gives
The loss has fallen from 0.097037 to 0.086754, and the output has moved from 0.559462 towards the target 1, to 0.583457.
Step 9. A numerical check. A gradient can be checked with a central difference, whose error shrinks with the square of the step :
Recomputing the loss without rounding for and , with , gives and , so that
which agrees with from Step 4. The notebook checks a gradient of its XOR network in the same way, and Part D of the interactive lab repeats this example number by number for any weights.
Optimisation in practice
Plain gradient descent uses the whole training set for every step. Stochastic gradient descent uses small random mini-batches, which is faster and adds noise that can help to escape poor regions. Momentum accumulates a moving average of gradients and damps oscillation across narrow valleys. Adam adapts the step size of every weight from running estimates of the first and second moments of its gradient and is a robust default [10]. The learning rate remains the most important setting: Too small and training crawls, too large and the loss oscillates or diverges.
Initialisation matters because signals must neither vanish nor explode as they pass through many layers. Glorot and Bengio proposed scaling the initial weights with the number of inputs and outputs of a layer [11]. Batch normalisation standardises the inputs of a layer over each mini-batch and often allows larger learning rates [12]. Inputs of different units, such as temperatures in degrees and pressures in millibars, should be standardised before training, as for k-means and support vector machines.
Formulas: Gradient descent, momentum, Adam, initialisation and normalisation
Training minimises the average loss of the training examples, where collects all weights and biases and is the loss of example . Gradient descent takes steps against the gradient , the vector of all partial derivatives. Stochastic gradient descent estimates the gradient from a random mini-batch of examples [9]:
One pass through all mini-batches is an epoch, so an epoch takes steps. Momentum keeps a velocity , a decaying sum of past steps with a factor , typically 0.9 [7, 9]:
Steps that point the same way accumulate, and steps that alternate across a narrow valley cancel. Adam keeps running means of the gradient and of its square for every parameter, corrects their bias towards zero in the first steps, and divides the first by the square root of the second [10]:
Here counts the steps, and start at zero, and the defaults are , and . All operations act on every parameter separately.
The learning rate decides whether gradient descent converges at all. For the loss with , the gradient is , and one step changes the error to
The error shrinks steadily for , shrinks with an alternating sign for , and does not shrink for . In many dimensions, the steepest direction limits the learning rate, while the flattest direction sets the speed, which is the difficulty of the narrow valley in Part E of the lab.
Initialisation sets the scale of the signals. For a weighted sum of independent inputs with mean zero and independent weights with mean zero, the variances multiply:
Keeping the variance of the signals from layer to layer requires , and keeping the variance of the error signals on the way back requires , where is the number of units of the layer. Glorot and Bengio proposed the compromise [11]
since a uniform distribution on the interval from to has the variance .
Batch normalisation standardises the weighted sums of a unit over each mini-batch of examples and then rescales them with two learned parameters, and [12]:
The small constant prevents a division by zero. At test time, running averages of and collected during training take the place of the statistics of the batch.
Worked example: Three optimisers on one loss
The loss has its minimum at and the gradient . All three optimisers start at with . Momentum uses , and Adam uses its defaults.
Step 1. Gradient descent.
Step 2. Momentum. With , the first step equals that of gradient descent, so the second gradient is again :
Step 3. Adam, first step. With and :
The bias correction undoes the start at zero, and the first step has the length whatever the size of the gradient, because .
Step 4. Adam, second step. Now and :
With , the step is
Step 5. Comparison. After two steps:
| Optimiser | ||
|---|---|---|
| Gradient descent | 1.08 | |
| Momentum | 1.62 | |
| Adam | 0.199897 |
Momentum is fastest here because its steps accumulate. Adam is slowest because its steps have a length of about , so with Adam the learning rate is roughly the largest change of a weight in one step [10].
Step 6. The learning rate. Here , so the error factor is . With , the factor 0.8 turns the error into −2.4 and −1.92, the values of Step 1. With , the factor is −0.5: The errors are 1.5 and −0.75, so jumps to 4.5 and back to 2.25 while it converges. With , the factor is −1.2: The errors are 3.6 and −4.32, so goes to 6.6 and then to −1.32, and the iteration diverges. Part F of the interactive lab runs all three optimisers on any loss of this form.
Worked example: Initial weights and a normalised mini-batch
Step 1. The Glorot range. The first layer of a network for the eight inputs of the concrete data of Week 7 has 16 units, so and :
which equals .
Step 2. The signal of one unit. For standardised inputs, with the variance 1, the weighted sum of a unit has
A tanh unit whose weighted sum lies one standard deviation from zero, at , has the output and the slope , so it passes gradients well. With weights drawn from instead, and , so the standard deviation is . At this typical value, and the slope is : The unit is saturated and passes almost no gradient back.
Step 3. Batch normalisation. One unit produces the weighted sums 2, 4, 6 and 8 for a mini-batch of four examples. With , the default of PyTorch:
and by symmetry and . With and :
The normalised values have the mean 0 and the variance , so the outputs have the mean and a standard deviation very close to . Because and are learned, the network can undo the normalisation where that helps. Part G of the lab follows signals through many layers and normalises any mini-batch.
Generalisation and regularisation
Networks with many weights can memorise their training data. The standard defences are a validation set with early stopping, which keeps the weights from the epoch with the lowest validation loss; weight decay, which penalises large weights like ridge regression; and dropout, which randomly switches off units during training so that the network cannot rely on any single unit [13]. Learning curves of training and validation loss over epochs show whether a network underfits, with both losses high, or overfits, with a growing gap.
On tabular data of moderate size, the tree ensembles of Weeks 7 and 8 are often as accurate as networks and easier to tune, so a network must earn its place by a fair comparison. Networks have long been applied in engineering: Yeh modelled concrete strength with them [14], and metaheuristics such as the ant lion optimiser have been used to train them where gradient methods struggle [15]. Their decisive advantages appear with images, signals, sequences and text, where they learn features that would otherwise have to be designed by hand [16]. Weeks 11 to 13 follow this path.
Check your understanding. Training loss keeps falling, while validation loss has been rising for 30 epochs. What should be done?
Formulas: Parameters, weight decay, dropout and early stopping
A fully connected layer with inputs and units has weights and biases. A network with the layer sizes , from the inputs to the outputs, therefore has
trainable parameters. When approaches the number of training examples, the network can fit the training data closely, noise included.
Weight decay adds the squared weights to the loss with a factor , as ridge regression does in Week 7 [9]:
A gradient step therefore shrinks every weight by the factor before it applies the gradient of the data:
Weights that the data do not support decay towards zero.
Dropout switches units off at random during training [13]. Each output of a layer is multiplied by an independent mask value , which is 1 with the keep probability and 0 otherwise. Deep learning libraries such as PyTorch also divide by , so that the expected value of every output stays the same:
At test time, all units are used without a mask. Srivastava and colleagues multiplied the outgoing weights by at test time instead, which gives the same expected values. In PyTorch, the argument of the dropout layer is the probability of dropping a unit, .
Early stopping computes the validation loss after every epoch and keeps the weights of the epoch with the lowest value,
It stops training when the best value has not improved for consecutive epochs, the patience. The difference , the generalisation gap, grows when the network starts to memorise its training data.
Worked example: Parameters and weight decay of a small network
Step 1. Counting parameters. A network for the concrete data of Week 7, with the seven ingredients and the age as its eight inputs, two hidden layers of 16 units and one output, has the layer sizes 8, 16, 16 and 1:
Step 2. Data per parameter. The data set has 1030 mixes, which gives examples per parameter. A training split of 80% keeps mixes and examples per parameter. Such a network can fit noise unless it is regularised and checked on validation data.
Step 3. One step with weight decay. A weight has the gradient , the learning rate is , and . The shrink factor is , so
Without weight decay, the step would give .
Step 4. Decay in the long run. A weight that receives no gradient from the data keeps the fraction 0.999 of its value in every step. After 1000 steps it keeps
of its value, close to after steps. Part H of the interactive lab counts parameters, applies weight decay and draws dropout masks.
Worked example: Dropout and early stopping
Step 1. One dropout mask. A hidden layer has the outputs , and a unit of the next layer has the weights . At test time, its weighted sum is
During training with , the mask keeps the first and third units and doubles their outputs, , so
Step 2. The expected value. The complementary mask gives and
The two masks are equally likely, and their mean is the test value. The mean over all 16 equally likely masks is also exactly 0.61, since every unit is kept in half of them. Single masks give very different sums, and this noise keeps the network from relying on any single unit.
Step 3. Early stopping. A network is trained with a patience of three epochs:
| Epoch | Training loss | Validation loss | Gap | Best so far | Epochs without improvement |
|---|---|---|---|---|---|
| 1 | 0.50 | 0.52 | 0.52 (epoch 1) | 0 | |
| 2 | 0.38 | 0.41 | 0.41 (epoch 2) | 0 | |
| 3 | 0.31 | 0.36 | 0.36 (epoch 3) | 0 | |
| 4 | 0.27 | 0.34 | 0.34 (epoch 4) | 0 | |
| 5 | 0.24 | 0.35 | 0.34 (epoch 4) | 1 | |
| 6 | 0.21 | 0.37 | 0.34 (epoch 4) | 2 | |
| 7 | 0.19 | 0.36 | 0.34 (epoch 4) | 3 |
After epoch 7, the validation loss has not improved for three epochs, so training stops and the weights of epoch 4, with the validation loss 0.34, are restored. Epoch 7 is better than epoch 6 but not better than the best value, so the counter keeps rising.
Step 4. Reading the curves. The training loss falls in every epoch, while the gap grows from 0.07 to 0.17 after epoch 4: The network has started to fit the noise of its training data. Two high losses close to each other would instead signal underfitting, which calls for a larger network or longer training rather than more regularisation. Part I of the lab applies the rule to any losses and trains a small network until it overfits.
Python step 10: Matrices, shapes and tensors
The Python step of this week is part of the Colab notebook, where every explanation stands next to a cell that runs it and the step closes with a quick check and exercises with immediate feedback. The printable lecture notes contain the same step together with the outputs of its code. The Colab button below opens the notebook at the step. Run the setup cell just above the step first, since the exercises use its check function.
Review cards
Select a card to turn it over.
Continue the week
The week continues with the simulation and the self-assessment of the interactive lab and with the Python step and the hands-on work of the Colab notebook. The week overview lists the discipline challenges, the weekly task and the research assignment.
Interactive lab Colab notebook Self-assessment Week overview and tasks
References
[1] McCulloch, W. S., & Pitts, W. (1943). A logical calculus of the ideas immanent in nervous activity. The Bulletin of Mathematical Biophysics, 5(4), 115-133. https://doi.org/10.1007/BF02478259
[2] Rosenblatt, F. (1958). The perceptron: A probabilistic model for information storage and organization in the brain. Psychological Review, 65(6), 386-408. https://doi.org/10.1037/h0042519
[3] Minsky, M., & Papert, S. (1969). Perceptrons: An Introduction to Computational Geometry. MIT Press.
[4] Nair, V., & Hinton, G. E. (2010). Rectified linear units improve restricted Boltzmann machines. In Proceedings of the 27th International Conference on Machine Learning (pp. 807-814).
[5] Cybenko, G. (1989). Approximation by superpositions of a sigmoidal function. Mathematics of Control, Signals and Systems, 2(4), 303-314. https://doi.org/10.1007/BF02551274
[6] Hornik, K., Stinchcombe, M., & White, H. (1989). Multilayer feedforward networks are universal approximators. Neural Networks, 2(5), 359-366. https://doi.org/10.1016/0893-6080(89)90020-8
[7] Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323(6088), 533-536. https://doi.org/10.1038/323533a0
[8] Paszke, A., Gross, S., Massa, F., et al. (2019). PyTorch: An imperative style, high-performance deep learning library. In Advances in Neural Information Processing Systems 32 (pp. 8024-8035). https://arxiv.org/abs/1912.01703
[9] Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning. MIT Press.
[10] Kingma, D. P., & Ba, J. (2015). Adam: A method for stochastic optimization. In 3rd International Conference on Learning Representations (ICLR 2015). https://arxiv.org/abs/1412.6980
[11] Glorot, X., & Bengio, Y. (2010). Understanding the difficulty of training deep feedforward neural networks. In Proceedings of the Thirteenth International Conference on Artificial Intelligence and Statistics, PMLR 9 (pp. 249-256).
[12] Ioffe, S., & Szegedy, C. (2015). Batch normalization: Accelerating deep network training by reducing internal covariate shift. In Proceedings of the 32nd International Conference on Machine Learning, PMLR 37 (pp. 448-456). https://arxiv.org/abs/1502.03167
[13] Srivastava, N., Hinton, G., Krizhevsky, A., Sutskever, I., & Salakhutdinov, R. (2014). Dropout: A simple way to prevent neural networks from overfitting. Journal of Machine Learning Research, 15(56), 1929-1958.
[14] Yeh, I.-C. (1998). Modeling of strength of high-performance concrete using artificial neural networks. Cement and Concrete Research, 28(12), 1797-1808. https://doi.org/10.1016/S0008-8846(98)00165-3
[15] Kose, U. (2018). An ant-lion optimizer-trained artificial neural network system for chaotic electroencephalogram (EEG) prediction. Applied Sciences, 8(9), 1613. https://doi.org/10.3390/app8091613
[16] LeCun, Y., Bengio, Y., & Hinton, G. (2015). Deep learning. Nature, 521(7553), 436-444. https://doi.org/10.1038/nature14539