All formulas

Numerical methods

Log-sum-exp

num.log-sum-expAlso called log sum exp, logsumexp, lse, log add exp

LSE⁡(x)=ln⁡(∑i=1nexi)\operatorname{LSE}(x) = \ln\left(\sum_{i=1}^{n} e^{x_i}\right)

Log of a sum of exponentials, a smooth maximum. Computing it as written overflows once an entry exceeds about 709; the stable form m + ln Σ exi − m, with m the largest entry, gives the same value for every input.

Notation

xx

values (logits or log-probabilities)

x ∈ ℝn

nn

number of values

Size, at least 1

LSE⁡(x)\operatorname{LSE}(x)

Result: the log of the sum of exponentials

scalar

Worked examples

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

  1. Given

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

    Result

    LSE⁡(x)=log⁡(2)\displaystyle \operatorname{LSE}(x) = \log{\left(2 \right)}

    ≈ 0.69314718056

  2. Given

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

    Result

    LSE⁡(x)=log⁡(e+e2+e3)\displaystyle \operatorname{LSE}(x) = \log{\left(e + e^{2} + e^{3} \right)}

    ≈ 3.40760596444

  3. Given

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

    Result

    LSE⁡(x)=log⁡(2)+1000\displaystyle \operatorname{LSE}(x) = \log{\left(2 \right)} + 1000

    ≈ 1000.69314718

  4. Given

    x=[−1000,−1000,−1000]x = [-1000, -1000, -1000]

    Result

    LSE⁡(x)=−1000+log⁡(3)\displaystyle \operatorname{LSE}(x) = -1000 + \log{\left(3 \right)}

    ≈ -998.901387711

Common mistakes

  • Exponentiates without shifting by the maximum

    exp overflows to inf for entries above about 709 and underflows to 0 below about −745, so the result becomes inf or −inf.

    Fix: Subtract the maximum m before exponentiating and add it back: m + ln Σ exp(xi − m), or call scipy.special.logsumexp.

  • Shifts by the maximum but does not add it back

    The result is ln Σ exp(xi − m), short by the maximum m.

    Fix: Add the maximum back after taking the log.

Sources

  • Blanchard et al. 2021

    Blanchard, Pierre; Higham, Desmond J.; Higham, Nicholas J. Accurately computing the log-sum-exp and softmax functions. IMA Journal of Numerical Analysis 41(4): 2311-2330, 2021. doi:10.1093/imanum/draa038

    doi.org
  • Goodfellow et al. 2016, §4.1

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

    deeplearningbook.org