Algorithms for calculating variance explained

Algorithms for calculating variance play a major role in computational statistics. A key difficulty in the design of good algorithms for this problem is that formulas for the variance may involve sums of squares, which can lead to numerical instability as well as to arithmetic overflow when dealing with large values.

Naïve algorithm

A formula for calculating the variance of an entire population of size N is:

\sigma2=\overline{(x2)}-\barx2=

N
\sum
2
x
i
-
N
(\sum
i=1
2/N
x
i)
i=1
N

.

Using Bessel's correction to calculate an unbiased estimate of the population variance from a finite sample of n observations, the formula is:

s2=\left(

n
\sum
2
x
i
i=1
n

-\left(

n
\sumxi
i=1
n

\right)2\right)

n
n-1

.

Therefore, a naïve algorithm to calculate the estimated variance is given by the following:

This algorithm can easily be adapted to compute the variance of a finite population: simply divide by n instead of n − 1 on the last line.

Because and can be very similar numbers, cancellation can lead to the precision of the result to be much less than the inherent precision of the floating-point arithmetic used to perform the computation. Thus this algorithm should not be used in practice,[1] [2] and several alternate, numerically stable, algorithms have been proposed.[3] This is particularly bad if the standard deviation is small relative to the mean.

Computing shifted data

The variance is invariant with respect to changes in a location parameter, a property which can be used to avoid the catastrophic cancellation in this formula.

\operatorname{Var}(X-K)=\operatorname{Var}(X).

with

K

any constant, which leads to the new formula

\sigma2=

n
\sum
2
(x
i-K)
-
n
(\sum
i=1
2/n
(x
i-K))
i=1
n-1

.

the closer

K

is to the mean value the more accurate the result will be, but just choosing a value inside thesamples range will guarantee the desired stability. If the values

(xi-K)

are small then there are no problems with the sum of its squares, on the contrary, if they are large it necessarily means that the variance is large as well. In any case the second term in the formula is always smaller than the first one therefore no cancellation may occur.

If just the first sample is taken as

K

the algorithm can be written in Python programming language as

def shifted_data_variance(data): if len(data) < 2: return 0.0 K = data[0] n = Ex = Ex2 = 0.0 for x in data: n += 1 Ex += x - K Ex2 += (x - K) ** 2 variance = (Ex2 - Ex**2 / n) / (n - 1) # use n instead of (n-1) if want to compute the exact variance of the given data # use (n-1) if data are samples of a larger population return variance

This formula also facilitates the incremental computation that can be expressed asK = Ex = Ex2 = 0.0n = 0

def add_variable(x): global K, n, Ex, Ex2 if n

0: K = x n += 1 Ex += x - K Ex2 += (x - K) ** 2

def remove_variable(x): global K, n, Ex, Ex2 n -= 1 Ex -= x - K Ex2 -= (x - K) ** 2

def get_mean: global K, n, Ex return K + Ex / n

def get_variance: global n, Ex, Ex2 return (Ex2 - Ex**2 / n) / (n - 1)

Two-pass algorithm

An alternative approach, using a different formula for the variance, first computes the sample mean,

\barx=

n
\sumxj
j=1
n,
and then computes the sum of the squares of the differences from the mean,

samplevariance=s2=\dfrac

n
{\sum
i=1

(xi-\barx)2}{n-1},

where s is the standard deviation. This is given by the following code:

def two_pass_variance(data): n = len(data) mean = sum(data) / n variance = sum((x - mean) ** 2 for x in data) / (n - 1) return variance

This algorithm is numerically stable if n is small.[1] [4] However, the results of both of these simple algorithms ("naïve" and "two-pass") can depend inordinately on the ordering of the data and can give poor results for very large data sets due to repeated roundoff error in the accumulation of the sums. Techniques such as compensated summation can be used to combat this error to a degree.

Welford's online algorithm

It is often useful to be able to compute the variance in a single pass, inspecting each value

xi

only once; for example, when the data is being collected without enough storage to keep all the values, or when costs of memory access dominate those of computation. For such an online algorithm, a recurrence relation is required between quantities from which the required statistics can be calculated in a numerically stable fashion.

The following formulas can be used to update the mean and (estimated) variance of the sequence, for an additional element xn. Here, \overline_n = \frac \sum_^n x_i denotes the sample mean of the first n samples

(x1,...,xn)

, \sigma^2_n = \frac \sum_^n \left(x_i - \overline_n \right)^2 their biased sample variance, and s^2_n = \frac \sum_^n \left(x_i - \overline_n \right)^2 their unbiased sample variance.

\barxn=

(n-1)\barxn-1+xn
n

=\barxn-1+

xn-\barxn-1
n

2
\sigma
n

=

(n-1)
2
\sigma
n-1
+(xn-\barxn-1)(xn-\barxn)
n

=

2
\sigma
n-1

+

(x-\barxn-1)(xn-\barxn)-
2
\sigma
n-1
n
n

.

2
s
n

=

n-2
n-1

2
s
n-1

+

(xn-\barxn-1)2
n

=

2
s
n-1

+

(xn-\barxn-1)2
n

-

2
s
n-1
n-1

,n>1

These formulas suffer from numerical instability, as they repeatedly subtract a small number from a big number which scales with n. A better quantity for updating is the sum of squares of differences from the current mean, \sum_^n (x_i - \bar x_n)^2, here denoted

M2,n

:

\begin{align} M2,n&=M2,n-1+(xn-\barxn-1)(xn-\barxn)

2
\\[4pt] \sigma
n

&=

M2,n
n
2
\\[4pt] s
n

&=

M2,n
n-1

\end{align}

This algorithm was found by Welford,[5] [6] and it has been thoroughly analyzed.[7] It is also common to denote

Mk=\barxk

and

Sk=M2,k

.[8]

An example Python implementation for Welford's algorithm is given below.

  1. For a new value new_value, compute the new count, new mean, the new M2.
  2. mean accumulates the mean of the entire dataset
  3. M2 aggregates the squared distance from the mean
  4. count aggregates the number of samples seen so far

def update(existing_aggregate, new_value): (count, mean, M2) = existing_aggregate count += 1 delta = new_value - mean mean += delta / count delta2 = new_value - mean M2 += delta * delta2 return (count, mean, M2)

  1. Retrieve the mean, variance and sample variance from an aggregate

def finalize(existing_aggregate): (count, mean, M2) = existing_aggregate if count < 2: return float("nan") else: (mean, variance, sample_variance) = (mean, M2 / count, M2 / (count - 1)) return (mean, variance, sample_variance)

This algorithm is much less prone to loss of precision due to catastrophic cancellation, but might not be as efficient because of the division operation inside the loop. For a particularly robust two-pass algorithm for computing the variance, one can first compute and subtract an estimate of the mean, and then use this algorithm on the residuals.

The parallel algorithm below illustrates how to merge multiple sets of statistics calculated online.

Weighted incremental algorithm

The algorithm can be extended to handle unequal sample weights, replacing the simple counter n with the sum of weights seen so far. West (1979)[9] suggests this incremental algorithm:

def weighted_incremental_variance(data_weight_pairs): w_sum = w_sum2 = mean = S = 0

for x, w in data_weight_pairs: w_sum = w_sum + w w_sum2 = w_sum2 + w**2 mean_old = mean mean = mean_old + (w / w_sum) * (x - mean_old) S = S + w * (x - mean_old) * (x - mean)

population_variance = S / w_sum # Bessel's correction for weighted samples # Frequency weights sample_frequency_variance = S / (w_sum - 1) # Reliability weights sample_reliability_variance = S / (w_sum - w_sum2 / w_sum)

Parallel algorithm

Chan et al.[10] note that Welford's online algorithm detailed above is a special case of an algorithm that works for combining arbitrary sets

A

and

B

:

\begin{align} nAB&=nA+nB\\ \delta&=\barxB-\barxA\\ \barxAB&=\barxA+\delta

nB
nAB

\\ M2,AB&=M2,A+M2,B+

2 ⋅ nAnB
nAB
\delta

\\ \end{align}

.This may be useful when, for example, multiple processing units may be assigned to discrete parts of the input.

Chan's method for estimating the mean is numerically unstable when

nAnB

and both are large, because the numerical error in

\delta=\barxB-\barxA

is not scaled down in the way that it is in the

nB=1

case. In such cases, prefer \bar x_ = \frac.def parallel_variance(n_a, avg_a, M2_a, n_b, avg_b, M2_b): n = n_a + n_b delta = avg_b - avg_a M2 = M2_a + M2_b + delta**2 * n_a * n_b / n var_ab = M2 / (n - 1) return var_abThis can be generalized to allow parallelization with AVX, with GPUs, and computer clusters, and to covariance.

Example

Assume that all floating point operations use standard IEEE 754 double-precision arithmetic. Consider the sample (4, 7, 13, 16) from an infinite population. Based on this sample, the estimated population mean is 10, and the unbiased estimate of population variance is 30. Both the naïve algorithm and two-pass algorithm compute these values correctly.

Next consider the sample, which gives rise to the same estimated variance as the first sample. The two-pass algorithm computes this variance estimate correctly, but the naïve algorithm returns 29.333333333333332 instead of 30.

While this loss of precision may be tolerable and viewed as a minor flaw of the naïve algorithm, further increasing the offset makes the error catastrophic. Consider the sample . Again the estimated population variance of 30 is computed correctly by the two-pass algorithm, but the naïve algorithm now computes it as −170.66666666666666. This is a serious problem with naïve algorithm and is due to catastrophic cancellation in the subtraction of two similar numbers at the final stage of the algorithm.

Higher-order statistics

Terriberry[11] extends Chan's formulae to calculating the third and fourth central moments, needed for example when estimating skewness and kurtosis:

\begin{align} M3,X=M3,A+M3,B&{}+

3nAnB(nA-nB)
2
n
X
\delta

+3\delta

nAM2,B-nBM2,A
nX

\\[6pt] M4,X=M4,A+M4,B&{}+

4
nnB
2
\left(n
A
-nAnB+
2\right)
n
B
A
3
n
X
\delta

\\[6pt] &{}+

2
2
nM2,B+
2
n
B
M2,A
A
2
n
X
6\delta

+4\delta

nAM3,B-nBM3,A
nX

\end{align}

Here the

Mk

are again the sums of powers of differences from the mean \sum(x - \overline)^k, giving

\begin{align} &skewness=g1=

\sqrt{n
M

3}{M

3/2
2
}, \\[4pt]& \text = g_2 = \frac-3.\end

For the incremental case (i.e.,

B=\{x\}

), this simplifies to:

\begin{align} \delta&=x-m\\[5pt] m'&=m+

\delta
n

\\[5pt] M2'&=M2+\delta2

n-1
n

\\[5pt] M3'&=M3+\delta3

(n-1)(n-2)
n2

-

3\deltaM2
n

\\[5pt] M4'&=M4+

\delta4(n-1)(n2-3n+3)
n3

+

6\delta2M2
n2

-

4\deltaM3
n

\end{align}

By preserving the value

\delta/n

, only one division operation is needed and the higher-order statistics can thus be calculated for little incremental cost.

An example of the online algorithm for kurtosis implemented as described is:def online_kurtosis(data): n = mean = M2 = M3 = M4 = 0

for x in data: n1 = n n = n + 1 delta = x - mean delta_n = delta / n delta_n2 = delta_n**2 term1 = delta * delta_n * n1 mean = mean + delta_n M4 = M4 + term1 * delta_n2 * (n**2 - 3*n + 3) + 6 * delta_n2 * M2 - 4 * delta_n * M3 M3 = M3 + term1 * delta_n * (n - 2) - 3 * delta_n * M2 M2 = M2 + term1

# Note, you may also calculate variance using M2, and skewness using M3 # Caution: If all the inputs are the same, M2 will be 0, resulting in a division by 0. kurtosis = (n * M4) / (M2**2) - 3 return kurtosis

Pébaÿ[12] further extends these results to arbitrary-order central moments, for the incremental and the pairwise cases, and subsequently Pébaÿ et al.[13] for weighted and compound moments. One can also find there similar formulas for covariance.

Choi and Sweetman[14] offer two alternative methods to compute the skewness and kurtosis, each of which can save substantial computer memory requirements and CPU time in certain applications. The first approach is to compute the statistical moments by separating the data into bins and then computing the moments from the geometry of the resulting histogram, which effectively becomes a one-pass algorithm for higher moments. One benefit is that the statistical moment calculations can be carried out to arbitrary accuracy such that the computations can be tuned to the precision of, e.g., the data storage format or the original measurement hardware. A relative histogram of a random variable can be constructed in the conventional way: the range of potential values is divided into bins and the number of occurrences within each bin are counted and plotted such that the area of each rectangle equals the portion of the sample values within that bin:

H(x
k)=h(xk)
A

where

h(xk)

and

H(xk)

represent the frequency and the relative frequency at bin

xk

and A= \sum_^K h(x_k) \,\Delta x_k is the total area of the histogram. After this normalization, the

n

raw moments and central moments of

x(t)

can be calculated from the relative histogram:
(h)
m
n

=

K
\sum
k=1
n
x
k

H(xk)\Deltaxk =

1
A
K
\sum
k=1
n
x
k

h(xk)\Deltaxk

(h)
\theta
n

=

K
\sum
k=1

(xk-m

(h)
1

)nH(xk)\Deltaxk =

1
A
K
\sum
k=1

(xk-m

(h)
1

)nh(xk)\Deltaxk

where the superscript

(h)

indicates the moments are calculated from the histogram. For constant bin width

\Deltaxk=\Deltax

these two expressions can be simplified using

I=A/\Deltax

:
(h)
m
n

=

1
I
K
\sum
k=1
n
x
k

h(xk)

(h)
\theta
n

=

1
I
K
\sum
k=1

(xk-m

(h)
1

)nh(xk)

The second approach from Choi and Sweetman is an analytical methodology to combine statistical moments from individual segments of a time-history such that the resulting overall moments are those of the complete time-history. This methodology could be used for parallel computation of statistical moments with subsequent combination of those moments, or for combination of statistical moments computed at sequential times.

If

Q

sets of statistical moments are known:

(\gamma0,q,\muq

2
,\sigma
q

,\alpha3,q,\alpha4,q)

for

q=1,2,\ldots,Q

, then each

\gamman

canbe expressed in terms of the equivalent

n

raw moments:

\gamman,q=mn,q\gamma0,q    rm{for}n=1,2,3,4andq=1,2,...,Q

where

\gamma0,q

is generally taken to be the duration of the

qth

time-history, or the number of points if

\Deltat

is constant.

The benefit of expressing the statistical moments in terms of

\gamma

is that the

Q

sets can be combined by addition, and there is no upper limit on the value of

Q

.

\gamman,c=

Q
\sum
q=1

\gamman,qforn=0,1,2,3,4

where the subscript

c

represents the concatenated time-history or combined

\gamma

. These combined values of

\gamma

can then be inversely transformed into raw moments representing the complete concatenated time-history

mn,c=

\gamman,c
\gamma0,c

forn=1,2,3,4

Known relationships between the raw moments (

mn

) and the central moments (

\thetan=\operatornameE[(x-\mu)n])

)are then used to compute the central moments of the concatenated time-history. Finally, the statistical moments of the concatenated history are computed from the central moments:

\muc=m1,c   

2
\sigma
c=\theta

2,c    \alpha3,c=

\theta3,c
3
\sigma
c

   \alpha4,c={

\theta4,c
4
\sigma
c
}-3

Covariance

Very similar algorithms can be used to compute the covariance.

Naïve algorithm

The naïve algorithm is

\operatorname{Cov}(X,Y)=

n
\sumxiyi-
n
(\sum
i=1
xi)(\sum
n
i=1
yi)/n
i=1
n

.

For the algorithm above, one could use the following Python code:def naive_covariance(data1, data2): n = len(data1) sum1 = sum(data1) sum2 = sum(data2) sum12 = sum([i1 * i2 for i1, i2 in zip(data1, data2)])

covariance = (sum12 - sum1 * sum2 / n) / n return covariance

With estimate of the mean

As for the variance, the covariance of two random variables is also shift-invariant, so given any two constant values

kx

and

ky,

it can be written:

\operatorname{Cov}(X,Y)=\operatorname{Cov}(X-kx,Y-ky)=\dfrac

n
{\sum
i=1

(xi-kx)(yi-ky)-

n
(\sum
i=1

(xi-kx))(\sum

n
i=1

(yi-ky))/n}{n}.

and again choosing a value inside the range of values will stabilize the formula against catastrophic cancellation as well as make it more robust against big sums. Taking the first value of each data set, the algorithm can be written as:

