Unit II: Backpropagation Networks
Tutorial: Neural Networks Unit II – Backpropagation Networks
Introduction
In Unit I, we studied biological neurons, artificial neurons, weights, biases, and activation functions.
In this unit, we move from a single artificial neuron to the process of training a neural network.
A neural network initially contains parameters such as weights and biases. These parameters are usually initialized with values that do not produce accurate predictions.
Training a neural network involves repeatedly:
- Performing a forward pass.
- Calculating the prediction error.
- Computing gradients using backpropagation.
- Updating the weights and biases.
- Repeating the process until the model improves.
The complete training process can be summarized as:
1. What Is a Backpropagation Network?
A backpropagation network is a neural network trained using the backpropagation algorithm.
Backpropagation itself is not a particular neural-network architecture. Instead, it is an algorithm for efficiently calculating the gradients of the loss function with respect to the network's parameters.
The gradients are then used by an optimization algorithm such as gradient descent or Adam to update the parameters.
For a simple network, the process is:
where:
- = input
- = pre-activation
- = activated output
- = prediction
- = loss
Backpropagation then computes:
and:
These gradients tell us how the loss changes when the parameters change.
2. Forward Propagation
Forward propagation, also called the forward pass, is the process of passing input data through the neural network to produce a prediction.
For a single layer, the basic equation is:
The activation function is then applied:
Here:
| Symbol | Meaning |
|---|---|
| Input vector | |
| Weight matrix | |
| Bias vector | |
| Pre-activation | |
Therefore, a complete layer can be represented as:
3. Multiple Neural Network Layers
A neural network normally contains multiple layers.
For example:
For the first layer:
Then:
The output of the first layer becomes the input to the second layer:
and:
For an -layer network, we can write:
and:
where:
4. Example of Forward Propagation
Consider a simple layer with two inputs and one neuron.
Let:
and:
with bias:
The pre-activation is:
Therefore:
which gives:
If we use ReLU:
then:
Thus, the output of the layer is:
5. Prediction
After the input passes through all required layers, the network produces a prediction.
We commonly represent the prediction using:
The symbol is pronounced "y-hat" and represents the model's predicted value.
For example, suppose the target value is:
and the network predicts:
The prediction is not exactly equal to the target. The difference between the prediction and target is used to calculate the loss.
6. Loss Function
A loss function measures how different the model's prediction is from the desired target.
The loss provides a numerical value that tells us how well the model is performing.
Generally:
where:
- = actual target
- = model prediction
- = loss
A smaller loss generally indicates that the prediction is closer to the target for the chosen loss function.
7. Mean Squared Error
One commonly used loss function for regression is Mean Squared Error (MSE).
For samples:
where:
- = actual value
- = predicted value
- = number of samples
The error is squared so that positive and negative errors do not cancel each other.
8. MSE Example
Suppose we have three target values:
and predictions:
The MSE is:
Therefore:
9. Why Do We Need Backpropagation?
After calculating the loss, we need to determine:
How should each weight and bias change to reduce the loss?
Suppose a network has thousands or millions of parameters. Manually calculating the effect of every parameter would be extremely inefficient.
Backpropagation solves this problem by efficiently calculating gradients using the chain rule of calculus.
For a parameter , we calculate:
This gradient tells us how sensitive the loss is to that parameter.
10. The Chain Rule
The mathematical foundation of backpropagation is the chain rule.
Suppose:
and:
Then:
Each derivative represents how one quantity influences the next. This allows us to calculate gradients through a sequence of operations.
11. Simple Backpropagation Example
Consider:
and:
Suppose the loss is:
We want to calculate:
Using the chain rule:
First:
Since , we have:
And because :
Therefore:
This is the gradient of the loss with respect to the weight.
12. Gradient
A gradient tells us the direction and rate at which the loss changes with respect to the parameters.
For a weight :
For a bias :
For a complete weight matrix:
and for a bias vector:
During training, these gradients are used to update the model parameters.
13. Gradient Descent
Gradient descent is an optimization algorithm used to minimize the loss function.
The basic weight update equation is:
where:
- = current weight
- = updated weight
- = learning rate
- = gradient
The learning rate controls the size of the update.
14. Learning Rate
The learning rate is commonly represented by:
A very small learning rate may cause training to progress slowly.
A very large learning rate can cause unstable training or prevent the optimizer from reaching a good minimum.
The update is:
The same principle applies to biases:
15. Why Do We Subtract the Gradient?
The gradient points in the direction of increasing loss.
Therefore, to reduce the loss, we move in the opposite direction.
This gives:
- If the gradient is positive (), the weight decreases.
- If the gradient is negative (), the weight increases.
16. Complete Training Cycle
The complete neural-network training process can be summarized as:
Step 1: Forward Pass
The input is passed through the network:
Step 2: Calculate Loss
Step 3: Backpropagation
Calculate gradients:
Step 4: Update Parameters
Step 5: Repeat
The process is repeated for many training examples and iterations.
17. Backpropagation Through a Layer
Consider a layer:
followed by:
Suppose the loss is .
Backpropagation calculates the gradient with respect to the pre-activation:
where represents element-wise multiplication.
The gradient with respect to the weights is:
The gradient with respect to the bias is:
And the gradient passed to the previous layer is:
These equations form the core of backpropagation for a fully connected layer.
18. Backpropagation Through Multiple Layers
For multiple layers, gradients are propagated backward from the output layer toward the input layer.
The forward direction is:
The backward direction is:
This is why the algorithm is called backpropagation. The error information is propagated backward through the computational graph.
19. Computational Graph
A neural network can be viewed as a computational graph.
For a simple neuron:
The forward pass moves from left to right.
Backpropagation moves from right to left:
At every operation, the chain rule is used to calculate the required derivatives.
Modern deep-learning frameworks such as PyTorch automatically construct and differentiate these computational graphs.
20. PyTorch Implementation
PyTorch provides automatic differentiation through its autograd system.
A simple neural-network example is:
1import torch 2import torch.nn as nn 3 4model = nn.Linear(3, 1) 5 6x = torch.tensor([[2., 3., 4.]]) 7target = torch.tensor([[10.]]) 8 9prediction = model(x) 10 11loss_fn = nn.MSELoss() 12loss = loss_fn(prediction, target) 13 14loss.backward() 15 16print("Prediction:", prediction) 17print("Loss:", loss) 18print("Weight gradient:", model.weight.grad) 19print("Bias gradient:", model.bias.grad)
21. Understanding the PyTorch Code
Creating the Model
1model = nn.Linear(3, 1)
This creates a fully connected linear layer with:
- 3 input features
- 1 output feature
Mathematically, it performs:
The weight matrix has shape and the bias has shape .
22. Creating the Input
1x = torch.tensor([[2., 3., 4.]])
The input contains three features:
The batch size is , so the tensor has shape .
23. Creating the Target
1target = torch.tensor([[10.]])
The desired output is . The target tensor has shape .
24. Forward Pass in PyTorch
1prediction = model(x)
Internally, the linear layer performs:
The actual value depends on the randomly initialized parameters of the model.
25. Calculating the Loss
1loss_fn = nn.MSELoss() 2loss = loss_fn(prediction, target)
For a single prediction, MSE is:
26. Calling backward()
1loss.backward()
This tells PyTorch to calculate the gradients of the loss with respect to parameters that require gradients:
The calculated gradients are stored in model.weight.grad and model.bias.grad.
27. Inspecting the Gradients
1print("Weight gradient:", model.weight.grad) 2print("Bias gradient:", model.bias.grad)
The gradient tells us how changing the parameters would affect the loss locally.
28. Important: backward() Does Not Update Weights
A common beginner mistake is assuming that loss.backward() updates the model parameters. It does not.
backward() only calculates gradients. The actual parameter update is performed by an optimizer.
Example:
1optimizer = torch.optim.SGD(model.parameters(), lr=0.01) 2optimizer.step()
The typical sequence is:
1optimizer.zero_grad() 2prediction = model(x) 3loss = loss_fn(prediction, target) 4loss.backward() 5optimizer.step()
Mathematically, the optimizer performs:
29. Complete PyTorch Training Example
1import torch 2import torch.nn as nn 3 4model = nn.Linear(3, 1) 5x = torch.tensor([[2., 3., 4.]]) 6target = torch.tensor([[10.]]) 7 8loss_fn = nn.MSELoss() 9optimizer = torch.optim.SGD(model.parameters(), lr=0.01) 10 11for step in range(100): 12 optimizer.zero_grad() # Clear old gradients 13 prediction = model(x) # Forward propagation 14 loss = loss_fn(prediction, target) 15 loss.backward() # Backpropagation 16 optimizer.step() # Update parameters 17 18 if step % 10 == 0: 19 print(f"Step: {step}, Loss: {loss.item():.4f}")
The training process is:
30. Why Do We Zero the Gradients?
PyTorch accumulates gradients by default. Therefore, before calculating gradients for the next iteration, we clear the existing gradients:
1optimizer.zero_grad()
Otherwise, gradients from multiple iterations can accumulate.
31. Full Backpropagation Pipeline
The entire process can be visualized as:
Then:
Finally, the optimizer updates the parameters:
32. Forward Propagation vs Backpropagation
| Forward Propagation | Backpropagation |
|---|---|
| Moves from input to output | Moves from output toward input |
| Calculates predictions | Calculates gradients |
| Uses weights and biases | Uses derivatives |
| Produces the loss | Determines how parameters affect the loss |
| Happens before loss calculation | Happens after loss calculation |
The complete process is:
33. Common Mistakes
Mistake 1: Thinking backward() Updates Weights
Incorrect: loss.backward() does not update parameters.
Correct: loss.backward() + optimizer.step()
Mistake 2: Forgetting to Clear Gradients
Always use optimizer.zero_grad() before the forward/backward cycle.
Mistake 3: Using the Wrong Tensor Shapes
For nn.Linear(3, 1), an input with one sample should have shape :
1x = torch.tensor([[2., 3., 4.]])
Mistake 4: Using an Inappropriate Loss Function
MSE is commonly used for regression:
For classification, cross-entropy is preferred.
34. Key Formulas
Forward Propagation
Activation
Prediction
Mean Squared Error
Gradient Descent
Bias Update
Chain Rule
35. Summary
Backpropagation is one of the fundamental algorithms used to train neural networks.
During forward propagation, the input travels through the network:
The prediction is compared with the target using a loss function:
Backpropagation then uses the chain rule to calculate how the loss changes with respect to each parameter:
An optimizer uses these gradients to update the parameters:
The complete training cycle is:
PyTorch automates the gradient-calculation portion through its autograd system, allowing us to train complex neural networks without manually deriving every gradient.
Next Topics
After understanding backpropagation networks, the next important topics are:
- Gradient Descent in Detail
- Stochastic Gradient Descent
- Mini-Batch Training
- Cross-Entropy Loss
- Optimizers
- Adam Optimizer
- Learning Rate Scheduling
- Vanishing and Exploding Gradients
- Weight Initialization
- Regularization and Dropout
- Multi-Layer Perceptrons
- Deep Neural Network Training
All mathematical expressions are now clean, valid KaTeX, and will render correctly with your ReactMarkdown configuration.