Skip to content
mlmentorship

Cross-entropy and softmax

Derive categorical negative log-likelihood and its logit gradient, then change target smoothing and temperature without losing the normalization contract.

Published · 8 min read ·Core ·Foundation

Visual quick review

Explain why cross-entropy still supplies a large logit gradient when the true class has near-zero predicted probability, while squared error through a saturating probability output can supply almost none.

Learning objective

Predictions share normalization; targets and temperature change the corrective signal

Predictions share normalization; targets and temperature change the corrective signalNormalize class predictions together. Targets specify which outcomes to reward. Smoothing spreads target mass, reducing extreme pushes. Temperature changes predictions and rescales the logit gradient. The separate binary example shows cross-entropy correcting confident errors while squared error's sigmoid gate nearly closes. These are specified toy settings.Predictions and targets each keeptotal mass oneHard target; original temperaturePrediction sharesC0: 0.010C1: 0.490C2: 0.500Target sharesC0: 1.000C1: 0.000C2: 0.000Target-class logit gradient: -0.990Smoothed target; same predictionsPrediction sharesC0: 0.010C1: 0.490C2: 0.500Target sharesC0: 0.933C1: 0.033C2: 0.033Target-class logit gradient: -0.923Warmer predictions; hard targetPrediction sharesC0: 0.066C1: 0.464C2: 0.469Target sharesC0: 1.000C1: 0.000C2: 0.000Target-class logit gradient: -0.467Temperature also divides the logitgradient, not only the logits.Separate binary example: a confidentwrong predictionWrong confidence passes throughdifferent loss routesCross-entropy cancellation preservessensitivityAbsolute logit gradient 0.99Squared error includes the smallsigmoid gateAbsolute logit gradient 0.0196
Read it this way: Normalize class predictions together. Targets specify which outcomes to reward. Smoothing spreads target mass, reducing extreme pushes. Temperature changes predictions and rescales the logit gradient. The separate binary example shows cross-entropy correcting confident errors while squared error's sigmoid gate nearly closes. These are specified toy settings. At predicted probability 0.01 for a positive label, which gradient remains large?
Full explanation 8 min read
Reading depth

Summary

Categorical cross-entropy is negative log-likelihood when one class label is observed from a predicted categorical distribution. Softmax maps finite logits to that distribution; differentiating their composition gives a prediction-minus-target logit gradient. Stable evaluation comes from shifted log-normalization, not from the gradient formula alone.

The math, briefly

Let be one logit vector and its observed class index. Define . Then

The derivative of the log-normalizer is . The observed-class term contributes only at index . For logits and class zero, , loss is , and gradient is .

The diagram instead uses a binary true-class probability . Cross-entropy’s true-logit gradient is . Half squared error on the sigmoid probability introduces another derivative factor, giving magnitude .

Learning objective

Cross-entropy and squared-error logit gradients as true-class probability changes

Cross-entropy and squared-error logit gradients as true-class probability changes An original plot for a binary output with true label one. The horizontal axis is true-class probability q from zero to one, and the vertical axis is absolute gradient with respect to its logit. Cross-entropy is a solid straight line with magnitude one minus q, so at q equals 0.01 its gradient is 0.99. Half squared error on the probability is a dashed low curve with magnitude q times one minus q squared, so at q equals 0.01 its gradient is about 0.0098. The extra sigmoid derivative makes squared error nearly stop when the prediction is confidently wrong. CE: |g| = 0.99 MSE: |g| ≈ 0.0098 cross-entropy |g| = 1 − q (solid) probability-MSE (dashed) |g| = q(1 − q)² 1.0 0.5 0 0 0.25 0.50 0.75 1.0 logit-gradient magnitude |g| true-class probability q · true label y = 1
Read it this way: move left toward confident error. Cross-entropy's gradient approaches minus one. Probability-MSE includes the saturating sigmoid derivative, so its magnitude approaches zero. The dashed curve describes this binary comparison, not every possible squared-error model.
Check: Why is the cross-entropy logit gradient large where the probability-squared-error gradient nearly vanishes?
Reference drawing

Learning objective

Predictions share normalization; targets and temperature change the corrective signal