def shifted_data_covariance(data_x, data_y): n = len(data_x) if n < 2: return 0 kx = data_x[0] ky = data_y[0] Ex = Ey = Exy = 0 for ix, iy in zip(data_x, data_y): Ex += ix - kx Ey += iy - ky Exy += (ix - kx) * (iy - ky) return (Exy - Ex * Ey / n) / n

Two-pass

The two-pass algorithm first computes the sample means, and then the covariance:

\barx=

n
\sum
i=1

xi/n

\bary=

n
\sum
i=1

yi/n

\operatorname{Cov}(X,Y)=

n
\sum(xi-\barx)(yi-\bary)
i=1
n

.

The two-pass algorithm may be written as:def two_pass_covariance(data1, data2): n = len(data1) mean1 = sum(data1) / n mean2 = sum(data2) / n

covariance = 0 for i1, i2 in zip(data1, data2): a = i1 - mean1 b = i2 - mean2 covariance += a * b / n return covariance

A slightly more accurate compensated version performs the full naive algorithm on the residuals. The final sums \sum_i x_i and \sum_i y_i should be zero, but the second pass compensates for any small error.

Online

A stable one-pass algorithm exists, similar to the online algorithm for computing the variance, that computes co-moment C_n = \sum_^n (x_i - \bar x_n)(y_i - \bar y_n):

\begin{alignat}{2} \barxn&=\barxn-1&+&

xn-\barxn-1
n

\\[5pt] \baryn&=\baryn-1&+&

yn-\baryn-1
n

\\[5pt] Cn&=Cn-1&+&(xn-\barxn)(yn-\baryn-1)\\[5pt] &=Cn-1&+&(xn-\barxn-1)(yn-\baryn) \end{alignat}

The apparent asymmetry in that last equation is due to the fact that (x_n - \bar x_n) = \frac(x_n - \bar x_), so both update terms are equal to \frac(x_n - \bar x_)(y_n - \bar y_). Even greater accuracy can be achieved by first computing the means, then using the stable one-pass algorithm on the residuals.

Thus the covariance can be computed as

\begin{align} \operatorname{Cov}N(X,Y)=

CN
N

&=

\operatorname{Cov
N-1

(X,Y)(N-1)+(xn-\barxn)(yn-\baryn-1)}{N}\\ &=

\operatorname{Cov
N-1

(X,Y)(N-1)+(xn-\barxn-1)(yn-\baryn)}{N}\\ &=

\operatorname{Cov
N-1

(X,Y)(N-1)+

N-1
N

(xn-\barxn-1)(yn-\baryn-1)}{N}\\ &=

\operatorname{Cov
N-1

(X,Y)(N-1)+

N
N-1

(xn-\barxn)(yn-\baryn)}{N}. \end{align}

def online_covariance(data1, data2): meanx = meany = C = n = 0 for x, y in zip(data1, data2): n += 1 dx = x - meanx meanx += dx / n meany += (y - meany) / n C += dx * (y - meany)

population_covar = C / n # Bessel's correction for sample variance sample_covar = C / (n - 1)

A small modification can also be made to compute the weighted covariance:

def online_weighted_covariance(data1, data2, data3): meanx = meany = 0 wsum = wsum2 = 0 C = 0 for x, y, w in zip(data1, data2, data3): wsum += w wsum2 += w * w dx = x - meanx meanx += (w / wsum) * dx meany += (w / wsum) * (y - meany) C += w * dx * (y - meany)

population_covar = C / wsum # Bessel's correction for sample variance # Frequency weights sample_frequency_covar = C / (wsum - 1) # Reliability weights sample_reliability_covar = C / (wsum - wsum2 / wsum)

Likewise, there is a formula for combining the covariances of two sets that can be used to parallelize the computation:

CX=CA+CB+(\barxA-\barxB)(\baryA-\bar

y
B)nAnB
nX

.

Weighted batched version

A version of the weighted online algorithm that does batched updated also exists: let

w1,...wN

denote the weights, and write

\begin{alignat}{2} \barxn+k&=\barxn&+&

n+k
\sumwi(xi-\barxn)
i=n+1
n+k
\sumwi
i=1

\\ \baryn+k&=\baryn&+&

n+k
\sumwi(yi-\baryn)
i=n+1
n+k
\sumwi
i=1

