All formulas

Machine learning building blocks

Log-softmax

ml.log-softmaxAlso called log softmax, logsoftmax, log_softmax, log probabilities

log⁡softmax⁡(x)i=xi−ln⁡(∑j=1nexj)\log\operatorname{softmax}(x)_i = x_i - \ln\left(\sum_{j=1}^{n} e^{x_j}\right)

Log of the softmax probabilities, computed as each score minus the log-sum-exp of all scores. Taking the log of a computed softmax loses accuracy and fails where the softmax overflows or underflows.

Notation

xx

logits (unnormalized scores)

x ∈ ℝn

nn

number of entries

Size, at least 2

log⁡softmax⁡(x)\log\operatorname{softmax}(x)

Result: the log-probabilities

vector

Worked examples

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

  1. Given

    x=[0,0]x = [0, 0]

    Result

    log⁡softmax⁡(x)=(−log⁡(2),−log⁡(2))\displaystyle \log\operatorname{softmax}(x) = \left(- \log{\left(2 \right)}, - \log{\left(2 \right)}\right)

    ≈ (-0.69314718056, -0.69314718056)

  2. Given

    x=[1,2,3]x = [1, 2, 3]

    Result

    log⁡softmax⁡(x)=(1−log⁡(e+e2+e3),2−log⁡(e+e2+e3),3−log⁡(e+e2+e3))\displaystyle \log\operatorname{softmax}(x) = \left(1 - \log{\left(e + e^{2} + e^{3} \right)}, 2 - \log{\left(e + e^{2} + e^{3} \right)}, 3 - \log{\left(e + e^{2} + e^{3} \right)}\right)

    ≈ (-2.40760596444, -1.40760596444, -0.407605964444)

  3. Given

    x=[1000,1000]x = [1000, 1000]

    Result

    log⁡softmax⁡(x)=(−log⁡(2),−log⁡(2))\displaystyle \log\operatorname{softmax}(x) = \left(- \log{\left(2 \right)}, - \log{\left(2 \right)}\right)

    ≈ (-0.69314718056, -0.69314718056)

Common mistakes

  • Takes the log of a naively computed softmax

    exp overflows for scores above about 709, and very negative log-probabilities underflow to log(0) = −inf.

    Fix: Compute xi − LSE(x) with the maximum subtracted inside the log-sum-exp, or call torch.log_softmax / scipy.special.log_softmax.

Source

  • Goodfellow et al. 2016, §6.2.2.3

    Goodfellow, Ian; Bengio, Yoshua; Courville, Aaron. Deep Learning. MIT Press, 2016.

    deeplearningbook.org