Introduction to Neural Networks and Backpropagation
Tue 30 Apr 2024 - 12 min readI originally wrote these notes as a way to make the concepts more concrete for myself.
Neural networks are a family of function approximators built by composing layers of relatively simple mathematical operations. Their name comes from a loose analogy with biological neurons, but modern neural networks should not be mistaken for realistic models of the brain.
Despite the simplicity of their individual parts, neural networks can approximate complicated relationships in data. They are used for tasks such as image classification, recommendation systems, sequence modelling and many other kinds of function approximation.
In this post, I’ll build up a small fully connected neural network from individual neurons, describe how information moves through it and then derive the backpropagation algorithm used to calculate its gradients. Finally, we’ll use those gradients to train the network with gradient descent.
An introduction to Neural Networks
Perceptron (single-neuron function)
One influential early model was Frank Rosenblatt’s perceptron, introduced in the late 1950s in the paper “The Perceptron: A probabilistic model for information storage and organization in the brain”1. A perceptron combines several inputs into a weighted sum and applies a threshold to produce its output. Modern artificial neurons use the same broad pattern, although they commonly use differentiable activation functions instead of a hard threshold.
A perceptron receives inputs . Each input has a corresponding adjustable weight . Together with a bias , these values form a weighted sum of the inputs.
Figure 1: The weighted sum and activation of a single neuron.This means multiplying every input by its corresponding weight , summing the results and adding the bias. The resulting scalar is the pre-activation :
where is the -th input, is its weight, is the bias and is the number of inputs.
In Rosenblatt’s formulation, this value is passed through a step function. The perceptron outputs if is greater than and otherwise:
Modern artificial neurons keep the same weighted sum but replace the hard threshold with a more general activation function :
Here, is the neuron’s scalar output, or activation. Common choices for include ReLU, sigmoid and hyperbolic tangent. They all introduce nonlinearity, but they have different ranges and behave differently during training.
This becomes cumbersome notation for when we need to describe larger networks with multiple layers or multiple neurons per layer. For this reason we can make use of vector and matrix notation to better organise our data.
Now we can instead represent both and as column-vectors.
Because both are column vectors, the weighted sum can be written as . We then add the bias and apply the activation function:
So, to summarise, a neuron takes an input vector and produces a scalar. It calculates a weighted sum of the inputs, adds a bias and applies a nonlinear activation function.
The nonlinearity is important because it allows a network to model nonlinear relationships. Without nonlinear activation functions, a stack of layers would still be equivalent to a single linear transformation. For example, composing these two linear functions only produces another linear function:
Multiple neurons and the MLP
A multi-layer perceptron (also called an MLP) is built by arranging our neurons into layers. In what’s called a fully connected layer, every neuron receives every activation from the previous layer as input. Each neuron has its own weights and bias so each can produces a distinct scalar output from the same input vector.
We can collect these individual scalar outputs into a column vector , where identifies the layer. For example, the two outputs and in the diagram below form the activation vector .
Figure 2: Two neuron outputs collected into the activation vector .Suppose layer contains activations and layer contains neurons. The weights for the whole layer can be represented by a matrix with rows and columns:
The entry is the weight connecting activation in the previous layer to neuron in layer . The first index therefore selects a destination neuron, while the second selects an input to that neuron. Each neuron also has its own bias, collected in the vector
This gives us the dimensions
Figure 3: A two-layer fully connected network.The layer first computes a vector of pre-activations and then applies the activation function elementwise:
Both and are vectors in . In our network pictured above, the input vector is , the hidden layer produces , and the output layer produces .
More generally, an MLP repeats this calculation for layers , using the activation from one layer as the input to the next. Evaluating those layers from through to is called the forward pass. Training the network requires working in the opposite direction to determine how each parameter influenced the final error. That is the purpose of backpropagation.
Backpropagation and optimization (training)
Neural networks are trained by adjusting these weights and biases so that their predictions produce a smaller loss. We do this by first determining how each parameter contributes to said loss.
Backpropagation utilises the chain rule from differential calculus to compute the gradient of the loss function, also known as an objective function, with respect to every weight and bias in the network. It starts from the output and propagates this information back through each layer.
An optimization algorithm such as gradient descent then uses the resulting gradients to update the parameters.
Loss calculation
A loss function measures how far the network’s prediction is from the desired target , producing a single scalar . Mean squared error (MLE) is a common choice for regression while classification problems often use a form of cross entropy.
The choice of loss function determines the gradient at the output layer. From there, backpropagation then uses the chain rule to propagate that gradient through the rest of the network.
For each layer , define the pre-activation gradient
The vector has the same dimensions as . At the output layer, the chain rule gives
where denotes elementwise multiplication.
In order to calculate for an earlier layer, we follow the computational path from the loss back to the pre-activations , applying the chain rule at each step.
Starting with at the output layer, we can work backwards through the network to obtain the pre-activation gradient for each preceding layer.
Figure 4: Backpropagation follows the computational path in reverse.Rather than expanding the entire chain for every layer, we can simplify the calculation by only looking at layer and the following layer . Suppose the two layers contain and neurons, respectively. Starting with the definition of the next layer’s pre-activation and working backwards through the linear transformation and activation function gives
This gives us the backward step: once we know , we can calculate and continue backwards through the network. The transposed weight matrix reverses the mapping from to .
Finally, the parameter gradients are computed, which are the changes in the loss function with respect to the parameters and . Looking at an individual weight and bias first, and then collecting the results, we get:
Now that we know how each parameter in our neural net influences the loss, we just need to figure out how to optimize our network to minimise the loss. Luckily, there is a simple and effective way of doing that as we’ve already done the hard part.
Gradient descent and optimization
The gradient points in the direction in which the loss increases most quickly. Gradient descent therefore updates each parameter in the opposite direction. Using the parameter gradients derived above, the updates for layer are
where is the learning rate, which controls the size of each update.
Ordinary gradient descent calculates these gradients over the entire training set before performing an update. Stochastic gradient descent (SGD) instead uses a randomly selected training example or, more commonly, a small batch of examples. Each update is then cheaper to compute, although the resulting gradient is a noisier estimate of the full-dataset gradient.
Training basically just consists of repeating these steps: perform a forward pass, calculate the loss, use backpropagation to calculate the parameter gradients and finally update the parameters. Repeating this process allows the network to gradually find parameters that produce a smaller loss on the training data.
- 1Rosenblatt, 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.