2

A trick in Log-Sum-Exp

 3 years ago
source link: https://arminli.com/trick-in-log-sum-exp/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Armin's Blog

A trick in Log-Sum-Exp

March 15, 2018

z=log⁡∑n=1Nexp⁡{xn}z=\log\sum_{n=1}^{N}\exp\{x_{n}\}z=logn=1∑N​exp{xn​}

时,可能会遇到溢出问题:

  1. exp{1000}=inf, log(inf)=inf, 向上溢出
  2. exp{-1000}=0, log(0)无法计算

为了避免这种情况,能够正常计算,将上式转化为:

log⁡∑n=1Nexp⁡{xn}=a+log⁡∑n=1Nexp⁡{xn−a}\log\sum_{n=1}^{N}\exp\{x_{n}\}=a+\log\sum_{n=1}^{N}\exp\{x_{n}-a\}logn=1∑N​exp{xn​}=a+logn=1∑N​exp{xn​−a}

其中对任意的 a 都成立,这个推导非常简单,这里就不写了。

最简单的做法是把 a 取为 {xn}\{x_{n}\}{xn​} 中的最大值,即

a=max⁡nxna=\max_{n} x_{n}a=nmax​xn​

这时 x-a 一定小于等于 0,exp{x-a} 就会在 0 到 1 之间,不会发生上溢出;而当 x=a 时,exp(x-a) = 1,也就是 log 的真数一定大于等于 1,因此也不会发生下溢出。

Reference

Computing Log-Sum-Exp


Profile picture

Written by Armin Li , a venture capitalist. [Weibo] [Subscribe]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK