Overview
Variance asks how far the values sit from their mean, on average, after squaring. Squaring makes every deviation positive and gives large deviations more say. The result is in squared units, such as square metres for lengths, which is why people quote its square root, the standard deviation, when describing data. Variance earns its place for a different reason: it adds up. The variance of a sum of independent quantities is the sum of their variances, and the total variation in a dataset splits exactly into a part inside groups and a part between groups. Those two facts sit under ANOVA, R squared, PCA and the handling of measurement error.
A short history
The idea of mean squared deviation goes back to the theory of errors of Gauss and Laplace in the early nineteenth century. Ronald Fisher introduced the word variance in 1918, in his paper The Correlation between Relatives on the Supposition of Mendelian Inheritance, because he needed a measure of spread that could be split into parts due to different causes. That additive property led directly to the analysis of variance.
How it works
- Compute the mean of the values, ignoring NaN entries.
- Subtract the mean from each value and square the result.
- Add the squares and divide by for a sample (ddof 1) or by for a whole population (ddof 0).
- To study a sum of two paired variables, use of_sum, which returns both variances, their covariance and the variance of the sum.
- To split variation by a grouping, use decompose, which returns the total, within-group and between-group sums of squares.
- For data in chunks or streams, use RunningVariance. It updates in one pass and merge combines two partial results exactly.
Watch out for
- The unit is the square of the data's unit, so a variance cannot be compared directly with the mean or read on the original scale.
- Outliers dominate it, because each deviation is squared. A single extreme value can account for most of the total.
- Variances add only when the variables are uncorrelated. If they move together, the covariance term must be included or the result is wrong.
- Dividing by on a sample gives an estimate that is too small on average, by the factor .
- A variance from very few values is itself very uncertain, so differences between small-sample variances are often noise.
Use cases
When to use it
Wherever spread enters a formula: ANOVA, R squared, PCA, portfolio risk, error propagation, standardising features. To describe spread to a reader, quote the standard deviation instead.
In industry
- Genetics and agriculture
- Breeders split the variance of a trait into genetic and environmental parts to estimate heritability, the use for which Fisher introduced the term.
- Machine learning
- Model error is analysed as bias plus variance, and principal component analysis reports the share of total variance each component explains.
- Experimentation
- A/B testing teams estimate the variance of a metric to work out how many users a test needs to detect a given difference.
Choosing it: what must hold
- Interval or ratio data for which a mean exists and is a sensible centre.
- A use that benefits from additivity, such as combining independent sources of error or splitting spread across groups.
- Awareness that the result is in squared units and is highly sensitive to outliers.
When to choose something else
| If | Use instead |
|---|---|
| You need spread in the data's own unit to report to people | Standard deviation |
| The data are skewed or have outliers | Quartiles and IQR |
| You want to test whether group means differ using variance components | One-way ANOVA |
Math foundations
Sample variance
The average squared deviation from the mean. The divisor counts the deviations that are free to vary once the mean is fixed.
Why n minus 1
Averaged over many samples, with the divisor equals the true variance. With the divisor the average would be , which is too small.
Variance of a sum
The spread of a sum is the two spreads plus a term for how the variables move together. When they are uncorrelated the last term is zero and variances simply add.
Splitting variation by groups
Total sum of squares equals within-group plus between-group. The split is exact, and the between share of the total is the fraction of variance the grouping explains (eta squared).
Merging two partial results
The sum of squared deviations of two chunks combined, from each chunk's count, mean and sum of squares. It is the group split above with two groups, and it lets variance be computed in parallel.
Symbols
- the i-th value
- the mean of all values
- number of values
- the sample variance and the true population variance
- the average over many repeated samples
- two paired variables
- mean and size of group g
- sums of squared deviations of chunk a and chunk b, each about its own mean
- means and sizes of the two chunks
Worked by hand
Eight values in two chunks: a holds 2, 4, 4, 4 (mean 3.5) and b holds 5, 5, 7, 9 (mean 6.5). Compute the variance of all eight by merging.
The merged sum of squares is 32, the same as computing it directly about the overall mean of 5. Of that, 14 lies within the chunks and 18 between them.
Visual example
Loading the example.
Try this
- Drag the value at 9 out to 12: its square grows much faster than its distance does.
- Press Push the groups together until the two group means meet, and watch the between part vanish.
- Switch between dividing by n and by n minus 1 and compare the two variances.
Code sample
import numpy as np
from impl import Variance, RunningVariance
from config import VarianceConfig
x = [2, 4, 4, 4, 5, 5, 7, 9]
print(Variance(VarianceConfig(ddof=0)).variance(x)) # 4.0
print(Variance().variance(x)) # 4.571 (sample)
print(Variance.decompose([1, 2, 3, 2, 3, 4], ["a", "a", "a", "b", "b", "b"]))
acc = RunningVariance().update(x[:4]).merge(RunningVariance().update(x[4:]))
print(acc.variance) # 4.571Read the implementation (114 lines)
"""Variance: the mean squared deviation from the mean.
NumPy only. Besides the plain estimate this template shows the two identities that make variance the workhorse of
statistics: the variance of a sum (var(x + y) = var(x) + var(y) + 2 cov(x, y)) and the split of total variation
into within-group and between-group parts (the basis of ANOVA and of R squared). `RunningVariance` computes the
variance in one pass and can merge the results of separate chunks.
"""
from __future__ import annotations
import numpy as np
try:
from .config import VarianceConfig
except ImportError: # run from the template's own folder
from config import VarianceConfig
class Variance:
"""Sample or population variance and its decompositions."""
def __init__(self, config: VarianceConfig | None = None) -> None:
self.config = config or VarianceConfig()
def variance(self, values) -> np.ndarray | float:
"""Variance of values (any shape) over config.axis; NaN entries are ignored.
Returns a float when config.axis is None, otherwise an array with that axis removed.
"""
x = np.asarray(values, dtype=float)
axis = self.config.axis
n = np.sum(~np.isnan(x), axis=axis)
if np.any(n - self.config.ddof <= 0):
raise ValueError("not enough values for the chosen ddof")
mean = np.nanmean(x, axis=axis, keepdims=True)
result = np.nansum((x - mean) ** 2, axis=axis) / (n - self.config.ddof)
return float(result) if np.ndim(result) == 0 else result
def of_sum(self, x, y) -> dict:
"""Parts of var(x + y) for paired x and y of shape (n,).
Returns {"var_x", "var_y", "covariance", "var_sum"} with var_sum = var_x + var_y + 2 * covariance.
The covariance term vanishes only when x and y are uncorrelated.
"""
x = np.asarray(x, dtype=float).ravel()
y = np.asarray(y, dtype=float).ravel()
if x.size != y.size:
raise ValueError(f"x and y must have the same length, got {x.size} and {y.size}")
if x.size - self.config.ddof <= 0:
raise ValueError("not enough values for the chosen ddof")
covariance = float(((x - x.mean()) * (y - y.mean())).sum() / (x.size - self.config.ddof))
flat = Variance(VarianceConfig(ddof=self.config.ddof, axis=None))
var_x, var_y = flat.variance(x), flat.variance(y)
return {"var_x": var_x, "var_y": var_y, "covariance": covariance, "var_sum": var_x + var_y + 2.0 * covariance}
@staticmethod
def decompose(values, groups) -> dict:
"""Split the total sum of squares into within-group and between-group parts.
values: shape (n,) numbers. groups: shape (n,) group label of each value.
Returns {"total", "within", "between", "explained"} where total = within + between (sums of squared
deviations) and explained = between / total is the share of variance the grouping accounts for
(eta squared).
"""
x = np.asarray(values, dtype=float).ravel()
labels = np.asarray(groups).ravel()
if x.size != labels.size or x.size == 0:
raise ValueError("values and groups must have the same non-zero length")
grand_mean = x.mean()
within = between = 0.0
for label in np.unique(labels):
member = x[labels == label]
within += float(((member - member.mean()) ** 2).sum())
between += member.size * float((member.mean() - grand_mean) ** 2)
total = float(((x - grand_mean) ** 2).sum())
return {"total": total, "within": within, "between": between, "explained": between / total if total else 0.0}
class RunningVariance:
"""One-pass variance (Welford) that can also merge two partial results (Chan, Golub and LeVeque)."""
def __init__(self, ddof: int = 1) -> None:
if ddof not in (0, 1):
raise ValueError(f"ddof must be 0 or 1, got {ddof}")
self.ddof = ddof
self.n = 0
self.mean = 0.0
self.sum_squares = 0.0 # sum of squared deviations from the current mean
def update(self, values) -> "RunningVariance":
"""Add one number or an array of numbers. Returns self."""
for value in np.asarray(values, dtype=float).ravel():
self.n += 1
delta = value - self.mean
self.mean += delta / self.n
self.sum_squares += delta * (value - self.mean)
return self
def merge(self, other: "RunningVariance") -> "RunningVariance":
"""Fold another accumulator into this one, as if its values had been fed here. Returns self."""
if other.n == 0:
return self
n = self.n + other.n
delta = other.mean - self.mean
self.sum_squares += other.sum_squares + delta * delta * self.n * other.n / n
self.mean += delta * other.n / n
self.n = n
return self
@property
def variance(self) -> float:
"""Variance of everything seen so far."""
if self.n - self.ddof <= 0:
raise ValueError("not enough values for the chosen ddof")
return self.sum_squares / (self.n - self.ddof)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Compute Variance().variance on 2, 4, 4, 4, 5, 5, 7, 9, then reproduce it with RunningVariance().update on the first four values merged with a second RunningVariance on the last four. Call Variance.decompose on the same values with group labels a and b and check that within plus between equals total.
Check on learning
- You measure a length as the sum of two independent measurements, each with a variance of 4. What is the variance of the sum, and why is its standard deviation not 4?
A way to think about it
Variances add for independent quantities. Standard deviations do not. Take the square root at the end.
- Averaging independent measurements divides the variance by . Derive that from the sum rule, and say what breaks if the measurements share a common error.
A way to think about it
The variance of a constant times a variable is the constant squared times the variance. A shared error adds positive covariance terms that do not average away.
- In decompose, the between-group part is 90 percent of the total. What does that say about the groups, and what would 2 percent say?
A way to think about it
Think about how well knowing the group alone lets you guess a value.
- Two stocks each have a variance of 0.04. Under what relation between them does a half-and-half portfolio have a variance of zero, and under what relation does it gain nothing?
A way to think about it
Write out the variance of the weighted sum and consider correlations of -1 and 1.
- Why can two chunks be merged exactly without revisiting their values, and why does that matter for data too large for one machine?
A way to think about it
The merge formula needs only three numbers per chunk. Ask what each machine must send to the others.