DL_tricks

1. Softmax函数计算概率时,数值不稳定,上溢。

如果,存在较大的xix_i时,对其使用使用expexp指数函数很容易出现上溢。

而当负数过多时,分母每一个部分都为0,相加也为0,会出现除以0问题。

以下中的bbxixnx_i \dots x_n中的maxmax

Softmax(xi)=exp(xi)j=1nexp(xj)=exp(xib)exp(b)j=1n(exp(xjb)exp(b))=exp(xib)exp(b)exp(b)j=1nexp(xjb)=exp(xib)j=1nexp(xjb)=Softmax(xib)\begin{aligned} \mathrm{Softmax}(x_i)& =\frac{\exp(x_i)}{\sum_{j=1}^n\exp(x_j)} \\ &=\frac{\exp(x_i-b)\cdot\exp(b)}{\sum_{j=1}^n\left(\exp(x_j-b)\cdot\exp(b)\right)} \\ &=\frac{\exp(x_i-b)\cdot\exp(b)}{\exp(b)\cdot\sum_{j=1}^n\exp(x_j-b)} \\ &=\frac{\exp(x_i-b)}{\sum_{j=1}^n\exp(x_j-b)} \\ &=\mathrm{Softmax}(x_i-b) \end{aligned}

经过这样的恒等变换,分子上最大为1,分母中即使全是负数,也至少会出现一个1,避免了除以0的情况。

2. 在计算KL散度或者交叉熵时,LSE的数值稳定性,上溢或者对数0。

log(exji=1nexi)=log(exj)log(i=1nexi)=xjlog(i=1nexi)\begin{aligned} \operatorname{log}\biggl(\frac{e^{x_{j}}}{\sum_{i=1}^{n}e^{x_{i}}}\biggr)& =\log(e^{x_j}) - \log\biggl(\sum_{i=1}^ne^{x_i}\biggr) \\ &=x_j - \log\biggl(\sum_{i=1}^ne^{x_i}\biggr) \end{aligned}

和上面一样,如果xix_i有较大的,则会出现上溢。如果全是很小的负数,则会出现对0取对数的情况。

分母部分做以下处理,ccmax(xj)max(x_j )

LogSumExp(x1xn)=log(i=1exi)=log(i=1nexicec)=log(eci=1nexic)=log(i=1nexic)+log(ec)=log(i=1nexic)+c\begin{aligned} LogSumExp(x_1\ldots x_n)& =\log\left(\sum_{i=1}e^{x_i}\right) \\ &=\log\left(\sum_{i=1}^ne^{x_i-c}e^c\right) \\ &=\log\left(e^c\sum_{i=1}^ne^{x_i-c}\right) \\ &=\log\left(\sum_{i=1}^ne^{x_i-c}\right)+\log(e^c) \\ &=\log\left(\sum_{i=1}^ne^{x_i-c}\right)+c \end{aligned}

这样,类似地,不会出现上溢,并且对数内最少有个1,不会出现对对数取0的情况。

log(Softmax(xj,x1xn))=xjLogSumExp(x1xn)=xjlog(i=1nexic)c\begin{aligned}\log(Softmax(x_j,x_1\ldots x_n))&=x_j - LogSumExp(x_1 \ldots x_n)\\&=x_j - \log\left( \sum_{i=1}^ne^{x_i-c} \right) - c\end{aligned}


DL_tricks
https://fengxiang777.github.io/2024/08/14/DL-tricks/
作者
FengXiang777
发布于
2024年8月14日
许可协议