可视化两个分布的 KL 散度
对照高斯闭式解与数值积分,比较正反方向和概率支持条件。
学完这一章,你能够
- 对照高斯闭式解与数值积分,比较正反方向和概率支持条件。
先明确哪一个分布产生样本
KL(P‖Q) 衡量从 P 抽样时,用 Q 代替 P 的期望对数损失增量。交换 P 和 Q 后,对期望的加权也变了。用 N(μ,σ²) 记号时,均值相差 2、标准差同为 1 的两个分布在两个方向都得到 2。若同均值、标准差分别为 1 和 3,两个方向约为 0.654168 和 2.901388。若 3 指方差,结果约为 0.215973、0.450694。
离散情形 Dₖₗ(P‖Q)=∑ₓP(x)ln[P(x)/Q(x)],由此可得 Dₖₗ=H(P,Q)−H(P)。P 固定时,两种优化有相同最优 Q。P(x)=0 的项为零,P(x)>0 而 Q(x)=0 会给出无穷大。散度非对称,也无需满足三角不等式。
用数值积分检查两种方向
程序通过解析式和同一宽网格上的梯形积分核对密度,避免用概率裁剪掩盖支持问题。网格若只覆盖窄区间,会丢掉宽分布的一部分质量。对照图同时显示密度和 KL 的有向积分项,后者允许局部为负。

