蓝色天空.知识 · 实践 · 创造
我的收藏
AI 数学基础 教程目录 54章
课程介绍
AI 数学基础 / LEARN BY DOING

可视化两个分布的 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 的有向积分项,后者允许局部为负。

宽窄高斯密度与两个方向 KL 的被积函数对比。
本站程序运行所得。两方向的积分使用各自的样本密度权重。

VAE 的常见目标会用 KL 将编码分布约束到先验。蒸馏可用教师分布为 P、学生为 Q。PPO 论文同时介绍 KL 惩罚和概率比裁剪两种目标,裁剪式不能与固定 KL 惩罚等同。

KL 在模型训练中的方向

场景应用及范围
编码后验与先验构造一维正态编码后验并计算对标准正态的 KL。实际重构训练待专题。
教师到学生教师固定时,交叉熵减去教师熵等于相应 KL。
旧策略和新策略可测分布变化、作控制或采用论文中的惩罚版本。程序分别计算 KL 与裁剪代理。

计算两个方向的高斯 KL 并生成对照图

含完整源码 · 100 行
展开查看收起
python
"""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 时,两方向数值不同。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

复跑实验

解压后按 README 运行自编程序。

下载本章实验包 (mbskycom202612a33.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联54章) · 含当前章节或实例 · mbskycom202612a33.zip

下载课程关联工程包:AI 数学基础

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a64.zip

常见错误与边界检查

  • 确认分布参数表示方差还是标准差。
  • 数值积分需核对网格截断误差。

技术规范与官方资料

练习与参考解答

查看参考解答

都是 0。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习