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

52. 单次遍历追踪流的均值和方差

EasyProbability and statistics

Batch norm、Adam 和监控仪表盘都需要对无法全部存入内存的数据流进行运行统计。朴素公式 mean(x ** 2) - mean(x) ** 2 会严重丢失精度。Welford 方法通过每次更新一个值来更新均值和平方偏差之和。

编写 running_stats(values) 函数,对 values 进行单次遍历并返回 (mean, variance),其中 variance 是总体方差(除以 n)。对于空列表,返回 (0.0, 0.0)。

函数def running_stats(values)
Play with it

Sample mean and spread from N(μ, σ²)

Draw samples and watch the sample std approach σ as the count grows. Welford's method computes the same variance in one streaming pass.

00.20.4-6-4-20246xdensity
sample mean
-0.025
sample std
0.901
true mean, std
0, 1
Synthetic samples drawn in your browser from N(μ1, σ1²).

示例 1

输入: values = [2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0]

输出: (5.0, 4.0)

示例 2

输入: values = [1e9 + 4.0, 1e9 + 7.0, 1e9 + 13.0, 1e9 + 16.0]

输出: (1000000010.0, 22.5)

示例 3

输入: values = []

输出: (0.0, 0.0)

约束条件

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

保留 n, mean 和 M2。

提示 2

对于每个 x: n += 1, delta = x - mean, mean += delta / n, M2 += delta * (x - mean)。

提示 3

Variance 是 M2 / n。

常见错误
  • 总体方差除以 n;错误的实现版本除以 n - 1。
理解思路

Welford 方法通过在每个新值到达时同时更新运行均值和运行平方偏差之和来工作。你不需要存储整个数据流,并且避免了使用 mean(x^2) - mean(x)^2 公式,因为该公式通过两个巨大且几乎相等的数相减会导致精度丢失。可以将其想象成老师在每个新成绩到达时更新班级平均分。

Worked example

values [2, 4, 6]。After 2: n = 1, mean = 2, M2 = 0。After 4: delta = 4 - 2 = 2, mean = 3, M2 += 2 * (4 - 3) = 2。After 6: delta = 6 - 3 = 3, mean = 4, M2 += 3 * (6 - 4) = 6, so M2 = 8。Population variance = 8 / 3 = 2.667。Check: deviations -2, 0, 2 squared sum to 8。

n += 1; delta = x - mean; mean += delta / n; M2 += delta * (x - new mean); variance = M2 / n。Empty input gives (0.0, 0.0)。Batch norm 统计和指标仪表盘都使用这种运行更新方式。
主题
Probability and statistics
相似题目
  • 计算两个对角高斯分布之间的 KL divergenceEasy
  • 使用 Jensen-Shannon divergence 比较两个 token 分布Easy
  • 使用逆 CDF 从固定均匀分布中进行类别采样Easy
  • 计算离散随机变量及其 aX + b 的均值和方差Easy
所有 Probability and statistics 道题目
反馈
52 / 903
Python 3solution.pyPython 空闲
1
2
3
4
def running_stats(values):
# your code here
pass
​

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

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