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

Gradients of MSE and Cross-Entropy Losses

Introduction

In our previous lesson, we established the softmax function as the essential tool for converting the raw, unbounded logits from a neural network's final layer into a valid probability distribution over multiple classes. We now have a vector of predicted probabilities, . The next logical step is to quantify how "wrong" these predictions are compared to the actual ground truth. This is the role of a loss function, also known as a cost or objective function.

This lesson focuses on deriving the gradients of the two most fundamental loss functions in neural networks: Mean Squared Error (MSE) for regression tasks and Cross-Entropy for classification. Our goal is not just to define these functions, but to compute their derivatives with respect to the network's final logits, . This specific gradient, , is the linchpin of the entire training process. It represents the initial error signal that we will propagate backward through the network to update all its parameters—a process we will fully dissect in our next lesson on backpropagation.

Mean Squared Error (MSE) for Regression

Let's begin with the "Classical to Modern Bridge." In classical linear regression, where the goal is to predict a continuous value, the Mean Squared Error is the standard loss function. It measures the average of the squared differences between the predicted values and the actual values. This same principle applies directly to neural networks designed for regression tasks, such as predicting the price of a house or the trajectory of an object.

For a regression network, the output layer typically has a linear activation function (or no activation at all), meaning the output prediction is simply the logit . For a single prediction and a single true label , the loss is:

The factor of is a common convention that simplifies the derivative without changing the location of the minimum.

Now, consider a network with output neurons, predicting a vector of continuous values. The prediction vector is and the true label vector is . The MSE loss is the sum of squared errors for each component:

Our task is to find the gradient of this loss with respect to the logit vector , which is . To do this, we can compute the partial derivative with respect to an arbitrary logit .

Question: When you take the partial derivative , which term in the summation is the only one that does not evaluate to zero? Using this insight, what is the resulting partial derivative?

Answer The derivative of a sum is the sum of the derivatives. When differentiating with respect to $z_j$, all terms $(z_k - y_k)^2$ where $k \neq j$ are treated as constants, and their derivatives are zero. The only term that survives is the one where $k=j$.

Applying the power rule and chain rule to this term gives:

This gives us a remarkably simple and intuitive result. The gradient of the MSE loss with respect to a single logit is simply the error for that output, . Therefore, the gradient vector for all logits is:

The error signal that needs to be propagated backward is simply the vector of differences between our predictions and the true values.

The article below formally defines various loss functions and derives this exact gradient for linear regression, which is identical to our neural network regression case.

A Tutorial on Regression Analysis: From Linear Models to Deep ...

This document provides formal definitions for loss functions and their use in parameter estimation.

Please focus on these parts: First, read the section on Loss Functions to understand their general role. Start at the definition of loss and review the table of common metrics. Next, read the definition of the MSE loss for linear regression in the section Loss Function. Finally, study the Gradient Computation section to see the formal derivation, which matches our result.

Cross-Entropy Loss for Classification

For classification tasks, where the network output is a probability distribution , MSE is generally not the best choice. Instead, we use the cross-entropy loss. From an information theory perspective, this loss measures the dissimilarity between the predicted probability distribution and the true distribution (which is a one-hot vector).

The multi-class cross-entropy loss for a single training example is defined as:

Where is 1 for the true class and 0 otherwise, and is the softmax probability for class .

Because is one-hot, this sum simplifies dramatically. If the correct class is , then and all other , so the loss becomes:

To minimize this loss, the network must maximize , which is equivalent to making the predicted probability of the correct class, , as close to 1 as possible. This aligns perfectly with the goal of classification.

Diagram showing the flow from raw scores (logits, denoted S) through the Softmax function to produce probabilities (f(s)i), which are then used in the Cross-Entropy Loss calculation (CE).

Deriving the Gradient of Cross-Entropy with Softmax

Our goal is to find the gradient . This is more involved than the MSE case because the loss is a function of the probabilities , which are themselves a function of the logits .

