Equations · Standard; the negative log-likelihood of a categorical model

The cross-entropy loss formula, explained

The loss used to train classifiers and language models: the average negative log-probability the model gave to the right answer.

L(θ)=−1N∑i=1N∑k=1Kyk(i)log⁡y^k(i)\mathcal{L}(\theta) = -\frac{1}{N}\sum_{i=1}^{N}\sum_{k=1}^{K} y^{(i)}_k \log \hat{y}^{(i)}_k

Open in the decoder →

Term by term

  1. L(θ)\mathcal{L}(\theta)

    The loss, as a function of the model's parameters.

  2. −1N∑i=1N-\frac{1}{N}\sum_{i=1}^{N}

    Average over the NN examples. The minus sign turns log-probabilities (negative) into a positive loss.

  3. yk(i)y^{(i)}_k

    The target for example ii, class kk: 1 for the correct class and 0 otherwise (one-hot). The (i)(i) indexes examples; it is not a power.

  4. y^k(i)\hat{y}^{(i)}_k

    The model's predicted probability of class kk for example ii, usually a softmax output.

  5. log⁡\log

    Natural log. Because yy is one-hot, the inner sum keeps only log⁡\log of the probability given to the correct class.

A small worked example

Target y=(0,1,0)\mathbf{y} = (0, 1, 0), prediction y^=(0.2,0.7,0.1)\hat{\mathbf{y}} = (0.2, 0.7, 0.1): the loss is −log⁡0.7≈0.357-\log 0.7 \approx 0.357. A confident wrong answer, y^2=0.01\hat{y}_2 = 0.01, would cost −log⁡0.01≈4.6-\log 0.01 \approx 4.6.

In code

import numpy as np

def cross_entropy(y_onehot, y_prob):
    # y_onehot, y_prob: (N, K)
    return -np.mean(np.sum(y_onehot * np.log(y_prob), axis=1))

Every symbol in it

L(θ)\mathcal{L}(\theta)Loss (ℒ)pθ(x)p_\theta(x)Thetaab\frac{a}{b}Fraction∑i=1Nxi\sum_{i=1}^{N} x_iSummationx(i),  W[l]\mathbf{x}^{(i)},\; W^{[l]}Superscript in parenthesesxi,  Wq,  pθ,  dmodelx_i,\; W_q,\; p_\theta,\; d_{\text{model}}Subscript (index or label)y^\hat{y}Hat (estimate)log⁡pθ(x)\log p_\theta(x)Logarithm

Other equations