BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Probability and statistics2 of 24 in topic

53. 计算两个对角高斯分布之间的 KL divergence

EasyProbability and statistics

两个高斯分布之间的 KL divergence 有闭式解。它是变分自编码器(VAE)中的正则项,也是比较两个预测分布的常用方法。

编写 kl_diag_gauss(mu1, sigma1, mu2, sigma2)。每个参数都是长度为 d 的 1D array;sigma1 和 sigma2 是标准差(正数),而不是方差。返回 KL(N1 || N2) 的 float 值,即在 d 个独立维度上的总和。每个维度的计算公式为 log(sigma2 / sigma1) + (sigma1^2 + (mu1 - mu2)^2) / (2 sigma2^2) - 0.5。

函数def kl_diag_gauss(mu1, sigma1, mu2, sigma2)
Play with it

KL divergence between two Gaussians

KL(N1 || N2) = log(σ2/σ1) + (σ1² + (μ1 − μ2)²) / (2σ2²) − 1/2, computed live. A diagonal Gaussian sums this over dimensions.

00.20.4-6-4-20246xdensity
KL(N1 || N2)
0.3499
KL(N2 || N1)
0.7195
KL is not symmetric: swap the two and the number changes.

示例 1

输入: mu1 = [0], sigma1 = [1], mu2 = [1], sigma2 = [1]

输出: 0.5

示例 2

输入: mu1 = [1.0, 2.0], sigma1 = [0.5, 3.0], mu2 = [1.0, 2.0], sigma2 = [0.5, 3.0]

输出: 0.0

示例 3

输入: mu1 = [0.0, 1.0], sigma1 = [2.0, 0.5], mu2 = [0.5, 0.0], sigma2 = [1.0, 1.5]

输出: 1.808243

约束条件

  • Python 3 with NumPy. Code runs in your browser.
  • Your code must pass all 9 tests to be accepted.
提示 1

将每个维度的公式向量化并求和。

提示 2

注意你持有的是标准差还是方差。

理解思路

KL divergence 衡量一个概率分布与另一个概率分布之间的差异程度;只有当它们完全匹配时,KL divergence 才为零,且它是不对称的。对于维度独立的高斯分布,每个维度都有闭式解,你只需要对所有维度求和。输入是标准差而非方差,这是一个容易出错的地方。Worked example, 一个维度: mu1 = 0, sigma1 = 1, mu2 = 0, sigma2 = 2. log(2 / 1) = 0.693. (1^2 + 0^2) / (2 x 2^2) = 1 / 8 = 0.125. KL = 0.693 + 0.125 - 0.5 = 0.318. 另一个例子: mu1 = 0, mu2 = 1, 两个 sigma 均为 1, 结果为 0 + (1 + 1) / 2 - 0.5 = 0.5. 如果写成 log(sigma2^2 / sigma1^2) 会使 log 项翻倍。

KL(N1 || N2) = sum over d of [log(sigma2 / sigma1) + (sigma1^2 + (mu1 - mu2)^2) / (2 sigma2^2) - 0.5]. 这是变分自编码器中的正则项。
主题
Probability and statistics
相似题目
  • 单次遍历追踪流的均值和方差Easy
  • 使用 Jensen-Shannon divergence 比较两个 token 分布Easy
  • 使用逆 CDF 从固定均匀分布中进行类别采样Easy
  • 计算离散随机变量及其 aX + b 的均值和方差Easy
所有 Probability and statistics 道题目
反馈
53 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def kl_diag_gauss(mu1, sigma1, mu2, sigma2):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 9 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS