It’s typical in many optimization problems in data analysis to standardize your data by subtracting off the empirical mean and dividing by the empirical standard deviation. However, in “online” situations where the data is acquired one at a time or in batches, it’s only possible to compute these statistics over the data observed up to that point. Further, it might not be desirable to store all the observations and re-compute the mean and standard deviation each time new data is acquired. There are simple formulas to update the existing mean and standard deviation to reflect the new data without storing all the observations.

Suppose we’ve observed $m$ observations, $x_i, \; i=1,\ldots,n$, so far, and we obtain a new “batch” of $n$ observations, $x_i \; i=m+1, \ldots, m+n$. Now denote,

Equation (1) is the desired updated mean, which we don’t want to compute as a sum over all observations. (2) is the current empirical mean, and (3) is the empirical mean of the new data batch. Yes, I realize I should write, $\hat{\mu}$, $\bar{x}$, or some such notation since the mean is empirical. But I’m not going to. Anyhow, from some simple calculations, we have that,

In other words, the updated mean is a linear combination of the mean over the old data and the mean over new data, yielding a simple recursive update.

Now let’s consider the empirical variances:

Observe that

so that

The update is a linear combination of the observed variances plus a correction by the means.

Note that, initially, we can set $m = \mu_m = \sigma_m^2 = 0$, and the formulas all work out. Also note that these are fine to use for vectors, since these statistics are computed component-wise.

Testing it out

Let’s write a simple class for storing the mean and standard deviation of the examples observed. Write a file call “statsrecorder.py”:

Now in a separate script, say “test_statsrecorder.py”, write:

You should observe nothing after running the scripts, which is exactly what should happen since we are asserting that our online tallies of mean and standard deviation agree with the same computation if all the observations were stored.