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

Now, let's look at the structure of our DenseLayer class. This class encapsulates both the forward pass (which we've seen in previous lessons) and the backward pass (which we're focusing on today).

const math = require('mathjs');
const { sigmoid, relu, linear, sigmoidDerivative, reluDerivative, linearDerivative } = require('./activations');
const { randomScaledInit, xavierNormalInit, heUniformInit } = require('./normalization');

class DenseLayer {
    constructor(
        nInputs,
        nNeurons,
        activationFnName = 'sigmoid',
        weightInitStrategy = 'random_scaled',
        weightInitScale = 0.01
    ) {
        this.nInputs = nInputs;
        this.nNeurons = nNeurons;
        this.activationFnName = activationFnName;
        this.weightInitStrategy = weightInitStrategy;
        this.weightInitScale = weightInitScale;

        if (weightInitStrategy === 'random_scaled') {
            this.weights = randomScaledInit(nInputs, nNeurons, weightInitScale);
        } else if (weightInitStrategy === 'xavier_normal') {
            this.weights = xavierNormalInit(nInputs, nNeurons);
        } else if (weightInitStrategy === 'he_uniform') {
            this.weights = heUniformInit(nInputs, nNeurons);
        } else {
            throw new Error(`Unsupported weight initialization strategy: ${weightInitStrategy}`);
        }

        // biases: shape [1, nNeurons] for broadcasting
        this.biases = math.zeros(1, nNeurons);

        // Set activation function and its derivative
        if (activationFnName === 'sigmoid') {
            this.activationFn = sigmoid;
            this.activationDerivativeFn = sigmoidDerivative;
        } else if (activationFnName === 'relu') {
            this.activationFn = relu;
            this.activationDerivativeFn = reluDerivative;
        } else if (activationFnName === 'linear') {
            this.activationFn = linear;
            this.activationDerivativeFn = linearDerivative;
        } else {
            throw new Error(`Unsupported activation: ${activationFnName}`);
        }

        // Variables to store values needed for backpropagation
        this.inputs = null;
        this.z = null;
        this.output = null;
        this.dWeights = null;
        this.dBiases = null;
    }
}

The key added components to notice:

  1. Activation Derivatives: We store not only the chosen activationFn but also its activationDerivativeFn.
  2. Caching Variables:
    • this.inputs will store the inputs to the layer;
    • this.z will store the pre-activation outputs;
    • this.output will store the post-activation outputs;
    • this.dWeights and this.dBiases will store the gradients of weights and biases.

This caching of intermediate values is crucial for backpropagation. We need to know these values during the backward pass to correctly compute the gradients.

The Forward Pass: Setting Up for Backpropagation

The forward pass not only computes the layer's output but also stores the necessary values for the backward pass. Let's examine the forward method implementation:

forward(inputs) {
    // inputs: 2D array (nSamples x nInputs)
    this.inputs = inputs;
    this.z = math.add(math.multiply(inputs, this.weights), this.biases); // Pre-activation output
    this.output = this.activationFn(this.z);
    return this.output;
}

This method:

  1. Stores the input values in this.inputs
  2. Calculates and stores the pre-activation outputs this.z (the weighted sum plus bias)
  3. Applies the activation function and stores the results in this.output
  4. Returns the output for use in subsequent layers

The key insight here is that we're caching all the intermediate values we'll need for the backward pass. This is essential for efficient computation of gradients during backpropagation.

As you may recall from our previous lessons, this is how information flows forward through the network. Now, let's see how errors flow backward during the backpropagation process.

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:

// --- Example Usage ---

if (require.main === module){
    // Single layer: 2 inputs, 3 neurons, sigmoid activation
    const layer = new DenseLayer(2, 3, 'sigmoid');

    const X_sample = math.matrix([[0.5, -0.2]]); // 1 sample, 2 features
    console.log("Input X:", X_sample.toString());

    // Forward pass
    const layerOutput = layer.forward(X_sample);
    console.log("Layer output (after sigmoid):", layerOutput.toString());

    // Assume a dummy gradient from a hypothetical next layer or loss function
    // This is d(Loss)/d(layer_output)
    // Shape must match layerOutput: (nSamples x nNeurons)
    const dummyDLossWrtLayerOutput = math.matrix([[0.1, -0.2, 0.05]]);
    console.log("Dummy dL/d(layer_output):", dummyDLossWrtLayerOutput.toString());

    // Backward pass
    const dLossWrtInput = layer.backward(dummyDLossWrtLayerOutput);

    console.log("\nCalculated Gradients:");
    console.log("  dL/d_weights:", layer.dWeights.toString());
    console.log("  dL/d_biases:", layer.dBiases.toString());
    console.log("  dL/d_inputs (to pass to prev layer):", dLossWrtInput.toString());
}

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 output similar to the following:

Input X: [ [ 0.5, -0.2 ] ]
Layer output (after sigmoid): [ [ 0.5001, 0.4984, 0.5013 ] ]
Dummy dL/d(layer_output): [ [ 0.1, -0.2, 0.05 ] ]

Calculated Gradients:
  dL/d_weights: [ [ 0.0125, -0.0250, 0.0062 ], [ -0.0050, 0.0100, -0.0025 ] ]
  dL/d_biases: [ [ 0.0250, -0.0500, 0.0125 ] ]
  dL/d_inputs (to pass to prev layer): [ [ 0.0007, -0.0002 ] ]

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 (dWeights)
    • Gradients for each bias (dBiases)
    • Gradients to pass to the previous layer (dLossWrtInput)

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