Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Gradients of Loss Functions

Recommended resources

Hello! Welcome to the next step in our journey through vector calculus for deep learning.

In our last lesson, we established the core mechanism of backpropagation: the vector chain rule. We saw that the gradient of a composite function is the product of the Jacobians of its constituent parts, applied in reverse order. This gave us a powerful, general tool for understanding how to differentiate a neural network.

Today, we will apply this tool to a crucial part of any network: the loss function. Our goal is to derive the gradient of the network's final output—the logits—with respect to the loss. This gradient is the initial "error signal" that kicks off the entire backpropagation process. We will derive these gradients for the two most common scenarios in deep learning: Mean Squared Error for regression tasks and Categorical Cross-Entropy for classification tasks. You'll see that in both cases, the final result is surprisingly simple and intuitive, a testament to the elegant design of these standard components.

1. Gradient of Mean Squared Error Loss

Let's begin with the simpler case: regression. In a typical regression problem, a network produces a vector of predictions, which we can call . For a regression task, these outputs are often the raw outputs of the final linear layer, which we've been calling the logits. The Mean Squared Error (MSE) loss measures the squared Euclidean distance between these predictions and the true target values .

Let . The MSE loss is defined as:

For simplicity in differentiation, we often work with the sum of squared errors, omitting the constant and sometimes adding a factor of to cancel the exponent after differentiation. Let's use . Our goal is to find the gradient of this scalar loss with respect to the prediction vector , which is .

We can compute this by finding the partial derivative with respect to each component :

Due to the linearity of the derivative, we can move it inside the sum. The derivative will be zero for all terms where . The only term that survives is the one where :

Since this holds for every component , the full gradient vector is:

The result is simply the error vector—the difference between the predicted and true values. This is a wonderfully intuitive outcome. The gradient points in the direction of the error, telling each output unit how far and in which direction it needs to move to reduce the loss. This vector is the initial upstream gradient that is fed into the final layer of the network for backpropagation.


2. Gradient of Categorical Cross-Entropy Loss

Now for the more involved, and perhaps more satisfying, case: multi-class classification. Here, the standard setup involves a final linear layer producing logits , a softmax activation function to convert logits into probabilities , and a Categorical Cross-Entropy loss function to measure the discrepancy between the predicted probabilities and the one-hot encoded true labels .

The pipeline is:

  1. Logits:
  2. Softmax:
  3. Loss:

Our goal is to compute the gradient of the loss with respect to the logits, . Using the chain rule, we can decompose this as:

This involves the product of the gradient of the loss with respect to the softmax outputs (a row vector) and the Jacobian of the softmax function. Let's derive each part separately.

The Derivative of Softmax and Cross-Entropy

The following article provides a clear, step-by-step derivation for both the softmax Jacobian and the gradient of the cross-entropy loss. We'll use it to build our argument.

The Softmax function and its derivative - Eli Bendersky's website

This article by Eli Bendersky offers a first-principles derivation that aligns well with our goal of understanding the mechanics.

First, read the section Derivative of softmax. This part carefully works through the quotient rule to find the partial derivatives \frac{\partial \hat{y}_i}{\partial z_j} for both the diagonal case (i=j) and the off-diagonal case (i \neq j). This gives us all the components of the softmax Jacobian, \frac{\partial \mathbf{\hat{y}}}{\partial \mathbf{z}}. Next, jump to the section Softmax and cross-entropy loss and read up to the equation for the Jacobian of xent. This section derives the gradient of the cross-entropy loss with respect to its inputs (the probabilities \mathbf{\hat{y}}), which gives us the term \frac{\partial L}{\partial \mathbf{\hat{y}}}.

Let's summarize the key results from the reading:

  1. Softmax Jacobian (): The partial derivative of the -th softmax output with respect to the -th logit is:

    This can be concisely written using the Kronecker delta, , as .

  2. Cross-Entropy Gradient (): For a one-hot true label vector where for the correct class , the loss simplifies to . The partial derivative with respect to an arbitrary output probability is:

    This is because is only non-zero (and equal to 1) for the correct class, so the derivative is non-zero only for that component.

Combining the Derivatives

Now we combine these two parts using the chain rule. The -th component of our target gradient is:

Let's plug in our results:

This sum looks intimidating, but a beautiful cancellation occurs. Let's expand it by considering the two cases for the softmax Jacobian.

We split the sum into the term where and all terms where :

Substitute the corresponding Jacobian elements:

Now, simplify each part:

  • First part:
  • Second part:

Combine them:

The term in the parentheses is . Since is a one-hot vector, the sum of its elements is exactly 1.

This stunningly simple result holds for every component . Therefore, the gradient vector is:

This is a cornerstone result in deep learning. The complex derivatives involving exponentials and logarithms completely cancel out, leaving the same intuitive form as the MSE gradient: prediction minus true value.

This diagram illustrates the elegant simplification we just derived. The gradient of the Cross-Entropy Loss with respect to the logits (z) collapses to the simple difference between the predicted probabilities (ŷ) and the true labels (y).

The following video provides an alternative walk-through of this exact derivation. Watching it can help solidify the algebraic steps.

Backpropagation for Softmax and Multi-Class Classification | Complete Mathematical Derivation

This video provides a focused mathematical derivation of the gradient of cross-entropy loss w.r.t logits.

The key derivation happens in two parts. First, watch how the Jacobian of the softmax is derived by considering the case where indices are different (i \neq j) from this segment, and then where indices are the same (i = j) from this part. Finally, watch the conclusion from here, where the derivatives of the loss and the softmax are combined via the chain rule to arrive at the final a_i - y_i result.

The fact that softmax and cross-entropy are such a compatible pair is no accident. This pairing provides a stable and meaningful gradient for training classification models. The error signal directly tells the model how to adjust its logits: if the predicted probability for the correct class is too low, the gradient will be positive for that logit, pushing it higher.


Conclusion

In this lesson, we applied the chain rule to derive the initial gradients for the backpropagation algorithm. We found that for two of the most common setups in deep learning, the result is remarkably consistent and intuitive.

Key Takeaways:

  • The gradient of the Mean Squared Error loss with respect to the network's predictions is simply the error vector: .
  • The gradient of the Categorical Cross-Entropy loss combined with a Softmax activation, taken with respect to the pre-activation logits , also simplifies to the error vector: .
  • This "gradient collapse" is a key reason for the prevalence of the Softmax/Cross-Entropy pair in classification, as it provides a numerically stable and computationally efficient starting point for backpropagation.

We've now seen how to compute the Jacobian for intermediate layers and the initial gradient from the loss function. In the next lesson, we will tie these concepts together by deriving the Jacobian of the softmax function itself, solidifying the derivation we used today and preparing you to trace gradients through any part of a network.