Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Output Layer Gradient Calculation

Hello! Welcome to the fourth lesson in our "Neural Networks from Scratch" module.

In our last lesson, you successfully implemented a forward pass, allowing our network to make predictions. However, those predictions were based on random, untrained weights. To make our network intelligent, it needs a way to learn from its mistakes. This is where backpropagation comes in.

Today, we'll take the first and most crucial step in understanding this learning process. We will focus on the very last layer of the network and use calculus to figure out how sensitive the network's error is to changes in that layer's weights and biases. This sensitivity is called the gradient, and it's the key to training.

This lesson directly addresses the learning outcome: Derive the gradient of the loss function with respect to the weights and biases of the output layer.

1. From Prediction to Error: The Loss Function

Before we can correct the network's errors, we need to quantify them. We do this using a loss function (also called a cost function). This function compares the network's predictions () with the true target values () and outputs a single number representing the total error.

A common loss function for regression tasks is the Mean Squared Error (MSE):

For a single training example, this simplifies to .

Our goal is to adjust the network's parameters (weights and biases ) to minimize this cost. The most common algorithm for this is gradient descent. The idea is to calculate the gradient of the cost function with respect to each parameter and take a small step in the opposite direction.

The update rule for any weight is:

Here, is the learning rate, and is the gradient we need to find.

The following video provides an excellent visual intuition for gradient descent and introduces the backpropagation process we'll be exploring.

Gradient Descent & Backpropagation Explained - Neural Networks from Scratch Part 2

This video from Adarsh Menon introduces the cost function and explains the core idea behind gradient descent using a simple 2D analogy. It sets the stage for why we need to calculate gradients.

Watch from the beginning (0:57) to 6:52. The first part (until 3:10) introduces the cost function and the parameter update rule. The second part (from 3:21) uses a clear visual to explain how the gradient's sign and magnitude guide the updates toward the minimum cost.

2. The Chain Rule: Deconstructing the Gradient

Now for the main task: calculating and for the final layer, which we'll call layer .

To do this, we must use the chain rule from calculus. Think of the network as a chain of functions. The cost depends on the final activation , which depends on the pre-activation , which in turn depends on the weights and biases .

Neural Network Architecture for Backpropagation
This diagram shows the connections from the previous layer's activations (\(h\)) to the pre-activations (\(z\)) and final activations (\(\hat{y}\)) of the output layer, which are then used to compute the loss \(L\).

This chain of dependencies can be written as:

The chain rule allows us to compute the overall derivative by multiplying the derivatives of each link in the chain.

A Simple Case: One Neuron Per Layer

To build intuition, let's start with the simplest possible network, where each layer has only one neuron. The 3Blue1Brown video and accompanying article are unparalleled for explaining this.

Backpropagation calculus | Deep Learning Chapter 4

This classic video from 3Blue1Brown masterfully breaks down the backpropagation calculus for the simplest case. It visually demonstrates how a change in a weight propagates through the network to affect the final cost.

Watch from 0:39 to 6:06. Pay close attention to how the derivative of the cost with respect to the last weight, ∂C/∂w(L), is broken down into three separate, easier-to-calculate derivatives using the chain rule. The video then shows the nearly identical derivation for the bias.

Let's formalize what you just saw. For a single training example, the cost is . The relationships are:

  1. , where is the activation function (e.g., sigmoid).

Gradient with respect to Weight :
Using the chain rule, we decompose the derivative:

