All formulas

Machine learning building blocks

Softmax cross-entropy loss

ml.cross-entropy-lossAlso called cross entropy loss, cross entropy, softmax cross entropy, categorical cross entropy

L=1B∑b=1B(ln⁡∑c=1Cezbc−zb,yb)\mathcal{L} = \frac{1}{B}\sum_{b=1}^{B}\left(\ln\sum_{c=1}^{C} e^{z_{bc}} - z_{b,y_b}\right)

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

zz

logits, one row per example

z ∈ ℝB×C

yy

true class of each example, 0-based

y ∈ {0, …, C−1}B

BB

batch size

Size, at least 1

CC

number of classes

Size, at least 2

L\mathcal{L}

Result: the mean loss, in nats

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    z=[[0,0]],y=[0]z = \left[\left[0, 0\right]\right], y = [0]

    Result

    L=log⁡(2)\displaystyle \mathcal{L} = \log{\left(2 \right)}

    ≈ 0.69314718056

  2. Given

    z=[[1,2,3]],y=[2]z = \left[\left[1, 2, 3\right]\right], y = [2]

    Result

    L=−3+log⁡(e+e2+e3)\displaystyle \mathcal{L} = -3 + \log{\left(e + e^{2} + e^{3} \right)}

    ≈ 0.407605964444

  3. Given

    z=[[0,0,0],[1000,0,0]],y=[1,0]z = \left[\left[0, 0, 0\right], \left[1000, 0, 0\right]\right], y = [1, 0]

    Result

    L=−500+log⁡(3)2+log⁡(2+e1000)2\displaystyle \mathcal{L} = -500 + \frac{\log{\left(3 \right)}}{2} + \frac{\log{\left(2 + e^{1000} \right)}}{2}

    ≈ 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.

    deeplearningbook.org