Predictions share normalization; targets and temperature change the corrective signalNormalize class predictions together. Targets specify which outcomes to reward. Smoothing spreads target mass, reducing extreme pushes. Temperature changes predictions and rescales the logit gradient. The separate binary example shows cross-entropy correcting confident errors while squared error's sigmoid gate nearly closes. These are specified toy settings.Predictions and targets each keeptotal mass oneHard target; original temperaturePrediction sharesC0: 0.010C1: 0.490C2: 0.500Target sharesC0: 1.000C1: 0.000C2: 0.000Target-class logit gradient: -0.990Smoothed target; same predictionsPrediction sharesC0: 0.010C1: 0.490C2: 0.500Target sharesC0: 0.933C1: 0.033C2: 0.033Target-class logit gradient: -0.923Warmer predictions; hard targetPrediction sharesC0: 0.066C1: 0.464C2: 0.469Target sharesC0: 1.000C1: 0.000C2: 0.000Target-class logit gradient: -0.467Temperature also divides the logitgradient, not only the logits.Separate binary example: a confidentwrong predictionWrong confidence passes throughdifferent loss routesCross-entropy cancellation preservessensitivityAbsolute logit gradient 0.99Squared error includes the smallsigmoid gateAbsolute logit gradient 0.0196
Derivation
Cross-entropy and squared-error logit gradients as true-class probability changes An original plot for a binary output with true label one. The horizontal axis is true-class probability q from zero to one, and the vertical axis is absolute gradient with respect to its logit. Cross-entropy is a solid straight line with magnitude one minus q, so at q equals 0.01 its gradient is 0.99. Half squared error on the probability is a dashed low curve with magnitude q times one minus q squared, so at q equals 0.01 its gradient is about 0.0098. The extra sigmoid derivative makes squared error nearly stop when the prediction is confidently wrong. CE: |g| = 0.99 MSE: |g| ≈ 0.0098 cross-entropy |g| = 1 − q (solid) probability-MSE (dashed) |g| = q(1 − q)² 1.0 0.5 0 0 0.25 0.50 0.75 1.0 logit-gradient magnitude |g| true-class probability q · true label y = 1
Read it this way: move left toward confident error. Cross-entropy's gradient approaches minus one. Probability-MSE includes the saturating sigmoid derivative, so its magnitude approaches zero. The dashed curve describes this binary comparison, not every possible squared-error model.
Check: Why is the cross-entropy logit gradient large where the probability-squared-error gradient nearly vanishes?
Read it this way: Normalize class predictions together. Targets specify which outcomes to reward. Smoothing spreads target mass, reducing extreme pushes. Temperature changes predictions and rescales the logit gradient. The separate binary example shows cross-entropy correcting confident errors while squared error's sigmoid gate nearly closes. These are specified toy settings. At predicted probability 0.01 for a positive label, which gradient remains large?

What an interviewer expects you to say

State the observation model, derive the log-normalizer gradient, declare the reduction, and explain stable evaluation. For independent examples, summed negative log-likelihood is the joint training objective; a mean divides its gradients by sample count. For multilabel tasks with independent binary targets, categorical normalization changes the model and is generally inappropriate.

Change the Requirement

Smooth the Target

New task: Replace a one-hot target with , where .

Picture and change: Optimize ; normalization preserves gradient .

Check: With , class zero, and , target gives gradient .

Use when: A deliberately softened training target is appropriate. The target and its interpretation have changed; improved calibration is not guaranteed by the algebra.

Change Temperature

New task: Use probabilities , with fixed .

Picture and change: The chain rule adds : .

Check: For and , . The gradient is approximately .

Use when: The task specifies temperature-scaled training or inference probabilities. Distillation may additionally scale its loss; state that convention separately.

Common confusions

  • Wrong API input. A logits-based cross-entropy API does not expect already normalized probabilities.
  • Wrong task. Multiclass normalization and independent multilabel Bernoulli losses encode different outcome spaces.
  • Unnormalized targets. For general target weights , the gradient is , not automatically .

Numerical stability: the LSE trick

Let and evaluate the shifted expression:

log_sum_exp(z) = max(z) + log(sum_j exp(z_j - max(z)))

For the loss itself, use . This avoids exponentiating positive shifted logits and avoids subtracting two large log-normalized quantities afterward. For logits , class-zero loss is , despite naive exponentiation overflowing. Nonfinite logits, unrepresentable differences, and all-masked rows still need a declared policy.

Why MSE fails on classification

The heading describes sigmoid saturation in the displayed example, not a universal impossibility theorem. Squared probability error is related to the Brier score and can be a meaningful evaluation or training objective. Its optimization behavior differs because the sigmoid derivative can suppress a confident-error logit update. Cross-entropy avoids that extra factor for logits, but parameter gradients can still vanish through other network operations.

Reconstruct

Does the simple logit gradient guarantee numerical stability or successful training?

No. Naive exponentiation can overflow before a gradient is computed. Stable normalization addresses that arithmetic issue; optimization, model suitability, and upstream derivatives remain separate concerns.


Related: BatchNorm vs LayerNorm. Related interview: Why does dropout work?.