Overview
A sample is a small window onto a population. An estimator is a rule that turns the sample into a guess at some unknown number, called a parameter, such as the population mean. Different samples give different guesses, so an estimator is itself a random quantity with a centre and a spread. A good one is centred on the truth (low bias) and does not scatter much (low variance). A point estimate is a single guess. An interval estimate is a range built so that, over many repetitions, it would contain the truth a stated share of the time. Estimation theory also sets a floor: no unbiased rule can have variance below the Cramer-Rao bound.
A short history
Gauss and Legendre introduced least squares around 1800 to combine astronomical observations. Ronald Fisher's 1922 paper On the Mathematical Foundations of Theoretical Statistics set out maximum likelihood and the criteria of consistency, efficiency and sufficiency for judging an estimator. Jerzy Neyman gave the theory of confidence intervals in 1937, and C. R. Rao and Harald Cramér found in the mid 1940s the lower bound on the variance of any unbiased estimator.
How it works
- Choose the parameter you want and an estimator , a function of the sample.
- Compute point estimates: the sample mean, the sample variance with divisor or , and the standard error of the mean.
- Where a model is assumed, find the maximum likelihood estimate, the parameter value that makes the observed sample most probable.
- Build a confidence interval: estimate plus and minus a quantile times the standard error, using when is known and Student's when it is not.
- Judge an estimator by simulation: draw many samples, apply the rule to each, and measure bias, variance and mean squared error.
- Compare its variance with the Cramer-Rao bound to see how close it is to the best possible.
Watch out for
- A 95% confidence interval does not mean the parameter has a 95% chance of lying in this particular interval. The 95% describes the procedure over repeated samples.
- The Wald interval for a proportion can extend past 0 or 1 and covers poorly for small or extreme proportions, which is why the template defaults to the Wilson interval.
- The chi-square interval for a variance relies on the population being normal and is badly off for heavy-tailed data.
- An unbiased estimator is not automatically the better one. A slightly biased rule with much smaller variance can have lower mean squared error.
fisher_informationuses a finite difference and a Monte Carlo average, so its result carries simulation noise and should be compared with a bound loosely.
Use cases
When to use it
Whenever you report a number computed from data and need to say how far it may be from the truth, and when you have to choose between competing ways of estimating the same thing.
In industry
- Polling
- Polling organisations estimate a population share from a sample and publish it with a margin of error, which is a confidence interval.
- Signal processing and navigation
- Radar and satellite positioning systems estimate range and position from noisy measurements using maximum likelihood and least squares.
- Machine learning
- Training most models is estimation: fitting logistic regression or a neural network by minimising cross entropy is maximum likelihood.
Choosing it: what must hold
- A clearly defined population quantity to estimate, such as a mean, a proportion or a model parameter.
- A sample that represents the population, ideally drawn at random.
- A probability model or at least assumptions that justify the estimator and its margin of error.
- Enough observations for large sample results to apply when the interval relies on them.
When to choose something else
| If | Use instead |
|---|---|
| You need a yes or no decision about a specific claim | Hypothesis testing |
| You have strong prior knowledge or very little data | Bayesian estimation with a prior and a credible interval |
| No formula exists for the estimator's standard error | The bootstrap |
Math foundations
Bias, variance and mean squared error
The average squared miss splits into a systematic part and a random part. This is the yardstick for comparing estimators, and it shows why trading a little bias for a large drop in variance can pay.
Sample mean and variance
The sample mean is unbiased for the population mean. Dividing by makes unbiased for the population variance. Dividing by instead gives the maximum likelihood estimate under a normal model, which is too small on average by the factor .
Maximum likelihood
Pick the parameter under which the observed data are most probable. For a normal sample this gives the mean and the divisor- variance, for an exponential sample the rate , and for a Poisson sample the mean .
Confidence interval for a mean
The standard error measures how much the sample mean varies. The quantile widens the interval to pay for estimating from the same data. When is known, replace by and the quantile by the normal quantile .
Wilson interval for a proportion
Found by solving for the proportions that a test would not reject. Its centre is pulled from toward one half, and it always stays inside 0 and 1.
Fisher information and the Cramer-Rao bound
Fisher information measures how sharply the likelihood reacts to a change in , so how much one observation tells you. The bound holds for every unbiased estimator from independent observations. An estimator that reaches it is called efficient.
Symbols
- the unknown parameter
- an estimator of the parameter
- the sample values and the sample size
- sample mean and sample variance
- the model's density or probability function
- one minus the confidence level, for example 0.05 for 95%
- quantile q of Student's t with nu degrees of freedom and of the standard normal
- the normal quantile for the chosen confidence, 1.96 for 95%
- sample proportion, successes over n
- population standard deviation
- Fisher information of one observation
Worked by hand
Sample: , so . Find the point estimates and a 95% confidence interval for the mean. The table gives .
The best single guess for the mean is 8, and the 95% interval runs from about 4.07 to 11.93. The interval is wide because five values say little about the spread.
Visual example
Loading the example.
Try this
- Press Draw new samples a few times: the count of misses changes, the long-run share barely does.
- Set n to 3 and compare the two averages of s²: dividing by n falls well short of 100.
- Raise the confidence level to 0.99 and watch every interval widen to keep its promise.
Code sample
import numpy as np
from impl import Estimator
from config import EstimationTheoryConfig
est = Estimator(EstimationTheoryConfig(confidence=0.95))
x = np.array([4.0, 6.0, 5.0, 7.0, 3.0, 5.0, 6.0, 4.0, 5.0, 5.0])
print(est.point_estimates(x)["mean"], est.mean_interval(x)) # 5.0, (4.174, 5.826)
print(est.proportion_interval(successes=18, n=40))
study = est.bias_variance_mse(np.median, lambda rng: rng.normal(0, 1, 20), true_value=0.0)
print(study["bias"], study["variance"])Read the implementation (267 lines)
"""Estimation theory: point estimators, interval estimators, and how to judge an estimator.
NumPy and the standard library only. The normal, Student t and chi-square quantiles the intervals need are
computed in this file (incomplete beta and gamma functions plus bisection).
"""
from __future__ import annotations
import math
from typing import Callable
import numpy as np
try:
from .config import EstimationTheoryConfig
except ImportError: # run from the template's own folder
from config import EstimationTheoryConfig
def _betacf(a: float, b: float, x: float) -> float:
"""Continued fraction of the incomplete beta function (modified Lentz method)."""
tiny = 1e-300
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
d = 1.0 / (d if abs(d) > tiny else tiny)
h = d
for m in range(1, 2000):
m2 = 2 * m
for aa in (
m * (b - m) * x / ((qam + m2) * (a + m2)),
-(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)),
):
d = 1.0 + aa * d
d = 1.0 / (d if abs(d) > tiny else tiny)
c = 1.0 + aa / c
c = c if abs(c) > tiny else tiny
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-15:
break
return h
def betainc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b), for a, b > 0 and 0 <= x <= 1."""
if x <= 0.0:
return 0.0
if x >= 1.0:
return 1.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x)
)
if x < (a + 1.0) / (a + b + 2.0):
return front * _betacf(a, b, x) / a
return 1.0 - front * _betacf(b, a, 1.0 - x) / b
def gammaincc(a: float, x: float) -> float:
"""Regularized upper incomplete gamma function Q(a, x) = 1 - P(a, x), for a > 0 and x >= 0."""
if x <= 0.0:
return 1.0
log_front = a * math.log(x) - x - math.lgamma(a)
if x < a + 1.0: # series for P
term = total = 1.0 / a
n = a
for _ in range(10000):
n += 1.0
term *= x / n
total += term
if abs(term) < abs(total) * 1e-16:
break
return 1.0 - total * math.exp(log_front)
tiny = 1e-300 # continued fraction for Q (modified Lentz method)
b = x + 1.0 - a
c = 1.0 / tiny
d = 1.0 / b
h = d
for i in range(1, 10000):
an = -i * (i - a)
b += 2.0
d = an * d + b
d = 1.0 / (d if abs(d) > tiny else tiny)
c = b + an / c
c = c if abs(c) > tiny else tiny
delta = d * c
h *= delta
if abs(delta - 1.0) < 1e-15:
break
return h * math.exp(log_front)
def norm_cdf(z: float) -> float:
"""P(Z <= z) for a standard normal Z."""
return 0.5 * math.erfc(-z / math.sqrt(2.0))
def norm_sf(z: float) -> float:
"""P(Z > z) for a standard normal Z (the upper tail)."""
return 0.5 * math.erfc(z / math.sqrt(2.0))
def t_cdf(t: float, df: float) -> float:
"""P(T <= t) for Student's t with `df` degrees of freedom."""
tail = 0.5 * betainc(0.5 * df, 0.5, df / (df + t * t))
return 1.0 - tail if t > 0 else tail
def t_sf(t: float, df: float) -> float:
"""P(T > t) for Student's t with `df` degrees of freedom."""
return t_cdf(-t, df)
def chi2_sf(x: float, df: float) -> float:
"""P(X > x) for a chi-square variable with `df` degrees of freedom."""
return gammaincc(0.5 * df, 0.5 * x) if x > 0 else 1.0
def chi2_cdf(x: float, df: float) -> float:
"""P(X <= x) for a chi-square variable with `df` degrees of freedom."""
return 1.0 - chi2_sf(x, df)
def _bisect(fn, lo: float, hi: float) -> float:
"""Root of the increasing function `fn` on [lo, hi], by bisection."""
for _ in range(100):
mid = 0.5 * (lo + hi)
if fn(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def norm_ppf(p: float) -> float:
"""Quantile of the standard normal: the z with P(Z <= z) = p, for 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError(f"p must be in (0, 1), got {p}")
if p > 0.5:
return -norm_ppf(1.0 - p)
return _bisect(lambda z: norm_cdf(z) - p, -40.0, 0.0)
def t_ppf(p: float, df: float) -> float:
"""Quantile of Student's t: the t with P(T <= t) = p, for 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError(f"p must be in (0, 1), got {p}")
if p > 0.5:
return -t_ppf(1.0 - p, df)
lo = -1.0
while t_cdf(lo, df) > p:
lo *= 2.0
return _bisect(lambda t: t_cdf(t, df) - p, lo, 0.0)
def chi2_ppf(p: float, df: float) -> float:
"""Quantile of the chi-square distribution: the x with P(X <= x) = p, for 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError(f"p must be in (0, 1), got {p}")
hi = max(1.0, df)
while chi2_cdf(hi, df) < p:
hi *= 2.0
return _bisect(lambda x: chi2_cdf(x, df) - p, 0.0, hi)
class Estimator:
"""Point and interval estimates for a sample, and Monte Carlo tools to study any estimator."""
def __init__(self, config: EstimationTheoryConfig | None = None) -> None:
self.config = config or EstimationTheoryConfig()
# ---- point estimation -------------------------------------------------------------------------
def point_estimates(self, x) -> dict:
"""Mean, variance (with the configured ddof), standard deviation and standard error of the mean.
x: sample, shape (n,).
"""
x = np.asarray(x, dtype=float).ravel()
if x.size < 2:
raise ValueError("need at least 2 observations")
var = float(x.var(ddof=self.config.ddof))
return {"n": x.size, "mean": float(x.mean()), "variance": var, "std": math.sqrt(var),
"standard_error": float(x.std(ddof=1)) / math.sqrt(x.size)}
@staticmethod
def mle_normal(x) -> dict:
"""Maximum likelihood estimates for a normal sample: the mean, and the variance with divisor n."""
x = np.asarray(x, dtype=float).ravel()
return {"mean": float(x.mean()), "variance": float(x.var(ddof=0))}
@staticmethod
def mle_exponential(x) -> float:
"""Maximum likelihood estimate of the rate of an exponential distribution: 1 / sample mean."""
return 1.0 / float(np.mean(x))
@staticmethod
def mle_poisson(x) -> float:
"""Maximum likelihood estimate of the Poisson mean: the sample mean."""
return float(np.mean(x))
# ---- interval estimation ----------------------------------------------------------------------
def mean_interval(self, x, sigma: float | None = None) -> tuple[float, float]:
"""Confidence interval for the population mean.
x: sample, shape (n,).
sigma: the known population standard deviation. When given, a z interval is used; when None,
the sample standard deviation and Student's t with n - 1 degrees of freedom.
"""
x = np.asarray(x, dtype=float).ravel()
n = x.size
upper = 0.5 + 0.5 * self.config.confidence
if sigma is not None:
half = norm_ppf(upper) * sigma / math.sqrt(n)
else:
if n < 2:
raise ValueError("need at least 2 observations when sigma is unknown")
half = t_ppf(upper, n - 1) * float(x.std(ddof=1)) / math.sqrt(n)
return float(x.mean()) - half, float(x.mean()) + half
def variance_interval(self, x) -> tuple[float, float]:
"""Confidence interval for the variance of a normal population, from the chi-square distribution."""
x = np.asarray(x, dtype=float).ravel()
n = x.size
if n < 2:
raise ValueError("need at least 2 observations")
ss = float(np.sum((x - x.mean()) ** 2))
tail = 0.5 * (1.0 - self.config.confidence)
return ss / chi2_ppf(1.0 - tail, n - 1), ss / chi2_ppf(tail, n - 1)
def proportion_interval(self, successes: int, n: int) -> tuple[float, float]:
"""Confidence interval for a proportion from `successes` out of `n` trials."""
if n <= 0 or not 0 <= successes <= n:
raise ValueError("need n > 0 and 0 <= successes <= n")
z = norm_ppf(0.5 + 0.5 * self.config.confidence)
p = successes / n
if self.config.proportion_method == "wald":
half = z * math.sqrt(p * (1.0 - p) / n)
return max(0.0, p - half), min(1.0, p + half)
denom = 1.0 + z * z / n
centre = (p + z * z / (2.0 * n)) / denom
half = z * math.sqrt(p * (1.0 - p) / n + z * z / (4.0 * n * n)) / denom
return max(0.0, centre - half), min(1.0, centre + half)
# ---- judging an estimator ---------------------------------------------------------------------
def bias_variance_mse(self, estimator: Callable, sampler: Callable, true_value: float) -> dict:
"""Monte Carlo bias, variance and mean squared error of an estimator.
estimator: function taking a sample (n,) and returning a number.
sampler: function taking a numpy Generator and returning one sample (n,).
true_value: the parameter the estimator aims at.
Uses `trials` samples. The returned values satisfy mse = bias^2 + variance.
"""
rng = np.random.default_rng(self.config.seed)
values = np.array([estimator(sampler(rng)) for _ in range(self.config.trials)], dtype=float)
bias = float(values.mean()) - true_value
variance = float(values.var())
return {"mean": float(values.mean()), "bias": bias, "variance": variance,
"mse": float(np.mean((values - true_value) ** 2))}
def fisher_information(self, log_pdf: Callable, theta: float, sampler: Callable, step: float = 1e-4) -> float:
"""Fisher information of one observation, I(theta) = E[(d/d theta log f(X; theta))^2].
log_pdf: function (x array, theta) -> log density of each x, same shape as x.
sampler: function taking a numpy Generator and returning draws (m,) from the model at `theta`.
The score is a central finite difference with the given step; the expectation is an average
over `trials` batches from the sampler.
"""
rng = np.random.default_rng(self.config.seed)
x = np.concatenate([np.asarray(sampler(rng), dtype=float).ravel() for _ in range(self.config.trials)])
score = (log_pdf(x, theta + step) - log_pdf(x, theta - step)) / (2.0 * step)
return float(np.mean(score**2))
@staticmethod
def cramer_rao_bound(fisher_information: float, n: int) -> float:
"""Lowest variance any unbiased estimator can reach from n independent observations: 1 / (n I)."""
if fisher_information <= 0 or n <= 0:
raise ValueError("fisher_information and n must be positive")
return 1.0 / (n * fisher_information)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
With Estimator(), call point_estimates and mean_interval on the worked sample and check them. Then use bias_variance_mse with a sampler that draws 10 normal values of variance 4 to compare np.var with ddof=0 and with ddof=1 as estimators of 4. Which has the smaller bias, and which the smaller mse?
Check on learning
- The divisor- variance estimate is biased but often has lower mean squared error than the divisor- one for normal data. How can a biased estimator be closer to the truth on average?
A way to think about it
Use the decomposition of mean squared error. Dividing by a larger number shrinks every estimate, which lowers the variance of the estimator as well as shifting its centre.
- To halve the width of a confidence interval for a mean, roughly how much more data do you need, and why not twice as much?
A way to think about it
Find where appears in the standard error and solve for the that makes it half as large.
- You observe 10 successes in 10 trials. What does the Wald interval give, and why is that answer not believable?
A way to think about it
Put into . Then ask whether ten successes really rule out a true rate of 0.9.
- For a normal model with known variance, the sample mean reaches the Cramer-Rao bound. The sample median is also unbiased for the centre. What does the bound tell you about the median without any calculation?
A way to think about it
The bound is a floor for every unbiased estimator. If one estimator sits on the floor, any different one can only match it or do worse.