Let's compute each term:

  • (How much does the cost change for a small change in the final activation?)
  • (How much does the activation change for a small change in its input? This is just the derivative of the activation function.)
  • (How much does the pre-activation change for a small change in the weight? From the formula for , we can see it's the activation of the previous neuron.)

Putting it all together:

Gradient with respect to Bias :
The derivation is almost identical. The first two terms of the chain rule are the same. Only the last term changes:

Therefore:

The 3Blue1Brown article provides these derivations in text form, which can be a useful reference to solidify your understanding.

Backpropagation calculus - 3Blue1Brown

This article is the text version of the video you just watched. It's a great way to review the equations at your own pace.

Read the sections 'Computing The First Derivative' and 'The Bias'. These sections walk through the exact same logic as the video, deriving the gradients for the weight and bias of the final layer.

3. Generalizing to Multiple Neurons (Vectorization)

The real power of neural networks comes from having multiple neurons per layer. While this introduces more indices, the core logic of the chain rule remains the same. The key is to switch from thinking about individual numbers to thinking in terms of vectors and matrices. Your background in linear algebra will be very helpful here.

Let's redefine our terms in vector form for a batch of N samples:

  • : Activations from the previous layer, shape (N, n_neurons_prev).
  • : Weight matrix of the output layer, shape (n_neurons_prev, n_neurons_out).
  • : Bias vector of the output layer, shape (1, n_neurons_out).
  • : Pre-activations, shape (N, n_neurons_out).
  • : Final activations (predictions ), shape (N, n_neurons_out).
  • : True labels, shape (N, n_neurons_out).
  • : Cost, a scalar.

Our goal is to find the gradient matrices (shape (n_neurons_prev, n_neurons_out)) and (shape (1, n_neurons_out)).

The following video walks through these derivations with a keen eye on the matrix dimensions, which is crucial for a correct implementation.

Gradient Descent & Backpropagation Explained - Neural Networks from Scratch Part 2

Let's return to the video by Adarsh Menon. This section derives the gradients for the output layer in a multi-neuron setting, explaining the necessary matrix transpositions to ensure the shapes align correctly.

Watch from 8:45 to 13:10. Focus on how the chain rule is applied to find ∂C/∂W2 and ∂C/∂B2 (their notation for the output layer). Pay special attention to the discussion around 11:02, where he explains why a1 needs to be transposed to get the correct shape for the weight gradient.

As the video explained, we can define an "error" term for the output layer, often denoted by delta (). This term combines the first two parts of our chain rule:

where denotes element-wise multiplication.

For MSE, . So, becomes a matrix of shape (N, n_neurons_out).

Once we have , the gradients are straightforward matrix operations:

  • Gradient with respect to Weights : The shapes are (n_neurons_prev, N) dot (N, n_neurons_out), resulting in the correct gradient shape (n_neurons_prev, n_neurons_out).
  • Gradient with respect to Biases : We sum the error contributions from all samples in the batch, resulting in a vector of shape (1, n_neurons_out).

For a more formal and compact reference, the Stanford CS224n notes provide these vectorized identities.

Computing Neural Network Gradients

These course notes provide a concise, mathematical summary of vectorized gradient computations. It's a dense but powerful resource.

Skim the 'Example: 1-Layer Neural Network' section. Their notation is slightly different (U for output weights, b2 for output bias), but the logic is the same. Notice how they first compute the error signal δ1 = ∂J/∂θ and then use it to find the gradients ∂J/∂U and ∂J/∂b2. This directly maps to our derivation.

A very common and important special case is a classification task using a Softmax output and Cross-Entropy loss. In this specific combination, the calculation for simplifies beautifully to just . This is a widely used shortcut in practice.

Conclusion

Excellent work! You've tackled the most conceptually important part of backpropagation. By understanding how to calculate the gradients for the final layer, you have the starting point for the entire learning algorithm.

Key Takeaways:

  • The goal of training is to minimize a loss function using an algorithm like gradient descent.
  • The core of gradient descent is calculating the gradient () of the loss with respect to each parameter.
  • We use the chain rule to break this complex derivative down into a product of simpler derivatives, following the path of computation backward from the loss.
  • For the output layer , the gradients are:
  • Expressing these operations in vectorized form is essential for efficient implementation.

In the next lesson, we will see how the error signal we just computed, , is used to continue the process. We will propagate this error backward one more step to derive the gradient of the loss function with respect to the weights and biases of a hidden layer.

Can't find a good explanation? Sign up and we'll make it for you

Sign up