17 min read
cross-entropy loss — from information theory to gradient flow
When training neural networks, optimizing Mean Squared Error on class probabilities causes gradients to vanish near wrong predictions. Switching to cross-entropy loss restores non-zero gradients even when predictions are far from targets. How does an optimal coding metric from 1948 information theory eliminate gradient saturation in deep learning?
By the end you should be able to compute for categorical targets, trace how softmax cancellation prevents gradient saturation, and diagnose overconfidence using decomposition.
Contents
Measuring surprise with entropy
How does Shannon entropy define the theoretical minimum average bit length required to encode samples from distribution ?
Imagine sending a stream of animal classifications for images where every image is guaranteed to be a cat, so the true distribution has , , and . If we assign a fixed naive 2-bit code to each class—say 00 for cat, 01 for dog, and 10 for bird—every message costs exactly bits [1]. But because dog and bird never occur, sending 00 every single time is completely redundant; zero bits of information are conveyed because there is no uncertainty. Even in a more balanced case where cat occurs of the time while dog and bird occur each, allocating equal 2-bit codes to all three classes wastes transmission capacity on frequent events while under-utilizing rare ones.
To minimize the expected message length, information theory assigns variable-length binary codes based on event probability. An outcome occurring with true probability carries an information content—or surprise—measured in bits by . When an event is certain (), its surprise is bits, requiring no code space. When an outcome is less frequent, such as , its surprise is bits, justifying a longer binary code.
Taking the expectation of this optimal code length across all possible outcomes sampled from true distribution establishes the theoretical lower bound on average message length, defined as Shannon entropy.
For our deterministic target distribution , calculating entropy yields bits. Perfect certainty requires zero bits on average to transmit. If were instead a uniform distribution over four classes, , the entropy would reach bits, requiring bits per outcome. Shannon's source coding theorem guarantees that no lossless compression scheme can achieve an average code length shorter than when messages are generated by distribution [1].
This establishes the absolute lower bound when our compression scheme knows the true distribution perfectly. In machine learning, however, the target distribution is hidden, and our model instead outputs an estimated distribution . What average bit penalty do we pay when we construct our coding scheme using estimated model probabilities instead of the true distribution ?
Cross-entropy loss
How does cross-entropy quantify the coding cost incurred when assuming distribution instead of true distribution ?
Consider classifying an image where the true target is cat, represented by target distribution true distribution . Suppose a neural network outputs predicted probabilities predicted distribution , assigning probability to dog and only to the true cat label. If we evaluate this mistake using a naive linear difference like , the metric penalizes all probability deficits uniformly. Under a linear metric, losing probability when moving from to incurs the exact same penalty as dropping from to . Yet these two failures represent fundamentally different model behaviors. Assigning to an event that actually occurs means the network considers the true outcome virtually impossible. In information theory, representing an event assigned probability requires a code word of length [1]. As approaches zero, the required code length approaches infinity, a catastrophe that linear metrics completely fail to capture.
To quantify the expected penalty incurred by assuming estimated distribution predicted distribution instead of true distribution true distribution, we compute the expected code length across all possible outcomes under . This expectation defines the cross-entropy [1]. For a target distribution and model output , the sum over all classes collapses because non-target classes have :
When the model assigns full confidence to the correct class (), the loss vanishes to , indicating that no excess code space is wasted. However, when the model makes a confident wrong prediction like , the target probability yields a cross-entropy loss of . If the model becomes even more confident in its mistake and drops to , the loss doubles to . In the extreme limit as , the loss grows without bound towards infinity:
By penalizing probability deficits logarithmically rather than linearly, cross-entropy loss generates extremely steep gradients precisely when the model is confidently wrong. This property prevents the optimization process from stalling on severe misclassifications.
Evaluating penalizes missing target probability with infinite severity, but does minimizing cross-entropy directly minimize an explicit distance between probability distributions and ?
Forward KL divergence
Why is minimizing cross-entropy equivalent to minimizing when target distribution is fixed?
When optimizing model parameters to classify our cat image with ground-truth target against predicted probabilities , minimizing the cross-entropy loss appears on the surface to depend on the intrinsic structure of . Because cross-entropy measures the total expected code length paid when events from are encoded using , one might worry that loss updates could be confounded by variations in target uncertainty. If cross-entropy combines both target complexity and distribution mismatch into a single scalar value, could gradient descent inadvertently attempt to alter the underlying target distribution's baseline entropy rather than focusing purely on model alignment? [2]
To test whether cross-entropy cleanly separates prediction error from target uncertainty, we decompose the total cross-entropy into two distinct terms: the baseline theoretical minimum code length given by target Shannon entropy , and the extra bit penalty incurred by using model probabilities instead of true probabilities . This excess penalty is called the forward KL divergence .
We write the forward KL divergence by taking the expectation over target distribution of the logarithmic difference between true probabilities and predicted probabilities :
Using standard logarithm rules to expand the log quotient , we split the summation into two separate sums:
We recognize the first term as the negative target entropy , and the second term as the cross-entropy . Substituting these definitions yields the fundamental decomposition formula:
This decomposition makes the distinction between target uncertainty and model miscalibration explicit. For our cat classification target , target entropy is . Even in settings with soft targets where , the target distribution is fixed by the dataset and contains no trainable model parameters . When taking the derivative of cross-entropy with respect to network weights , the target entropy derivative vanishes identically:
Because , updating network parameters along the negative gradient of cross-entropy is mathematically identical to updating parameters along . The optimization algorithm cannot modify the dataset's intrinsic entropy; every parameter update works exclusively to minimize the statistical discrepancy between predicted probabilities and target distribution .
Cross-entropy isolates distribution mismatch mathematically, but how does this log-based objective behave when optimized via gradient descent through continuous logit activations?
Softmax gradient cancellation
Why does combining softmax with cross-entropy produce a linear, non-saturating gradient error vector ?
In our cat classification task, the model converts raw, unnormalized logits into predicted probabilities using the softmax function. Because softmax normalizes every component by the sum of exponentials , evaluating its partial derivatives introduces quotient terms and coupled cross-terms. The derivative of every predicted probability with respect to every input logit yields a complex Jacobian matrix containing terms like and . Navigating this interconnected quotient structure during backpropagation threatens severe computational overhead and potential gradient vanishing.
To compute the loss gradient with respect to logit , we apply the multivariable chain rule across all output probabilities: . Differentiating loss gives . For the softmax output, the Jacobian entry equals when and when . Substituting these components into the chain rule expansion gives:
Notice the algebraic simplification: the denominator in cancels the factor in , while in cancels inside . Simplifying the remaining terms yields . Because is a valid probability distribution, target probabilities sum to (). The expression collapses completely to [1]. In vector form, .
Logit response and gradient error under softmax cross-entropy
As varies, predicted probability follows a smooth sigmoid curve while the logit gradient remains bounded between and without collapsing to zero when is small.
This simplified two-logit model ( varying, held , target ) illustrates how scales smoothly with logit input .
This exact cancellation between the softmax exponential and cross-entropy logarithm leaves a purely linear residual error vector . When the model is confidently wrong ( for target ), the gradient magnitude guarantees strong, constant parameter updates. But what happens if we pair softmax outputs with an alternative loss function like Mean Squared Error instead?
Cross-entropy versus quadratic loss
Why does Mean Squared Error saturate and freeze model learning when evaluating confidently misclassified probabilities?
Suppose our network evaluates a cat image () and outputs a confidently misclassified prediction . Measuring probability error with Mean Squared Error Mean Squared Error loss yields a loss penalty , near its maximum theoretical bound [3]. Intuition suggests that such a severe error should trigger steep gradient updates to correct the model parameters model parameters. Instead, backpropagation stalls completely, leaving the network trapped in its incorrect state.
To understand why parameter updates freeze, trace how the loss gradient flows back through the network to the unnormalized logit logit. Under softmax activation, probability depends on all class logits. The partial derivative of with respect to logit is . By the chain rule, the gradient of any loss function with respect to logit is .
For Mean Squared Error, taking the derivative with respect to predicted probability gives . Substituting this into the chain rule yields the explicit logit derivative:
When the model is confidently wrong (), the factor in the softmax derivative vanishes to zero, driving the entire product . Although the loss derivative indicates a massive prediction error, it is scaled down by the vanishing softmax term . Consequently, the gradient becomes negligible, parameter updates cease, and learning freezes.
Cross-entropy loss avoids this saturation through exact derivative cancellation. The cross-entropy loss derivative with respect to probability is . Multiplying by the softmax derivative gives:
The factor in the denominator of the cross-entropy derivative perfectly cancels the vanishing term in the softmax derivative. Even when , cross-entropy maintains a robust gradient of , ensuring rapid parameter updates until the prediction matches the target.
Cross-entropy eliminates gradient saturation, but its drive to reach zero loss forces target logit , causing model overconfidence.
Label smoothing
How does label smoothing alter target to prevent logit explosion and improve probability calibration?
With a hard one-hot target for classifying our cat image, cross-entropy loss reaches its theoretical minimum of zero only when the predicted probability . Expressed in terms of unnormalized logits logit, predicted probability . For to equal , the logit difference for non-target classes must approach infinity. As gradient descent continuously updates model parameters model parameters, the optimization algorithm relentlessly increases weight magnitudes to drive target logit relative to and . This logit explosion causes extreme probability overconfidence: the network outputs probabilities arbitrarily close to on training samples, destroying probability calibration and making hidden representations rigid and fragile to noise [4].
Label smoothing resolves logit explosion by altering target distribution before computing cross-entropy loss cross-entropy. For total classes and smoothing factor , the original one-hot vector softens into target distribution . The cross-entropy loss reaches its absolute minimum when predicted probability vector perfectly matches , setting and .
To produce prediction under softmax normalization, target logit no longer needs to approach infinity. Instead, the optimal logit difference is finite: . Because the loss function penalizes predictions that overestimate target certainty beyond , gradient descent stops expanding weight magnitudes once logit differences reach this finite threshold.
This completes our throughline from information theory to backpropagation dynamics. Measuring categorical mismatch using cross-entropy loss guarantees non-saturating linear gradients that preserve steep updates when predictions are wrong, avoiding the vanishing gradient failure of quadratic loss. Incorporating label smoothing regularizes optimal logit magnitudes, preventing infinite weight growth while preserving clear margin boundaries between classes.
Transfer set
Put the pieces together
These questions combine mechanisms from more than one section. Work from the causal chain before opening the answer.
- 01
Suppose a 3-class classifier is trained using label smoothing parameter , so the target becomes instead of standard target . How does this altered target change the logit gradient and the optimal logit difference at the loss minimum?
Show answer
Under softmax cross-entropy, the logit gradient vector remains , meaning the residual error signal for class 1 becomes instead of . The gradient vanishes to zero when (), corresponding to a finite optimal logit difference . Because minimizing is equivalent to minimizing when is fixed, parameter updates bring predicted probabilities toward without requiring target logit .
- 02
Consider evaluating a model prediction against target using Mean Squared Error versus cross-entropy. Why does cross-entropy maintain a non-zero gradient magnitude of while Mean Squared Error yields a vanishing logit gradient of approximately ?
Show answer
The cross-entropy loss derivative with respect to predicted probability originates from the logarithmic coding penalty , which grows infinitely as . When multiplied by the softmax Jacobian derivative via the chain rule, the inverse factor cancels the vanishing term, leaving a linear residual error . Under Mean Squared Error, the loss derivative lacks this inverse probability factor, leaving the vanishing factor in the logit derivative intact and stalling gradient flow.
- 03
How does combining the forward KL divergence decomposition with softmax cross-entropy and label smoothing resolve the gradient saturation problem of Mean Squared Error while preventing logit explosion?
Show answer
Decomposing cross-entropy into proves that optimizing cross-entropy directly minimizes distribution mismatch because target entropy is constant. The negative log-likelihood coding penalty yields probability derivative , which cancels the vanishing term in the softmax derivative . This cancellation converts distribution mismatch into a linear, non-saturating logit error signal , restoring steep gradient flow when where Mean Squared Error saturates. Finally, replacing hard target with smoothed target places the minimum at finite probability predictions , bounding the required optimal logit difference to a finite threshold and preventing weight explosion.
References
- [1]Shannon (1948) A Mathematical Theory of CommunicationModel-knowledge reference; verify independently.
- [2]Kullback & Leibler (1951) On Information and SufficiencyModel-knowledge reference; verify independently.
- [3]Golik et al. (2013) Cross-Entropy vs Squared Error Training SamplesModel-knowledge reference; verify independently.
- [4]Szegedy et al. (2016) Rethinking the Inception Architecture for Computer VisionModel-knowledge reference; verify independently.