Question: Given the functional composition , what mathematical rule must we invoke to find the derivative of the loss with respect to the logits ?

Answer We must use the **multivariable chain rule**. The influence of a single logit $z_j$ on the final loss $\mathcal{L}$ is channeled through *all* the probabilities $p_1, p_2, ..., p_K$, because a change in one logit affects all outputs of the softmax function.

The chain rule states:

This expression elegantly breaks our problem into two parts we already know how to solve:

  1. : The derivative of the cross-entropy loss with respect to an output probability.
  2. : The derivative of the softmax function, which we derived in the last lesson. This is an element of the softmax Jacobian matrix.

Let's compute these parts and assemble the result.

Part 1: Derivative of Loss w.r.t. Probability
For , the derivative with respect to a single probability is:

Part 2: Derivative of Softmax (from last lesson)
We have two cases for :

  • Case :
  • Case :

Part 3: Assembling with the Chain Rule
We expand the sum from the chain rule, splitting it into the term and the sum over all terms:

Now, substitute the derivatives we found:

Let's simplify this expression step-by-step:

  1. Cancel terms in each part:
  2. Distribute and factor out of the sum:
  3. Factor out from the last two terms:
  4. Recognize that since is one-hot, the term in the parenthesis is simply the sum of all elements of , which is .

This yields an astonishingly simple and elegant result. The gradient of the combined softmax and cross-entropy loss with respect to a logit is simply the difference between the predicted probability and the true label . The full gradient vector is:

The following video provides a complete, step-by-step walkthrough of this exact derivation. Watching it will help solidify your understanding of each algebraic manipulation.

Back propagation through Cross Entropy and Softmax

This video, "Back propagation through Cross Entropy and Softmax" from MLDawn, meticulously derives the gradient we just computed from first principles.

Please watch from 17:48 to 52:22. The presenter systematically applies the sum rule, constant rule, and chain rule, recalls the softmax derivative, and combines everything to arrive at the final p - y result. This detailed breakdown is excellent for reinforcing the mathematical steps.

A Unified View: Prediction - Label

Let's take a step back and compare the gradients we've derived.

  • Regression with MSE:
  • Classification with Softmax + Cross-Entropy:

In both cases, the gradient has the same intuitive structure: . For regression, the prediction is the logit vector . For classification, the prediction is the probability vector . This is a powerful and unifying concept in the design of neural networks and loss functions. The error signal that initiates backpropagation is a direct measure of how wrong the network's prediction was.

An example of the gradient vector `p - y`. The true class is 2 (so y = [0, 0, 1, 0, 0]). The gradient for class 2 is p₂ - 1 (a negative value, pulling its probability towards 1), while the gradients for all other classes are pᵢ - 0 = pᵢ (positive values, pushing their probabilities towards 0).

Conclusion

In this lesson, we have derived the crucial starting gradients for the backpropagation algorithm. We have seen how to measure the error of a neural network's output and, more importantly, how to calculate the sensitivity of that error with respect to the pre-activation logits.

Key Takeaways:

  • Loss Functions Quantify Error: MSE is the standard for regression, while Cross-Entropy is the standard for classification.
  • Gradient for MSE: For a regression network with linear outputs, the gradient of the MSE loss with respect to the logits is simply .
  • Gradient for Cross-Entropy: The combination of a Softmax output layer and a Cross-Entropy loss function results in a beautifully simple gradient with respect to the logits: .
  • Unified Pattern: Both scenarios result in a gradient of the form prediction - label, providing a powerful and intuitive starting point for training.

Preview of the Next Lesson:

With the "head" of the gradient, , now fully derived, we are ready to tackle the main event: deriving the full backpropagation algorithm. We will apply the chain rule recursively to propagate this initial error signal backward through the network's layers, computing the gradients with respect to every weight and bias, and . This will give us everything we need to finally start training a neural network.

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

Sign up