Introduction

Welcome back to "Training Neural Networks: The Backpropagation Algorithm"! You've made excellent progress so far, having learned about loss functions in our first lesson and gradient descent in our second. Today, we're diving into the heart of neural network training: backpropagation.

In our previous lesson, we explored how gradient descent updates weights by moving in the direction opposite to the gradient of the loss function. But we left an important question unanswered: How do we actually calculate these gradients in a neural network with multiple layers and thousands or even millions of parameters?

That's where backpropagation comes in. Backpropagation (short for "backward propagation of errors") is an efficient algorithm for computing these gradients. Today, we'll focus specifically on implementing the backward pass for a single dense layer, which will form the building block for training complete neural networks.

By the end of this lesson, you'll understand how to:

  • Calculate derivatives for different activation functions.
  • Store necessary values during the forward pass.
  • Implement the backward pass to calculate gradients.
  • Connect these gradients to the gradient descent algorithm we learned previously.

Let's embark on this crucial step in our neural network journey!

Understanding the Chain Rule for Backpropagation
Activation Functions and Their Derivatives
The DenseLayer Class Structure
The Forward Pass: Setting Up for Backpropagation
The Backward Pass: Calculating Gradients
Backpropagation in Action: A Practical Example

Let's now see how our backpropagation implementation works in practice with a simple example:

# Create a single layer: 2 inputs, 3 neurons, sigmoid activation
layer <- DenseLayer$new(n_inputs = 2, n_neurons = 3, activation_fn_name = 'sigmoid')

X_sample <- matrix(c(0.5, -0.2), nrow = 1, ncol = 2)  # 1 sample, 2 features
cat("Input X:\n")
print(X_sample)

# Forward pass
layer_output <- layer$forward(X_sample)
cat("Layer output (after sigmoid):\n")
print(layer_output)

# Assume a dummy gradient from a hypothetical next layer or loss function
# This is d(Loss)/d(layer_output)
# Shape must match layer_output: (n_samples, n_neurons_in_layer)
dummy_d_loss_wrt_layer_output <- matrix(c(0.1, -0.2, 0.05), nrow = 1, ncol = 3)
cat("Dummy dL/d(layer_output):\n")
print(dummy_d_loss_wrt_layer_output)

# Backward pass
d_loss_wrt_input <- layer$backward(dummy_d_loss_wrt_layer_output)

cat("\nCalculated Gradients:\n")
cat("  dL/d_weights (shape", dim(layer$d_weights), "):\n")
print(layer$d_weights)
cat("  dL/d_biases (shape", dim(layer$d_biases), "):\n")
print(layer$d_biases)
cat("  dL/d_inputs (to pass to prev layer) (shape", dim(d_loss_wrt_input), "):\n")
print(d_loss_wrt_input)

This example:

  1. Creates a single DenseLayer with 2 inputs and 3 neurons.
  2. Performs a forward pass with a sample input.
  3. Simulates receiving gradients from the next layer using a dummy gradient.
  4. Performs a backward pass using this gradient.
  5. Prints the computed gradients for weights, biases, and inputs.
Output Discussion

When we run this code, we get the following output:

Input X:
     [,1] [,2]
[1,]  0.5 -0.2

Layer output (after sigmoid):
          [,1]      [,2]      [,3]
[1,] 0.5000116 0.4984150 0.5013022

Dummy dL/d(layer_output):
     [,1] [,2] [,3]
[1,]  0.1 -0.2 0.05

Calculated Gradients:
  dL/d_weights (shape 2 3 ):
           [,1]        [,2]        [,3]
[1,] 0.01250000 -0.02499975  0.00624996
[2,] -0.00500000  0.00999990 -0.00249998

  dL/d_biases (shape 1 3 ):
           [,1]        [,2]        [,3]
[1,] 0.02500000 -0.04999950  0.01249992

  dL/d_inputs (to pass to prev layer) (shape 1 2 ):
            [,1]        [,2]
[1,] 0.0006935802 -0.0001824598

Looking at this output:

  1. Our input is a single sample with two features: [0.5, -0.2].
  2. The forward pass produces outputs around 0.5 (since our weights are initialized close to zero, the sigmoid of values near zero is about 0.5).
  3. We provide a dummy gradient [0.1, -0.2, 0.05] representing how the loss would change if each output neuron's value changed slightly.
  4. The backward pass calculates:
    • Gradients for each weight (d_weights).
    • Gradients for each bias (d_biases).
    • Gradients to pass to the previous layer (d_loss_wrt_input).

This example demonstrates the full cycle of forward and backward passes for a single layer. In a complete neural network, we would perform this process for each layer, starting from the output and working backward (hence the name backpropagation).

Conclusion and Next Steps

Congratulations! You've now mastered one of the most fundamental algorithms in deep learning: backpropagation for a single dense layer. The chain rule has empowered us to efficiently calculate gradients through a network, while our careful implementation of activation functions and their derivatives has given us the building blocks for neural network learning. Our layer's forward pass not only computes outputs but also strategically caches values needed for the backward pass, which then efficiently computes the gradients that power the learning process.

In our upcoming practice exercises, you'll gain hands-on experience with backpropagation and see how these gradients drive the learning process in neural networks. After solidifying these concepts through practice, we'll expand this foundation to implement backpropagation for entire multi-layer networks and explore more advanced optimization techniques to enhance our models' performance.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal