Expectation and Variance of an Estimator, With Model Examples
Understand bias, variance and mean squared error of estimators through accuracy scores, shrinkage, ensembles and mini-batches.
Key takeaways
- Bias is the gap between an estimator's average value and the quantity it targets, and variance is its spread around that average.
- Mean squared error equals squared bias plus variance.
- The variance of an average of n independent values is the single-value variance divided by n, so the standard error shrinks like 1/√n.
- A slightly biased estimator can have a much smaller total error than an unbiased one.
- Choosing the best of several noisy scores produces an optimistic estimate of the winner.
An estimator is a rule that turns data into a guess about an unknown quantity. Because the data are random, so is the guess. Its expectation tells you where it lands on average across many hypothetical datasets, and its variance tells you how much it jumps from one dataset to another.
Test accuracy, a mini-batch gradient, a fitted weight and a cross-validation score are all estimators. Asking these two questions about each of them explains a great deal about why results wobble.
The definitions
Let θ be the quantity you want and θ̂ your estimator. The expectation E is taken over the randomness in the data (and in the algorithm, if it is random).
bias(θ̂) = E[θ̂] − θ
Var(θ̂) = E[ (θ̂ − E[θ̂])² ]
MSE(θ̂) = E[ (θ̂ − θ)² ] = bias² + Var The last line follows from writing θ̂ − θ as (θ̂ − E[θ̂]) + (E[θ̂] − θ), squaring, and noting that the cross term averages to zero. The standard error is the standard deviation of an estimator.
These are properties of the procedure, not of the single number you computed. One estimate cannot be "biased" by itself. It can only come from a rule that is.
Two rules do most of the work. Expectation is linear: E[aX + bY] = aE[X] + bE[Y], whether or not X and Y are independent. Variance is not: Var(aX + bY) = a²Var(X) + b²Var(Y) + 2ab Cov(X, Y), where the covariance Cov measures how the two move together.
The sample mean and sample variance
Draw n independent values with mean μ and variance σ². Their average x̄ has:
E[x̄] = μ unbiased
Var(x̄) = σ² / n
standard error = σ / √n To halve the standard error, you need four times as much data. To cut it tenfold, a hundred times.
The variance itself is trickier. Averaging the squared distances from x̄ gives a result whose expectation is σ²(n − 1)/n, slightly too small, because x̄ was chosen to be close to these very points. Dividing by n − 1 instead of n removes the bias, for n ≥ 2. NumPy's var divides by n by default, and its ddof argument changes the divisor.
Accuracy is an estimator
On n independent test examples, each prediction is right with probability p, the true accuracy on that distribution. The observed accuracy p̂ is unbiased with variance p(1 − p)/n.
With p = 0.9 and n = 400, the standard error is √(0.09/400) = 0.015. A rough 95% range is about plus or minus 0.03, so an observed 0.91 against a rival's 0.89 on separate test sets of this size is weak evidence. The normal approximation behind that range gets poor when p is near 0 or 1 or n is small.
Independence is essential. If the 400 examples are 20 photographs each of 20 objects, the effective sample is much smaller than 400. Confidence intervals for test metrics and bootstrap resampling show how to put ranges on scores.
Trading bias for variance
Suppose you estimate a mean μ with c · x̄, where c is between 0 and 1. This shrinks the estimate toward zero.
bias = (c − 1) μ
Var = c² σ² / n
MSE = (1 − c)² μ² + c² σ² / n Take μ = 1, σ² = 4 and n = 4, so Var(x̄) = 1.
| c | Squared bias | Variance | MSE |
|---|---|---|---|
| 1.0 | 0.00 | 1.00 | 1.00 |
| 0.75 | 0.06 | 0.56 | 0.63 (rounded) |
| 0.5 | 0.25 | 0.25 | 0.50 |
| 0.0 | 1.00 | 0.00 | 1.00 |
Half the unbiased estimate has half the error. The best factor here is μ²/(μ² + σ²/n) = 0.5. It depends on the unknown μ, so in practice you tune the amount of shrinkage on data. This is the logic of ridge regression, and the same decomposition applied to predictions appears in the bias-variance tradeoff.
Averaging correlated models
Ensembles average predictions to reduce variance. Suppose M predictors each have variance σ² at some input, and every pair has correlation ρ ≥ 0.
Var(average) = ρσ² + (1 − ρ) σ² / M
σ² = 1, ρ = 0.5, M = 10: 0.5 + 0.05 = 0.55 Adding members shrinks only the second term. The floor ρσ² stays, which is why random forests work to decorrelate their trees by sampling both rows and features. Averaging does nothing to a bias that all members share.
Mini-batch gradients
The gradient of the average training loss is a mean over all examples. A mini-batch of B examples drawn uniformly at random gives an unbiased estimator of it, with variance roughly proportional to 1/B when the batch is small compared with the dataset.
Quadrupling the batch halves the gradient noise and quadruples the work per step. That square root explains why very large batches give diminishing returns.
Sample some examples more often than others and the plain average becomes biased. You can restore the target by weighting each sampled loss by the ratio of the intended probability to the sampling probability. This importance weighting is unbiased when every relevant example has a nonzero chance of selection, but rare large weights can make its variance huge.
The winner's score is biased upward
Each validation score is true performance plus noise. When you pick the highest of many, you favor candidates whose noise happened to be positive.
Suppose two models have identical true accuracy and their scores carry independent Gaussian noise with standard error 0.015. The expected value of the larger of two such scores exceeds the truth by about 0.564 standard errors, here roughly 0.0085. With dozens of configurations the inflation grows. Scores on a shared test set are correlated, which changes the amount, but the direction remains.
The cure is a fresh set that played no part in the choice, as set out in the jobs of training, validation and test sets. See also multiple comparisons.
Comparing two models on the same examples
Often the quantity you care about is a difference. If two classifiers are scored on the same test set, their accuracies are correlated, because easy examples are easy for both. Look at the per-example difference in correctness, which is −1, 0 or 1.
Say there are 1,000 examples. Model A alone is right on 40 of them, model B alone on 20, and on the remaining 940 they agree.
mean difference = (40 − 20) / 1000 = 0.020
mean squared difference = (40 + 20) / 1000 = 0.060
variance of one difference ≈ 0.060 − 0.020² = 0.0596
standard error of the mean ≈ √(0.0596 / 1000) ≈ 0.0077 The gap of 0.02 is about 2.6 standard errors. Had you treated the two scores as independent, each with accuracy near 0.9, the standard error of the gap would have come out near 0.013, and the same improvement would have looked much less certain. Pairing removes the noise the two models share. Tests for comparing two models develops this into formal procedures.
Cross-validation scores
A k-fold cross-validation score averages k results, but they are not independent. The training sets overlap heavily, so the fold scores tend to be correlated. Dividing their standard deviation by √k therefore gives an error bar that should be read as rough, and often too narrow.
The estimator also targets something slightly different from what you may want. It describes the performance of the training procedure on somewhat smaller training sets, averaged over folds, not the error of the one model you finally ship. With little data, training on a smaller set can make the estimate pessimistic.
Repeating the whole procedure with new fold assignments reduces the noise that comes from the split. It cannot reduce the uncertainty that comes from having only these examples.
Simulate it
When algebra gets hard, simulate many datasets and look at the spread.
import numpy as np
rng = np.random.default_rng(0)
x = rng.normal(loc=1.0, scale=2.0, size=(200_000, 4)) # (trials, n)
means = x.mean(axis=1) # one estimate per trial
for c in [1.0, 0.75, 0.5]:
print(c, np.mean((c*means - 1.0)**2)) # near 1.00, 0.625, 0.50
print(x.var(axis=1).mean(), x.var(axis=1, ddof=1).mean()) # near 3 and 4 In real work you have one dataset, so you cannot redraw it. Resampling it, or repeating training with different seeds and splits, gives a partial view of the variability.
Common confusions
- Unbiased does not mean accurate. The first test example alone gives an unbiased estimate of accuracy, and a useless one.
- Consistent differs from unbiased. A consistent estimator converges to the target as n grows, even if it is biased at every finite n.
- More data does not remove every bias. A test set collected from the wrong population stays wrong at any size.
- Spread across seeds is only one source. It omits the variation from which examples you happened to collect.
When you report a number, report what kind of repetition its error bar describes.
Common questions
Is a standard deviation across five seeds the standard error?
No. The standard deviation describes how single runs scatter. The standard error of the average of five independent runs is that figure divided by √5. State which one you show, and remember that five values give only a coarse estimate of either.
Should I prefer an unbiased estimator?
Not automatically. If your goal is to be close to the truth on the data you have, mean squared error or the cost of the resulting decision matters more. Unbiasedness is valuable when you will average many estimates, as with mini-batch gradients over thousands of steps, because noise cancels and a systematic offset does not.
Does a larger test set fix an optimistic score?
It shrinks the noise, and with it the size of the selection effect. It does not undo leakage, duplicated examples or a mismatch between the test data and the data the model will meet in use.