Track mean and variance of a stream in one pass
Batch norm, Adam and monitoring dashboards all keep running statistics over a stream that never fits in memory. The naive formula mean(x ** 2) - mean(x) ** 2 loses precision badly. Welford's method updates the mean and the sum of squared deviations one value at a time.
Write running_stats(values) that walks the values once and returns (mean, variance), where variance is the population variance (divide by n). For an empty list return (0.0, 0.0).
def running_stats(values)Understand the idea
Welford's method keeps a running mean and a running sum of squared deviations, updating both with each new value. You never store the whole stream, and you avoid the formula mean(x^2) - mean(x)^2, which subtracts two huge nearly equal numbers and loses precision. Think of a teacher updating the class average as each new mark arrives. 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. Rule: 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 statistics and metric dashboards use running updates like this.