178. 使用指数移动平均平滑噪声指标
训练 loss 曲线通常包含噪声。TensorBoard 和 W&B 使用指数移动平均来平滑它们:每个新值都会与运行平均值进行混合。
编写 ema(values, alpha),返回一个长度相同的列表,其中 out[0] = values[0] 且 out[t] = alpha * values[t] + (1 - alpha) * out[t - 1]。
def ema(values, alpha)EMA smoothing with alpha
out[t] = α x[t] + (1 − α) out[t − 1]. High alpha follows the data closely, low alpha smooths more but lags.
Synthetic data made in your browser: y = 10 + 0.05 t + 2 sin(2πt / 12) + noise.
示例 1
输入: values = [1.0, 3.0, 2.0, 6.0], alpha = 0.5
输出: [1.0, 2.0, 2.0, 4.0]
示例 2
输入: values = [10.0, 0.0, 0.0, 0.0], alpha = 0.1
输出: [10.0, 9.0, 8.1, 7.29]
示例 3
输入: values = [4.0, 5.0], alpha = 1.0
输出: [4.0, 5.0]
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
Each output only depends on the current value and the previous output, so one running number is enough.
提示 2
Set the first output to the first value, then for every later value append alpha * value + (1 - alpha) * previous output.
提示 3
Handle index 0 separately, since there is no previous output yet, and use out[-1] as the previous value for the rest.
常见错误
- 有 bug 的版本交换了这两个权重。
理解思路
指数移动平均通过将每个新值与迄今为止的运行平均值混合,从而平滑噪声序列。旧值不会完全消失,只是逐渐淡化。这就像对一名板球运动员形成看法,最近的一场比赛权重最大,但过去的表现仍然重要。alpha 是最新值的权重:较大的 alpha 会紧跟数据,较小的 alpha 会进行重度平滑。
values [10, 20, 20], alpha = 0.5. out[0] = 10. out[1] = 0.5 x 20 + 0.5 x 10 = 15. out[2] = 0.5 x 20 + 0.5 x 15 = 17.5. 若 alpha = 0.1,则 out[1] = 0.1 x 20 + 0.9 x 10 = 11,平滑得多。
out[0] = values[0]; out[t] = alpha x values[t] + (1 - alpha) x out[t - 1]. 交换这两个权重是一个常见的 bug。训练仪表盘通过这种方式平滑 loss 曲线,同样的思想也出现在 optimizers 和模型权重平均中。