Machine learning building blocks
Softmax cross-entropy loss
ml.cross-entropy-lossAlso called cross entropy loss, cross entropy, softmax cross entropy, categorical cross entropy
Mean negative log-probability of the true class under the softmax of each row of logits, in nats. Classes are 0-based. This is torch.nn.functional.cross_entropy with integer targets and mean reduction.
Notation
logits, one row per example
z ∈ ℝB×C
true class of each example, 0-based
y ∈ {0, …, C−1}B
batch size
Size, at least 1
number of classes
Size, at least 2
Result: the mean loss, in nats
scalar
Worked examples
Each result is solved exactly and confirmed by two independent computations.
Given
Result
≈ 0.69314718056
Given
Result
≈ 0.407605964444
Given
Result
≈ 0.549306144334
Common mistakes
Computes softmax probabilities, then their log
exp overflows for logits above about 709 and the log of an underflowed probability is −inf.
Fix: Use log-sum-exp with the row maximum subtracted, or torch.nn.functional.cross_entropy on raw logits.
Applies softmax before a loss that applies it again
Probabilities are passed where logits are expected, so the softmax is applied twice.
Fix: Pass raw logits to cross_entropy; it applies log-softmax itself.
Applies the NLL loss to raw logits
nll_loss expects log-probabilities; on raw logits it returns the mean of −zb yb.
Fix: Apply log_softmax before nll_loss, or use cross_entropy.
Sums instead of averaging
The per-example losses are summed over the batch.
Fix: Divide by the batch size, or use reduction='mean'.
Source
Goodfellow et al. 2016, §6.2.1.1
Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron. Deep Learning. MIT Press, 2016.