VAE 的常见目标会用 KL 将编码分布约束到先验。蒸馏可用教师分布为 P、学生为 Q。PPO 论文同时介绍 KL 惩罚和概率比裁剪两种目标,裁剪式不能与固定 KL 惩罚等同。
KL 在模型训练中的方向
| 场景 | 应用及范围 |
|---|---|
| 编码后验与先验 | 构造一维正态编码后验并计算对标准正态的 KL。实际重构训练待专题。 |
| 教师到学生 | 教师固定时,交叉熵减去教师熵等于相应 KL。 |
| 旧策略和新策略 | 可测分布变化、作控制或采用论文中的惩罚版本。程序分别计算 KL 与裁剪代理。 |
计算两个方向的高斯 KL 并生成对照图
"""Compare two directions of Gaussian KL in closed form and by quadrature."""
from hashlib import sha256
import json
from math import inf, isclose, isinf, log, pi, sqrt
from pathlib import Path
import platform
import struct
import matplotlib
matplotlib.use("Agg")
from matplotlib import pyplot as plt
import numpy as np
def gaussian_kl(p,q):
m,s=p
n,t=q
return log(t/s)+(s*s+(m-n)**2)/(2*t*t)-.5
def log_density(x,params):
mean,sd=params
return -.5*((x-mean)/sd)**2-log(sd*sqrt(2*pi))
def discrete_kl(p,q):
if any(a>0 and b==0 for a,b in zip(p,q,strict=True)):
return inf
return sum(a*log(a/b) for a,b in zip(p,q,strict=True) if a > 0)
def main():
cases=[]
def record(name, operation, inputs, expected, actual):
assert expected == actual, (name, expected, actual)
cases.append(dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True))
pairs=[((0.,1.),(2.,1.)),((0.,1.),(0.,3.)),((0.,1.),(0.,sqrt(3)))]
values=[[round(gaussian_kl(p,q),6), round(gaussian_kl(q,p),6)] for p,q in pairs]
record("both_gaussian_directions","distinguish standard deviation three from variance three",
pairs,[[2.,2.],[.654168,2.901388],[.215973,.450694]],values)
x=np.linspace(-40,40,40001)
close=[]
for p,q in pairs:
a,b=log_density(x,p),log_density(x,q)
close.append(bool(np.allclose([np.trapezoid(np.exp(a)*(a-b),x),np.trapezoid(np.exp(b)*(b-a),x)],
[gaussian_kl(p,q),gaussian_kl(q,p)],atol=1e-10,rtol=0.)))
record("integrate_without_probability_clipping","integrate both directions on one wide grid",
{"bounds":[-40,40],"samples":len(x)},[True,True,True],close)
p,q=[1.,0.],[0.,1.]
record("discrete_support_boundary","evaluate missing support and a zero-probability weighted term",
[p,q],[True,0.],[isinf(discrete_kl(p,q)),discrete_kl(p,p)])
p,q=[.75,.25],[.6,.4]
gap=-sum(a*log(b) for a,b in zip(p,q,strict=True))+sum(a*log(a) for a in p)
record("entropy_identity","subtract the teacher entropy from its cross entropy with the student",
[p,q],True,isclose(gap,discrete_kl(p,q)))
record("latent_normal_penalty","compare a latent Gaussian against a unit prior",
[[1,2],[0,1]],1.306853,round(gaussian_kl((1,2),(0,1)),6))
old,new=[.5,.5],[.8,.2]
ratio=new[0]/old[0]
clipped=min(ratio,min(1.2,max(.8,ratio)))
record("policy_penalty_and_clipping_differ","compare one positive-advantage ratio with a weighted KL penalty",
{"old":old,"new":new,"advantage":1,"clip":.2,"penalty_weight":.5},
[1.2,1.488428], [clipped,round(ratio-.5*discrete_kl(old,new),6)])
window=np.linspace(-10,10,2001)
wide=np.exp(log_density(window,(0.,3.)))
record("truncated_wide_density_mass","measure lost mass with a finite integration window",
{"window":[-10,10],"std":3},.999142,round(float(np.trapezoid(wide,window)),6))
output=Path(__file__).resolve().parent/"outputs/kl-directions.png"
output.parent.mkdir(exist_ok=True)
narrow_log=log_density(window,(0.,1.))
wide_log=log_density(window,(0.,3.))
fig,axes=plt.subplots(1,2,figsize=(9.25,4.2),layout="constrained")
axes[0].plot(window,np.exp(narrow_log),label="P, sd 1",color="#126d7e")
axes[0].plot(window,wide,label="Q, sd 3",color="#aa4d23")
axes[1].plot(window,np.exp(narrow_log)*(narrow_log-wide_log),label="P to Q",color="#126d7e")
axes[1].plot(window,wide*(wide_log-narrow_log),label="Q to P",color="#aa4d23")
axes[0].set(title="Gaussian densities",ylabel="Density")
axes[1].set(title="Directed KL integrands",ylabel="Density times log ratio")
for ax in axes:
ax.set(xlabel="Value")
ax.axhline(0,color="#6a7171",lw=.7)
ax.grid(alpha=.25)
ax.legend()
fig.savefig(output,dpi=100)
plt.close(fig)
data=output.read_bytes()
record("plot_gaussian_kl","render densities and their directed, signed integrands",
{"standard_deviations":[1,3]},[[925,420],True],
[list(struct.unpack(">II",data[16:24])),data.startswith(b"\x89PNG\r\n\x1a\n")])
cases[-1]["artifact"]=dict(path="outputs/kl-directions.png",sha256=sha256(data).hexdigest(),bytes=len(data))
print(json.dumps(dict(version=platform.python_version(),library_versions={"numpy":np.__version__,"matplotlib":matplotlib.__version__},cases=cases)))
if __name__=="__main__":
main()
- 相同尺度下两个方向的结果同为 2;尺度为 1 和 3 时,两方向数值不同。
所需环境:Windows、Python 3.12.14。numpy 2.5.4;matplotlib 3.11.2。
当前源码 SHA256:de7db323119274ba57247ee98341f2e3c74ebf9b4b6cf056045367b4b27233cf
复跑实验
解压后按 README 运行自编程序。
所需环境:Windows、Python 3.12.14。numpy 2.5.4;matplotlib 3.11.2。
ZIP SHA256:0d5ba88da9bafa2086a803693e81cc53531142a1e1d8e68150224803752661b6
常见错误与边界
- 确认分布参数表示方差还是标准差。
- 数值积分需核对网格截断误差。
练习与解答
若 P、Q 正好相同,两个方向的散度是多少?
展开参考解答
都是 0。