Smooth a noisy metric with an exponential moving average

Training loss curves are noisy. TensorBoard and W&B smooth them with an exponential moving average: each new value is mixed with the running average.

Write ema(values, alpha) that returns a list the same length where out[0] = values[0] and out[t] = alpha * values[t] + (1 - alpha) * out[t - 1].

Signaturedef ema(values, alpha)

Understand the idea

An exponential moving average smooths a noisy series by mixing each new value with the running average so far. Old values never fully disappear, they just fade. Like forming an opinion of a cricketer where the latest match counts most but past form still matters. alpha is the weight on the newest value: a large alpha follows the data closely, a small alpha smooths heavily. Worked example: 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. With alpha = 0.1, out[1] would be 0.1 x 20 + 0.9 x 10 = 11, much smoother. Rule: out[0] = values[0]; out[t] = alpha x values[t] + (1 - alpha) x out[t - 1]. Swapping the two weights is a common bug. Training dashboards smooth loss curves this way, and the same idea appears in optimizers and model weight averaging.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: alpha 0.5ema([1.0, 3.0, 2.0, 6.0], 0.5)
  • Sample 2: alpha 0.1ema([10.0, 0.0, 0.0, 0.0], 0.1)
  • Test 3: alpha 1 copies inputema([4.0, 5.0], 1.0)