Math Fundamentals · lesson 14/15
Moving Averages (EMA)
A moving average smooths a noisy sequence by mixing in past values. The exponential moving average (EMA) gives recent points more weight, and it updates with one multiply and one add. Optimizer state, batch-norm statistics, and target networks all run on this recursion.
The idea
The simple moving average takes the mean of the last values and weights them all equally. The EMA replaces the window with a decay:
with . Unrolling shows why it is exponential: . The weight of a value steps back is , a geometric decay.
Two settings to reason about:
- Effective window is about steps. averages over roughly 10 samples; over roughly 100. Larger is smoother and slower to react.
- Bias correction removes the start-up lag. Initializing makes early values too small by a factor of , so the corrected estimate is . Adam applies this to both of its moment estimates.
Because the recursion is linear, it converges to the constant level of any stationary input: if forever, .
Worked example
Let with and :
Checking the weights directly: enters with weight , with , and with . Weighted sum: . The weights sum to 1, as they must.
The effective window is steps. With the same three points would be dominated by the initial value, because the window is 10 steps long.
For bias correction, start from . The first raw estimate is , exactly half of , but dividing by recovers . As grows, and the correction fades away.
In code
import numpy as np
x = np.array([1.0, 2.0, 3.0, 4.0, 3.0, 2.0])
def ema(xs, beta):
s, out = 0.0, []
for t, xt in enumerate(xs):
s = beta * s + (1 - beta) * xt
out.append(s / (1 - beta**(t + 1))) # bias-corrected
return np.round(out, 4)
print(ema(x, 0.5)) # [1. 1.6667 2.4286 3.2667 3.129 2.5556]
print(ema(x, 0.9)) # [1. 1.5263 2.0701 2.6313 2.7213 2.5674]The curve lags on the way up and is smoother at the peak. That lag is the price of variance reduction.
Check yourself
- Why is the new value multiplied by rather than added directly?
- How many past samples does effectively average over?
- Why does Adam correct its moment estimates for bias early in training?
Key takeaways
- EMA is a geometric-weighted average: .
- is the effective window; bias correction fixes the cold start.
- It is the standard way to track a running statistic cheaply in one pass.