交叉熵 & K-L散度
交叉熵
信息论主要研究如何量化数据中的信息。最重要的信息度量单位是熵Entropy,一般用
H
H
H表示。分布的熵的公式如下:
H
=
−
∑
i
=
1
N
p
(
x
i
)
⋅
log
p
(
x
i
)
H=-\sum_{i=1}^{N} p\left(x_{i}\right) \cdot \log p\left(x_{i}\right)
H=−i=1∑Np(xi)⋅logp(xi)
Example:
Support there are there categories, the correct answer for an example is (1, 0, 0);
- The predicted answer of model A after softmax regression is (0.5, 0.2, 0.3);
- The predicted answer of model B after softmax regression is (0.7, 0.1, 0.2);
- The predicted answer of model C after softmax regression is(1.0, 0.0, 0.0);
𝑯((1, 0, 0), (0.5, 0.2, 0.3)) = -log 0.5 ≈ 0.301
𝑯((1, 0, 0), (0.7, 0.1, 0.2)) = -log 0.7 ≈ 0.155
𝑯((1, 0, 0), (1.0, 0.0, 0.0)) = -log 1.0 ≈ 0.0
So define cross entropy loss function:
Loss
=
−
∑
i
=
1
n
y
i
log
y
i
′
\begin{aligned} &\text { Loss }=-\sum_{i=1}^{n} y_{i} \log y_{i}^{\prime}\\ \end{aligned}
Loss =−i=1∑nyilogyi′
其中
:
y
i
: \quad y_{i}
:yi 为标签值,
y
i
′
\quad y_{i}^{\prime}
yi′ 为预测值
The cross entropy represents uncertainty. =>熵可以表示信息内部的混沌程度。
1948年,香农引入信息熵,将其定义为离散随机事件的出现概率。一个系统越是有序,信息熵就越低;反之,一个系统越是混乱,信息熵就越高。所以说,信息熵可以被认为是系统有序化程度的一个度量。
K-L散度=>相对熵
只需要稍加修改熵
H
H
H的计算公式就能得到K-L散度的计算公式。设
p
p
p为观察得到的概率分布,
q
q
q为另一分布来近似
p
p
p,则
p
p
p、
q
q
q的K-L散度为:
D
K
L
(
p
∥
q
)
=
∑
i
=
1
N
p
(
x
i
)
⋅
(
log
p
(
x
i
)
−
log
q
(
x
i
)
)
D_{K L}(p \| q)=\sum_{i=1}^{N} p\left(x_{i}\right) \cdot\left(\log p\left(x_{i}\right)-\log q\left(x_{i}\right)\right)
DKL(p∥q)=i=1∑Np(xi)⋅(logp(xi)−logq(xi))
根据上面的公式,K-L散度其实是数据的原始分布
p
p
p和近似分布
q
q
q之间的对数差值的期望。如果继续用2为底的对数计算,则K-L散度值表示信息损失的二进制位数。下面公式以期望表达K-L散度:
D
K
L
(
p
∥
q
)
=
E
[
log
p
(
x
)
−
log
q
(
x
)
]
D_{K L}(p \| q)=E[\log p(x)-\log q(x)]
DKL(p∥q)=E[logp(x)−logq(x)]
其中
E
q
E_{q}
Eq 表示从
q
q
q 采样,计算log
q
−
log
p
q-\log p
q−logp 的期望 ( expectation )
E
E
E。当变分分布 ( variational distribution )
q
q
q 等于真实分布
p
p
p 时,KL散度等于0。如果用参数
θ
\theta
θ 来表示 分布
q
θ
q_{\theta}
qθ -例如高斯分布
N
(
μ
,
σ
2
)
N\left(\mu, \sigma^{2}\right)
N(μ,σ2) 用参数均值
μ
\mu
μ 和方差
σ
2
\sigma^{2}
σ2 来表示一那么变分推断就是求参数
θ
\theta
θ 的值或范围,使
q
θ
q_{\theta}
qθ 近似
p
p
p。这也是变分推断被“变分"推断的原因。
一般,K-L散度以下面的书写方式更常见:
D
K
L
(
p
∥
q
)
=
∑
i
=
1
N
p
(
x
i
)
⋅
log
p
(
x
i
)
q
(
x
i
)
D_{K L}(p \| q)=\sum_{i=1}^{N} p\left(x_{i}\right) \cdot \log \frac{p\left(x_{i}\right)}{q\left(x_{i}\right)}
DKL(p∥q)=i=1∑Np(xi)⋅logq(xi)p(xi)
K-L散度能帮助我们度量使用一个分布来近似另一个分布时所损失的信息量。