Backpropagation in a Single-Layer Neural Network Using Matrix Operations
Backpropagation is the cornerstone of neural network training, allowing networks to learn by propagating errors backward and adjusting weights accordingly. Let's break down how a basic single-layer neural network trains itself through backpropagation using matrix operations.
Basic Structure of a Single-Layer Neural Network
A single-layer neural network consists of:
- Input layer (X): The features of our training examples
- Weights (W): Parameters connecting inputs to outputs
- Bias (b): Additional parameter added to the weighted sum
- Activation function: Typically sigmoid or ReLU
- Output layer (y): The prediction result
The Forward Pass
The forward pass involves propagating the input through the network to generate predictions:
- Start with input matrix X of shape [n_examples × n_features]
- Apply weights W of shape [n_features × n_outputs]
- Calculate the weighted sum: Z = XW
- Apply the activation function (sigmoid): ŷ = σ(Z)
In matrix form:
# Forward propagation
Z = np.dot(X, W) # Weighted sum
y_pred = sigmoid(Z) # Apply activation function
The sigmoid function is defined as:
( \sigma(z) = \frac{1}{1 + e^{-z}} )
Computing the Error
After forward propagation, we compare our predictions to the actual target values:
# Calculate error
error = y_actual - y_pred
Where:
- y_actual is the matrix of true output values
- y_pred is our network's predictions
The Backward Pass (Backpropagation)
The core of backpropagation is calculating how much each weight contributed to the error, then updating weights accordingly:
-
Calculate the gradient of the error with respect to the output:
# Calculate the gradient of the error
delta = error * sigmoid_derivative(y_pred)
The sigmoid derivative can be calculated as:
( \sigma'(z) = \sigma(z) \times (1 - \sigma(z)) )
-
Calculate the gradient with respect to the weights using the chain rule:
# Calculate weight gradients
weight_gradients = np.dot(X.T, delta)
-
Update the weights using gradient descent:
# Update weights
W += learning_rate * weight_gradients
The matrix operations here are elegant and efficient:
- X.T is the transpose of the input matrix
- The dot product X.T and delta gives us the gradient for all weights simultaneously
Complete Training Loop
Putting it all together, the training algorithm looks like this:
def train_single_layer_network(X, y, learning_rate=0.1, max_iterations=1000, tolerance=0.001):
# Initialize weights randomly
n_features = X.shape[1]
n_outputs = y.shape[1]
W = np.random.randn(n_features, n_outputs) * 0.01
for i in range(max_iterations):
# Forward propagation
Z = np.dot(X, W)
y_pred = sigmoid(Z)
# Calculate error
error = y - y_pred
# Check for convergence
if np.abs(error).max() < tolerance:
print(f"Converged after {i} iterations")
break
# Backpropagation
delta = error * sigmoid_derivative(y_pred)
# Update weights
W += learning_rate * np.dot(X.T, delta)
return W
The Matrix Advantage
Using matrices provides several benefits:
- We can process all training examples simultaneously (batch processing)[10]
- Vectorized operations are much faster than loops[5]
- The code becomes cleaner and more readable[6]
Example Walk-through
Let's consider a simple example with 4 training examples, 3 input features, and 1 output:
- X is a [4×3] matrix (4 examples, 3 features each)
- W is a [3×1] matrix (3 features connected to 1 output)
- y is a [4×1] matrix (4 examples, 1 output each)
Forward pass:
- Z = X · W gives a [4×1] matrix of weighted sums
- y_pred = σ(Z) gives a [4×1] matrix of predictions
Backward pass:
- error = y - y_pred gives a [4×1] matrix of errors
- delta = error * σ'(y_pred) gives a [4×1] matrix of deltas
- X.T · delta gives a [3×1] matrix of weight gradients
Weight update:
- W += learning_rate * (X.T · delta) updates all weights simultaneously
The whole process works with matrices, processing all training examples together and updating all weights at once, making the implementation efficient and elegant[10].
This is the essence of backpropagation in a single-layer neural network using matrix operations. The matrix approach scales well to more complex networks with multiple layers, simply by extending the chain rule through the additional layers.