16.1 Backpropagation Algorithm
The Engine of Learning
Backpropagation, short for "backward propagation of errors," is the algorithm that allows us to efficiently train deep neural networks. It's the workhorse that powers modern deep learning, from image recognition to large language models.
The core idea is to calculate the gradient of the loss function with respect to each weight and bias in the network. This tells us how a small change in each parameter affects the overall error. We can then use this information to update the parameters in a way that reduces the error.
The Two-Pass Process
Backpropagation consists of two main passes through the network:
- The Forward Pass: An input is fed into the network, and its value is propagated forward from layer to layer. At each neuron, we calculate the weighted sum of its inputs and apply the activation function. This continues until we get the final output, which is then used to calculate the loss.
- The Backward Pass: This is where the magic happens. We start at the output layer and propagate the error backward. At each layer, we use the chain rule from calculus to compute the gradient of the loss with respect to the layer's weights and biases. This gradient is then passed to the previous layer, and the process continues until we reach the input layer.
A Glimpse at the Math
Let's consider a single neuron. Its output is \(a = f(z)\), where \(z = \sum w_i x_i + b\) is the weighted input and \(f\) is the activation function. The loss is \(L\).
To update a weight \(w_i\), we need the gradient \(\frac{\partial L}{\partial w_i}\). Using the chain rule, we can break this down:
\(\frac{\partial L}{\partial w_i} = \frac{\partial L}{\partial a} \frac{\partial a}{\partial z} \frac{\partial z}{\partial w_i}\)
- \(\frac{\partial L}{\partial a}\) is the gradient from the next layer (this is what's being "backpropagated").
- \(\frac{\partial a}{\partial z} = f'(z)\) is the derivative of the activation function.
- \(\frac{\partial z}{\partial w_i} = x_i\) is the input corresponding to the weight.
By calculating these components at each neuron, we can efficiently compute the gradients for the entire network.
Visualizing Backpropagation
This visualization shows a simple neural network. You can adjust the input and target values. The forward pass calculates the output and error. The backward pass then visualizes the flow of gradients (represented by the thickness and color of the lines) back through the network.
Predicted Output: {{output.toFixed(4)}}
Loss (MSE): {{loss.toFixed(4)}}