\\ Cn+k&=Cn&+&

n+k
\sum
i=n+1

wi(xi-\barxn+k)(yi-\baryn)\\ &=Cn&+&

n+k
\sum
i=n+1

wi(xi-\barxn)(yi-\baryn+k)\\ \end{alignat}

The covariance can then be computed as

\operatorname{Cov}N(X,Y)=

CN
N
\sumwi
i=1

See also

References

  1. Book: Einarsson, Bo. Accuracy and Reliability in Scientific Computing. 2005. SIAM. 978-0-89871-584-2. 47.
  2. Algorithms for computing the sample variance: Analysis and recommendations. https://ghostarchive.org/archive/20221009/http://cpsc.yale.edu/sites/default/files/files/tr222.pdf . 2022-10-09 . live. Tony F.. Chan. Tony F. Chan. Gene H.. Golub. Gene H. Golub. Randall J.. LeVeque. The American Statistician. 37. 3. 242–247. 1983. 2683386. 10.1080/00031305.1983.10483115.
  3. Book: Schubert. Erich. Gertz. Michael. 2018-07-09. Numerically stable parallel computation of (co-)variance. ACM. 10. 10.1145/3221269.3223036. 9781450365055. 49665540.
  4. Book: Higham, Nicholas J. . Accuracy and Stability of Numerical Algorithms . Society for Industrial and Applied Mathematics . 2002 . 2nd . Philadelphia, PA . Problem 1.10 . 10.1137/1.9780898718027. 978-0-898715-21-7 . e, 2002075848 . Metadata also listed at ACM Digital Library.
  5. B. P. . Welford . 1962 . Note on a method for calculating corrected sums of squares and products . . 4 . 3 . 419–420 . 1266577 . 10.2307/1266577.
  6. [Donald E. Knuth]
  7. Ling . Robert F. . 1974 . Comparison of Several Algorithms for Computing Sample Means and Variances . Journal of the American Statistical Association . 69 . 348 . 859–866 . 10.2307/2286154. 2286154 .
  8. Web site: Cook . John D. . 30 September 2022 . 1 November 2014 . Accurately computing sample variance . John D. Cook Consulting: Expert consulting in applied mathematics & data privacy.
  9. West . D. H. D. . 1979 . Updating Mean and Variance Estimates: An Improved Method . . 22 . 9 . 532–535 . 10.1145/359146.359153 . 30671293 . free.
  10. Web site: Chan . Tony F. . Tony F. Chan . Golub . Gene H. . Gene H. Golub . LeVeque . Randall J. . November 1979 . Updating Formulae and a Pairwise Algorithm for Computing Sample Variances . Department of Computer Science, Stanford University . Technical Report STAN-CS-79-773, supported in part by Army contract No. DAAGEI-‘E-G-013 .
  11. Web site: Terriberry . Timothy B. . 15 October 2008 . 9 December 2007 . Computing Higher-Order Moments Online . dead . https://web.archive.org/web/20140423031833/http://people.xiph.org/~tterribe/notes/homs.html . 23 April 2014 . 5 May 2008.
  12. Web site: Pébay . Philippe Pierre . September 2008 . Sponsoring Org.: USDOE . Formulas for Robust, One-Pass Parallel Computation of Covariances and Arbitrary-Order Statistical Moments . Sandia National Laboratories (SNL) . Albuquerque, NM, and Livermore, CA (United States) . UNT Digital Library . 10.2172/1028931 . 1028931 . Technical Report SAND2008-6212, TRN: US201201%%57, DOE Contract Number: AC04-94AL85000 . free.
  13. Pébaÿ . Philippe . Terriberry . Timothy . Kolla . Hemanth . Bennett . Janine . 2016 . Numerically Stable, Scalable Formulas for Parallel and Online Computation of Higher-Order Multivariate Central Moments with Arbitrary Weights . Computational Statistics . 31 . 4 . 1305–1325 . Springer . 10.1007/s00180-015-0637-z . 124570169 .
  14. Choi . Myoungkeun . Sweetman . Bert . 17534100 . 2010 . Efficient Calculation of Statistical Moments for Structural Health Monitoring . Journal of Structural Health Monitoring . 9 . 1 . 13–24 . 10.1177/1475921709341014.