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

54. 使用 Jensen-Shannon divergence 比较两个 token 分布

EasyProbability and statistics

KL divergence 不具备对称性,且当其中一个分布为零时会趋于无穷大。Jensen-Shannon divergence 解决了这两个问题,是衡量 drift 和 diversity 的常用指标。

编写 js_divergence(p, q),输入为两个和为 1 的 1D 非负数组。令 m = (p + q) / 2,返回以 nats 为单位的 0.5 KL(p || m) + 0.5 KL(q || m)。当第一个分布为 0 的项贡献为 0。

函数def js_divergence(p, q)

示例 1

输入: js_divergence([1, 0], [0, 1])

输出: log 2

示例 2

输入: p = [0.2, 0.8], q = [0.2, 0.8]

输出: 0.0

示例 3

输入: p = [0.1, 0.4, 0.5], q = [0.3, 0.3, 0.4]

输出: 0.03253

约束条件

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

JS is the average of two KL divergences, each measured against the midpoint distribution m = (p + q) / 2, which is never zero where p or q is positive.

提示 2

Compute m, write a helper kl(a, b) that sums a * log(a / b), and return 0.5 kl(p, m) + 0.5 kl(q, m).

提示 3

Inside kl, keep only entries where a > 0 with a mask like k = a > 0 so 0 * log 0 terms are skipped instead of giving nan.

理解思路

KL divergence 衡量一个分布与另一个分布之间的差异,但它不具备对称性,并且当第二个分布在第一个分布不为零的地方为零时,结果会变为无穷大。Jensen-Shannon divergence 解决了这两个问题:将每个分布与其平均值 m 进行比较(只要其中一个分布为正,m 就绝不会为零),然后对两个 KL 散度取平均。结果是对称的,且最大值为 ln 2。

Worked example

p = [0.5, 0.5], q = [1, 0]. m = [0.75, 0.25]. KL(p || m) = 0.5 * ln(0.5 / 0.75) + 0.5 * ln(0.5 / 0.25) = -0.2027 + 0.3466 = 0.1438. KL(q || m) = 1 * ln(1 / 0.75) = 0.2877,且零项不产生贡献。JS = 0.5 * 0.1438 + 0.5 * 0.2877 = 0.2158 nats。完全不同的分布(如 [1, 0] 和 [0, 1])结果为 ln 2 = 0.6931。

m = (p + q) / 2; JS = 0.5 * KL(p || m) + 0.5 * KL(q || m),其中 KL(a || b) = 在 a > 0 的项上对 a * ln(a / b) 求和。常用于衡量 token 分布之间的 drift 以及生成文本的 diversity。
主题
Probability and statistics
相似题目
  • 单次遍历追踪流的均值和方差Easy
  • 计算两个对角高斯分布之间的 KL divergenceEasy
  • 使用逆 CDF 从固定均匀分布中进行类别采样Easy
  • 计算离散随机变量及其 aX + b 的均值和方差Easy
所有 Probability and statistics 道题目
反馈
54 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def js_divergence(p, q):
# your code here
pass
​

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

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