Algorithmcore
Horvitz-Thompson estimator
Also called HT estimator, pi-estimator.
Estimates a population total by summing each sampled value divided by its inclusion probability. It is unbiased for any design in which every unit can be sampled.
- Time
- Θ(n²) worst · best
- Space
- Θ(1) extra
- Where
- n = the number of distinct units in the sample
- Model
- Real RAM
- Properties
- design baseddeterministiclinear in yneeds pairwise probabilitiesunbiased
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel G. Horvitz, Donovan J. Thompson, 1952
The Horvitz-Thompson estimator estimates the total of a finite population from a random sample by , where is the probability that unit is in the sample. It works for every sampling design, with or without equal probabilities, and is unbiased whenever every unit has . Its variance depends on the pairwise inclusion probabilities , and with all the sample gives an unbiased estimate of that variance. The weight is the same weight as in importance sampling and inverse probability weighting. Designs that choose the on purpose, such as PPS sampling, use this estimator to undo their unequal chances.
In plain words
A sampling plan gives some units a high chance of being picked and others a low one. If a unit had a one in ten chance, then on average it shows up in one sample out of ten, so when it does show up, it stands in for ten copies of itself. The estimate of the total adds up every sampled value multiplied by one over its chance.
Averaged over all the samples the plan can draw, every unit is counted exactly once, so the estimate is right on average. How much it varies depends on how often pairs of units appear together, so the error estimate needs the chance of each pair as well. If some unit can never be picked, nothing can stand in for it, and the estimate misses its value.
The problem
A population has units, labelled , with fixed unknown values . A sampling design is a probability distribution on the subsets of , chosen by the statistician and known. One subset is drawn from , and is observed for . The randomness is in only; the are constants. This is design-based inference.
The inclusion probabilities are
with . The design has fixed size if every subset with has units. The task is to estimate , to estimate the variance of that estimate, and to compute both from , the observed and the and of the sampled units.
The algorithm
HT-ESTIMATE(S, y, π) ▷ every i ∈ S has π_i > 0- 1
T ← 0 - 2
for each i ∈ S do - 3
T ← T + y_i / π_i ▷ unit i stands for 1/π_i units - 4
return T HT-VARIANCE(S, y, π, π2) ▷ needs π_ij > 0 for i, j ∈ S- 5
v ← 0 - 6
for each i ∈ S do - 7
v ← v + (1 − π_i) · (y_i / π_i)² - 8
for each j ∈ S with j ≠ i do - 9
v ← v + (1 − π_i π_j / π_ij) · (y_i / π_i) · (y_j / π_j) - 10
return v SYG-VARIANCE(S, y, π, π2) ▷ fixed-size designs only- 11
v ← 0 - 12
for each pair i < j in S do - 13
v ← v + (π_i π_j / π_ij − 1) · (y_i / π_i − y_j / π_j)² - 14
return v
Lines L1 to L4 compute the estimate . Lines L5 to L10 compute the Horvitz-Thompson variance estimate
and lines L11 to L14 compute the Sen-Yates-Grundy estimate
Both estimate the same variance . The first works for every design with ; the second needs a fixed sample size, and then it is usually the better one, because it is zero when is the same for all sampled units, and nonnegative whenever for all pairs. The standard error is the square root of the estimate.
The algorithm does not draw the sample. Drawing is the job of the design: simple random sampling, Bernoulli sampling, stratified sampling, PPS sampling, or any other plan whose and can be computed.
Example
The population has units with , so . The design draws one of six pairs with these probabilities.
| sample | ||||||
|---|---|---|---|---|---|---|
| 0.1 | 0.1 | 0.2 | 0.1 | 0.2 | 0.3 |
Summing the rows gives , which add up to , and each is the probability of the pair itself. For the sample , line L3 adds and , so . All six samples, in exact arithmetic:
Weighting by , the mean of is exactly , and its variance is . The mean of and the mean of are both exactly , so both are unbiased, but is negative on two of the six samples. Here for every pair, so is never negative. For comparison, simple random sampling of 2 of the 4 units, with , has variance .
Correctness
Write for the indicator of , so that with and . By linearity of expectation, . The covariance of and is , which gives
Each term of is a term of this sum divided by the probability that the sample contains it, so is unbiased. For a fixed-size design, for each , which turns the sum into , and the same argument shows that is unbiased. The full proofs are below. They are exact statements about expectations over the design; the normal interval in the variants is an approximation.
Proof: The Horvitz-Thompson estimate and its variance estimates are unbiasedfull
The population is with fixed values and total . The sample is drawn from a design ; is the indicator of , , and . Write and, for units with , . All expectations are over the design, and the arithmetic is exact.
Lemma 1 (the loops). HT-ESTIMATE returns . HT-VARIANCE returns , and SYG-VARIANCE returns .
Proof. Lines L2 and L3 add once for each to . In HT-VARIANCE, the diagonal term of the double sum is , which is line L7, and an off-diagonal term is , which is line L9; lines L6 and L8 visit every ordered pair once. In SYG-VARIANCE, , which is line L13, and line L12 visits every unordered pair once.
Theorem 1 (unbiased estimate). If for every , then . In general, if sums over the sampled units with (no other units can be sampled), then .
Proof. A unit with is in with probability 0, so with probability 1, . By linearity of expectation, .
Theorem 2 (variance). If for every , then
Proof. with constant coefficients, so , and . For , .
Theorem 3 (HT variance estimate). If for all , then .
Proof. By Lemma 1, , the sum over all ordered pairs, since exactly when both units are in (and ). Taking expectations term by term, cancels the denominator, which leaves the sum of Theorem 2.
Lemma 4 (fixed size). If every sample with has exactly units, then for every .
Proof. with probability 1. Multiply by and take expectations: . Taking expectations of gives . So .
Theorem 5 (Sen-Yates-Grundy form). For a fixed-size design with all ,
Proof. Expand the double sum . is symmetric, so by Lemma 4 both row and column sums vanish, and the double sum is by Theorem 2. The diagonal terms of the double sum are 0 and each unordered pair appears twice, so , and .
Theorem 6 (SYG variance estimate). For a fixed-size design with for all , . If moreover for all , then for every sample.
Proof. By Lemma 1, over all unordered pairs of the population. With , the expectation is the sum of Theorem 5. Under the extra condition every term is a nonnegative number times a square.
Corollary 7 (simple random sampling). For of units without replacement, , , and with and .
Proof. Here and for , so . Then , so by Lemma 1
using . For , the coefficient equals , and , which gives the same value.
Cost. HT-ESTIMATE does one division and one addition per sampled unit, operations. HT-VARIANCE runs line L7 times and line L9 times, and SYG-VARIANCE runs line L13 times, each a constant number of operations given ; so both take time and extra space. All loops are over the finite set , so the procedures terminate.
Complexity
Lines L1 to L4 do one division and one addition per sampled unit: operations, time. Lines L5 to L10 visit all ordered pairs of sampled units, and lines L11 to L14 all unordered pairs, so both take time if each can be looked up or computed in . The extra space is besides the inputs. The time in the front matter is for the estimate and one variance estimate together; the estimate alone is a single pass and can run on a stream.
Computing the and is the design's cost, not the estimator's. For simple random sampling of from they are the closed forms and . For Bernoulli sampling with unequal probabilities, . For a design given as a list of samples and probabilities, as in the example, summing over the list costs per sample.
Properties
- Unbiased for every design. The only condition is for every unit with . It does not need the design to be simple, stratified or of fixed size.
- Linear in . The estimate of is the sum of the estimates, so the estimate of a domain total is the estimate with set to 0 outside the domain, and stratified estimates add over strata.
- Exact recovery. If for all in a fixed-size design, then for every sample and the variance is zero. The closer is to proportional to , the smaller the variance; this is the reason for PPS sampling.
- Simple random sampling. With , , and both variance estimates reduce to with and the sample variance of the sampled values with divisor .
- Not equivariant to a shift. Adding a constant to every adds to , not , unless for every sample.
Variants and improvements
- Mean and proportion. estimates the mean, with variance estimate . For a 0-1 variable it estimates a proportion, and it can exceed 1; see the pitfalls.
- Hájek ratio. divides by the estimate of instead of . It is a ratio of two unbiased estimates, so it is biased: in the example its mean is against the true mean . It stays between the smallest and largest sampled values, is equivariant to a shift, and often has a much smaller variance when the sample size is random. It is the self-normalized form of importance sampling and the usual form of inverse probability weighting.
- Poisson sampling. With independent inclusions, for , so all cross terms vanish: and . The sample size is random, so does not apply.
- A normal interval. For large samples from designs where a central limit theorem holds, is an approximate confidence interval. Its coverage is measured, not proved, for any given design and sample size.
- Generalized regression. Using an auxiliary variable known for all units, the regression and calibration estimators adjust the weights so that the weighted sample reproduces the known auxiliary totals.
- Streams and sketches. Priority sampling keeps a weighted sample of a stream with a threshold, and the Horvitz-Thompson idea with that threshold gives unbiased estimates of subset sums.
- Off-policy evaluation. Weighting each logged reward by one over the probability that the logging policy took the action is the same estimator in off-policy evaluation.
When to use it
Use it whenever the sample was drawn by a known probability design with unequal inclusion probabilities, and an estimate of a total, mean or proportion is needed that is unbiased by construction, without a model for . Under simple random sampling it is the ordinary expansion estimate . When is not related to the , or the sample size is random, the Hájek ratio or a regression estimator is usually more accurate. When the probabilities are estimated, as with propensity scores in observational data, the unbiasedness no longer holds exactly; see inverse probability weighting.
Pitfalls
- Units with . A unit that can never be sampled is missing from every estimate, and . No weighting can repair a frame that leaves units out.
- Pairs with . In systematic sampling, many pairs never occur together. Then neither nor can be computed, and dropping the missing terms gives a biased estimate of the variance.
- Negative variance estimates. can be negative, as for the samples and of the example. is nonnegative when for every pair; for a design that breaks this condition it can be negative too. Report and handle a negative value; do not take its square root.
- The proportion can exceed 1. With the example design and , the true proportion is , but the sample gives . The Hájek ratio gives 1 on the same sample.
- The wrong probabilities. The must be those of the design actually used. Successive draws proportional to size, for instance, do not give proportional to size; the PPS page shows the bias that follows.
- With-replacement formulas. In independent draws with probabilities , the Hansen-Hurwitz estimator divides each draw by . The Horvitz-Thompson estimator applies to the set of distinct units, with . Mixing the two, by using as for the distinct units or by counting a unit once per draw with weight , gives a biased estimate.
- Unbiased but absurd. Basu (1971) told of a circus owner who wanted the total weight of 50 elephants from one weighing. A design that picks the average elephant with probability and each of the other 49 with probability makes about times the average weight when the average elephant is picked, and 4900 times an elephant's weight otherwise. The estimate is unbiased and useless for every sample: unbiasedness is a property of the average over samples, and says nothing about the sample at hand.
- The divisor. The in the simple random sampling formula uses , and the population in uses . Say which one is meant.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/horvitz-thompson-estimator/. The authors are listed in prov/D95ZRB.jsonl.
"""The Horvitz-Thompson estimate of a population total and its variance estimates.
A sample is a sequence of distinct unit labels. y and pi map a label to its
value and its inclusion probability (a dict or a list). pij(i, j) returns the
probability that units i and j (i != j) are both in the sample. With Fraction
or int inputs the results are exact.
"""
import math
from collections.abc import Callable, Mapping, Sequence
from stdist import norm_ppf
def _check(sample: Sequence, pi) -> None:
if len(set(sample)) != len(sample):
raise ValueError("the sample must list distinct units")
for i in sample:
if pi[i] <= 0:
raise ValueError(f"unit {i!r} has inclusion probability {pi[i]!r} <= 0")
def ht_total(sample: Sequence, y: Mapping | Sequence, pi: Mapping | Sequence):
"""Return sum over the sample of y[i] / pi[i]. Cost: 2 n operations."""
_check(sample, pi)
total = 0 # @line L1
for i in sample: # @line L2
total = total + y[i] / pi[i] # @line L3
return total # @line L4
def ht_variance(sample: Sequence, y, pi, pij: Callable) -> float:
"""The Horvitz-Thompson variance estimate; needs pij(i, j) > 0. Cost: Theta(n^2).
The value can be negative.
"""
_check(sample, pi)
v = 0 # @line L5
for i in sample: # @line L6
ci = y[i] / pi[i]
v = v + (1 - pi[i]) * ci * ci # @line L7
for j in sample: # @line L8
if j == i:
continue
q = pij(i, j)
if q <= 0:
raise ValueError(f"pair {i!r}, {j!r} has joint probability {q!r} <= 0")
v = v + (1 - pi[i] * pi[j] / q) * ci * (y[j] / pi[j]) # @line L9
return v # @line L10
def syg_variance(sample: Sequence, y, pi, pij: Callable) -> float:
"""The Sen-Yates-Grundy variance estimate, for fixed-size designs only. Cost: Theta(n^2)."""
_check(sample, pi)
v = 0 # @line L11
for a in range(len(sample)): # @line L12
i = sample[a]
for b in range(a + 1, len(sample)):
j = sample[b]
q = pij(i, j)
if q <= 0:
raise ValueError(f"pair {i!r}, {j!r} has joint probability {q!r} <= 0")
d = y[i] / pi[i] - y[j] / pi[j]
v = v + (pi[i] * pi[j] / q - 1) * d * d # @line L13
return v # @line L14
def hajek_mean(sample: Sequence, y, pi):
"""The Hajek ratio: sum y[i]/pi[i] divided by sum 1/pi[i]. Biased, but shift equivariant."""
_check(sample, pi)
if not sample:
raise ValueError("the Hajek ratio needs a nonempty sample")
num = sum((y[i] / pi[i] for i in sample), 0)
den = sum((1 / pi[i] for i in sample), 0)
return num / den
def ht_interval(estimate: float, variance: float, level: float = 0.95) -> tuple[float, float]:
"""The approximate normal interval estimate +- z * sqrt(variance).
Raises ValueError for a negative variance estimate. The coverage is
approximate and depends on the design and the sample size.
"""
if variance < 0:
raise ValueError("negative variance estimate")
half = norm_ppf(0.5 + level / 2) * math.sqrt(variance)
return float(estimate) - half, float(estimate) + half
stdist.py 238 lines
# SPDX-License-Identifier: MIT
# Shared helper of the pe1 statistics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Normal, chi-square, t and F distribution functions in the standard library.
The incomplete gamma and beta functions return a lower tail and an upper
tail, and each tail is computed directly where it is small, so an upper tail
such as chi2_sf(200, 3) does not come from 1 - cdf and does not cancel.
Quantiles use a safeguarded bisection on the CDF (lower half) or on the upper
tail (upper half); the bracket shrinks until floating point stops it, so the
probability error is that of the CDF, below 1e-12 for moderate parameters.
"""
import math
from statistics import NormalDist
_STD = NormalDist()
_EPS = 1e-16
_TINY = 1e-300
_MAXIT = 10000
def norm_cdf(x: float) -> float:
"""P(Z <= x) for a standard normal Z."""
return 0.5 * math.erfc(-x / math.sqrt(2.0))
def norm_sf(x: float) -> float:
"""P(Z > x), computed with erfc, so it is accurate for large x."""
return 0.5 * math.erfc(x / math.sqrt(2.0))
def norm_ppf(p: float) -> float:
"""The lower p-quantile z_p of the standard normal, 0 < p < 1."""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
return _STD.inv_cdf(p)
def _gamma_tails(a: float, x: float) -> tuple[float, float]:
"""(P(a, x), Q(a, x)), the regularized lower and upper incomplete gamma."""
if a <= 0.0 or x < 0.0:
raise ValueError("need a > 0 and x >= 0")
if x == 0.0:
return 0.0, 1.0
if math.isinf(x):
return 1.0, 0.0
front = math.exp(-x + a * math.log(x) - math.lgamma(a))
if x < a + 1.0:
# Series: P = front * sum_{j >= 0} x^j / (a (a + 1) ... (a + j)).
ap, term = a, 1.0 / a
total = term
for _ in range(_MAXIT):
ap += 1.0
term *= x / ap
total += term
if abs(term) < abs(total) * _EPS:
break
p = front * total
return p, 1.0 - p
# Continued fraction for Q, modified Lentz.
b = x + 1.0 - a
c = 1.0 / _TINY
d = 1.0 / b
h = d
for i in range(1, _MAXIT):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < _TINY:
d = _TINY
c = b + an / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
q = front * h
return 1.0 - q, q
def gamma_p(a: float, x: float) -> float:
"""Regularized lower incomplete gamma P(a, x)."""
return _gamma_tails(a, x)[0]
def gamma_q(a: float, x: float) -> float:
"""Regularized upper incomplete gamma Q(a, x) = 1 - P(a, x)."""
return _gamma_tails(a, x)[1]
def _beta_cf(a: float, b: float, x: float) -> float:
"""The continued fraction of I_x(a, b), modified Lentz."""
qab, qap, qam = a + b, a + 1.0, a - 1.0
c = 1.0
d = 1.0 - qab * x / qap
if abs(d) < _TINY:
d = _TINY
d = 1.0 / d
h = d
for m in range(1, _MAXIT):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < _TINY:
d = _TINY
c = 1.0 + aa / c
if abs(c) < _TINY:
c = _TINY
d = 1.0 / d
step = d * c
h *= step
if abs(step - 1.0) < _EPS:
break
return h
def _beta_tails(a: float, b: float, x: float, y: float | None = None) -> tuple[float, float]:
"""(I_x(a, b), 1 - I_x(a, b)), each computed directly where it is small.
y is 1 - x; pass it when it is known more accurately than 1 - x.
"""
if a <= 0.0 or b <= 0.0:
raise ValueError("need a > 0 and b > 0")
if y is None:
y = 1.0 - x
if x <= 0.0:
return 0.0, 1.0
if y <= 0.0:
return 1.0, 0.0
front = math.exp(
math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
+ a * math.log(x) + b * math.log(y)
)
if x < (a + 1.0) / (a + b + 2.0):
low = front * _beta_cf(a, b, x) / a
return low, 1.0 - low
# Symmetry: I_x(a, b) = 1 - I_(1-x)(b, a).
up = front * _beta_cf(b, a, y) / b
return 1.0 - up, up
def beta_inc(a: float, b: float, x: float) -> float:
"""Regularized incomplete beta function I_x(a, b)."""
return _beta_tails(a, b, x)[0]
def chi2_cdf(x: float, k: float) -> float:
"""P(X <= x) for X chi-square with k > 0 degrees of freedom."""
return 0.0 if x <= 0.0 else gamma_p(k / 2.0, x / 2.0)
def chi2_sf(x: float, k: float) -> float:
"""P(X > x) for X chi-square with k degrees of freedom, without 1 - cdf."""
return 1.0 if x <= 0.0 else gamma_q(k / 2.0, x / 2.0)
def t_sf(x: float, k: float) -> float:
"""P(T > x) for T Student t with k > 0 degrees of freedom."""
if math.isfinite(x):
s = k + x * x
half = 0.5 * _beta_tails(k / 2.0, 0.5, k / s, x * x / s)[0] # P(|T| > |x|) / 2
else:
half = 0.0
return half if x >= 0.0 else 1.0 - half
def t_cdf(x: float, k: float) -> float:
"""P(T <= x) for T Student t with k degrees of freedom."""
return t_sf(-x, k)
def f_cdf(x: float, k1: float, k2: float) -> float:
"""P(F <= x) for F with (k1, k2) degrees of freedom."""
if x <= 0.0:
return 0.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[1]
def f_sf(x: float, k1: float, k2: float) -> float:
"""P(F > x) = I_(k2 / (k2 + k1 x))(k2 / 2, k1 / 2)."""
if x <= 0.0:
return 1.0
return _beta_tails(k2 / 2.0, k1 / 2.0, k2 / (k2 + k1 * x), k1 * x / (k2 + k1 * x))[0]
def _quantile(cdf, sf, p: float, lo: float, hi: float) -> float:
"""The x with cdf(x) = p, by bisection on cdf (p <= 1/2) or on sf (p > 1/2).
lo must satisfy cdf(lo) <= p; hi is doubled until cdf(hi) >= p.
"""
if not 0.0 < p < 1.0:
raise ValueError("p must be in (0, 1)")
if p <= 0.5:
g = lambda x: cdf(x) - p # increasing in x
else:
q = 1.0 - p
g = lambda x: q - sf(x) # increasing in x, and no cancellation in sf
while g(hi) < 0.0:
lo, hi = hi, 2.0 * hi if hi > 0.0 else 1.0
for _ in range(400):
mid = 0.5 * (lo + hi)
if mid <= lo or mid >= hi:
break
if g(mid) < 0.0:
lo = mid
else:
hi = mid
return 0.5 * (lo + hi)
def chi2_ppf(p: float, k: float) -> float:
"""The lower p-quantile chi^2_(k, p)."""
return _quantile(lambda x: chi2_cdf(x, k), lambda x: chi2_sf(x, k), p, 0.0, max(1.0, k))
def t_ppf(p: float, k: float) -> float:
"""The lower p-quantile t_(k, p)."""
if p == 0.5:
return 0.0
if p < 0.5:
return -t_ppf(1.0 - p, k)
return _quantile(lambda x: t_cdf(x, k), lambda x: t_sf(x, k), p, 0.0, 1.0)
def f_ppf(p: float, k1: float, k2: float) -> float:
"""The lower p-quantile F_(k1, k2, p)."""
return _quantile(lambda x: f_cdf(x, k1, k2), lambda x: f_sf(x, k1, k2), p, 0.0, 1.0)
test_horvitz_thompson_estimator.py 187 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/horvitz-thompson-estimator/. The authors are listed in prov/D95ZRB.jsonl.
import itertools
import random
from fractions import Fraction
from horvitz_thompson_estimator import hajek_mean, ht_interval, ht_total, ht_variance, syg_variance
from stdist import norm_ppf
def inclusion(design, units):
"""pi_i and pi_ij of a design given as {sample tuple: probability}, by summing."""
pi = {i: sum((p for s, p in design.items() if i in s), Fraction(0)) for i in units}
pij = {(i, j): sum((p for s, p in design.items() if i in s and j in s), Fraction(0))
for i in units for j in units}
return pi, pij
def moments(design, values):
"""Mean and variance over the design of the given per-sample values."""
mean = sum((p * values[s] for s, p in design.items()), Fraction(0))
var = sum((p * (values[s] - mean) ** 2 for s, p in design.items()), Fraction(0))
return mean, var
def var_formula(y, pi, pij, units):
return sum(((pij[i, j] - pi[i] * pi[j]) * y[i] / pi[i] * y[j] / pi[j]
for i in units for j in units), Fraction(0))
def random_fixed_design(rng, n_units, size):
"""Every subset of the given size gets a positive random probability."""
subsets = list(itertools.combinations(range(n_units), size))
w = [rng.randint(1, 9) for _ in subsets]
total = sum(w)
return {s: Fraction(wi, total) for s, wi in zip(subsets, w)}
EXAMPLE = {(1, 2): Fraction(1, 10), (1, 3): Fraction(1, 10), (1, 4): Fraction(2, 10),
(2, 3): Fraction(1, 10), (2, 4): Fraction(2, 10), (3, 4): Fraction(3, 10)}
EXAMPLE_Y = {1: 2, 2: 3, 3: 6, 4: 10}
def test_running_example_table():
units = [1, 2, 3, 4]
pi, pij = inclusion(EXAMPLE, units)
assert [pi[i] for i in units] == [Fraction(2, 5), Fraction(2, 5), Fraction(1, 2), Fraction(7, 10)]
q = lambda i, j: pij[i, j]
y = EXAMPLE_Y
expected = {
(1, 2): (Fraction(25, 2), Fraction(15, 4), Fraction(15, 4), Fraction(5, 2)),
(1, 3): (Fraction(17), Fraction(-33), Fraction(49), Fraction(34, 9)),
(1, 4): (Fraction(135, 7), Fraction(935, 49), Fraction(1690, 49), Fraction(54, 11)),
(2, 3): (Fraction(39, 2), Fraction(-297, 4), Fraction(81, 4), Fraction(13, 3)),
(2, 4): (Fraction(305, 14), Fraction(1815, 196), Fraction(1805, 98), Fraction(61, 11)),
(3, 4): (Fraction(184, 7), Fraction(3728, 49), Fraction(128, 147), Fraction(23, 3)),
}
for s, row in expected.items():
got = (ht_total(s, y, pi), ht_variance(s, y, pi, q), syg_variance(s, y, pi, q), hajek_mean(s, y, pi))
assert got == row
est = {s: ht_total(s, y, pi) for s in EXAMPLE}
mean, var = moments(EXAMPLE, est)
assert mean == 21 and var == Fraction(127, 7) == var_formula(y, pi, pij, units)
assert moments(EXAMPLE, {s: ht_variance(s, y, pi, q) for s in EXAMPLE})[0] == Fraction(127, 7)
assert moments(EXAMPLE, {s: syg_variance(s, y, pi, q) for s in EXAMPLE})[0] == Fraction(127, 7)
assert moments(EXAMPLE, {s: hajek_mean(s, y, pi) for s in EXAMPLE})[0] == Fraction(2159, 396)
def test_unbiased_by_enumeration_fixed_size():
rng = random.Random(1952)
for _ in range(150):
n_units = rng.randint(3, 6)
size = rng.randint(2, n_units - 1)
design = random_fixed_design(rng, n_units, size)
units = list(range(n_units))
y = [Fraction(rng.randint(-20, 30), rng.randint(1, 4)) for _ in units]
pi, pij = inclusion(design, units)
q = lambda i, j: pij[i, j]
assert sum(pi.values()) == size
est = {s: ht_total(s, y, pi) for s in design}
mean, var = moments(design, est)
assert mean == sum(y)
assert var == var_formula(y, pi, pij, units)
syg_form = sum(((pi[i] * pi[j] - pij[i, j]) * (y[i] / pi[i] - y[j] / pi[j]) ** 2
for i, j in itertools.combinations(units, 2)), Fraction(0))
assert var == syg_form
assert moments(design, {s: ht_variance(s, y, pi, q) for s in design})[0] == var
assert moments(design, {s: syg_variance(s, y, pi, q) for s in design})[0] == var
def test_unbiased_by_enumeration_poisson_sampling():
rng = random.Random(7)
for _ in range(40):
n_units = rng.randint(1, 6)
units = list(range(n_units))
pi = [Fraction(rng.randint(1, 9), 10) for _ in units]
y = [Fraction(rng.randint(-15, 15)) for _ in units]
design = {}
for bits in itertools.product((0, 1), repeat=n_units):
s = tuple(i for i in units if bits[i])
p = Fraction(1)
for i in units:
p *= pi[i] if bits[i] else 1 - pi[i]
design[s] = p
q = lambda i, j: pi[i] * pi[j]
est = {s: ht_total(s, y, pi) for s in design}
mean, var = moments(design, est)
assert mean == sum(y)
assert var == sum(((1 - pi[i]) * y[i] ** 2 / pi[i] for i in units), Fraction(0))
assert moments(design, {s: ht_variance(s, y, pi, q) for s in design})[0] == var
def test_simple_random_sampling_closed_forms():
rng = random.Random(3)
for _ in range(100):
big_n = rng.randint(3, 7)
n = rng.randint(2, big_n)
y = [Fraction(rng.randint(-10, 40)) for _ in range(big_n)]
f = Fraction(n, big_n)
pi = [f] * big_n
q = lambda i, j: Fraction(n * (n - 1), big_n * (big_n - 1))
samples = list(itertools.combinations(range(big_n), n))
for s in samples:
ys = [y[i] for i in s]
ybar = sum(ys, Fraction(0)) / n
s2 = sum(((v - ybar) ** 2 for v in ys), Fraction(0)) / (n - 1)
closed = big_n ** 2 * (1 - f) * s2 / n
assert ht_total(s, y, pi) == big_n * ybar
assert ht_variance(s, y, pi, q) == closed == syg_variance(s, y, pi, q)
mean_y = sum(y, Fraction(0)) / big_n
pop_s2 = sum(((v - mean_y) ** 2 for v in y), Fraction(0)) / (big_n - 1)
uniform = {s: Fraction(1, len(samples)) for s in samples}
mean, var = moments(uniform, {s: ht_total(s, y, pi) for s in samples})
assert mean == sum(y) and var == big_n ** 2 * (1 - f) * pop_s2 / n
def test_proportion_can_exceed_one_and_hajek_stays_in_range():
pi, _ = inclusion(EXAMPLE, [1, 2, 3, 4])
yb = {1: 1, 2: 1, 3: 0, 4: 1}
assert ht_total((1, 2), yb, pi) / 4 == Fraction(5, 4)
assert hajek_mean((1, 2), yb, pi) == 1
est = {s: ht_total(s, yb, pi) / 4 for s in EXAMPLE}
assert moments(EXAMPLE, est)[0] == Fraction(3, 4)
def test_zero_probabilities_are_rejected():
for bad in (lambda: ht_total([0, 1], [1, 2], [Fraction(1, 2), 0]),
lambda: ht_variance([0, 1], [1, 2], [Fraction(1, 2)] * 2, lambda i, j: 0),
lambda: syg_variance([0, 1], [1, 2], [Fraction(1, 2)] * 2, lambda i, j: 0),
lambda: ht_total([0, 0], [1, 2], [Fraction(1, 2)] * 2),
lambda: ht_interval(10.0, -1.0)):
try:
bad()
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
def test_missing_units_bias():
# Unit 2 is never sampled: the expectation misses exactly its value.
design = {(0,): Fraction(1, 2), (1,): Fraction(1, 2)}
y = [Fraction(4), Fraction(6), Fraction(5)]
pi = [Fraction(1, 2), Fraction(1, 2), Fraction(0)]
mean, _ = moments(design, {s: ht_total(s, y, pi) for s in design})
assert mean == sum(y) - y[2]
def test_normal_interval_coverage_simple_random_sampling():
# Measured, not proved: about 95 percent coverage for n = 30 of N = 120.
rng = random.Random(2024)
big_n, n, reps = 120, 30, 1000
y = [rng.gammavariate(4.0, 5.0) for _ in range(big_n)]
total = sum(y)
f = n / big_n
pi = [f] * big_n
joint = n * (n - 1) / (big_n * (big_n - 1))
q = lambda i, j: joint
lo, hi = ht_interval(0.0, 1.0, 0.95)
assert abs(hi - norm_ppf(0.975)) < 1e-15 and lo == -hi
covered = 0
for _ in range(reps):
s = rng.sample(range(big_n), n)
a, b = ht_interval(ht_total(s, y, pi), syg_variance(s, y, pi, q))
covered += a <= total <= b
assert 0.92 <= covered / reps <= 0.97
History
Horvitz and Thompson (1952) generalized sampling without replacement to unequal probabilities and gave the estimator , its variance in terms of the , and an unbiased estimate of the variance. Sen (1953) and, independently, Yates and Grundy (1953) gave the variance for fixed-size designs as a sum over pairs of squared differences, with the estimate . Basu's 1971 essay on the foundations of survey sampling used the circus example to argue that design unbiasedness alone does not make an estimate sensible. Cochran's textbook treats the estimator in Section 9A.7.
References
- D. G. Horvitz and D. J. Thompson, A generalization of sampling without replacement from a finite universe, Journal of the American Statistical Association 47(260), 1952, pp. 663 to 685 (the estimator of the total, its variance with the pairwise inclusion probabilities, and an unbiased estimate of that variance)
- On the estimate of the variance in sampling with varying probabilities, the whole paper (the variance estimator for fixed-size designs)
- F. Yates and P. M. Grundy, Selection without replacement from within strata with probability proportional to size, Journal of the Royal Statistical Society Series B 15(2), 1953, pp. 253 to 261 (the variance in the form of squared differences and its estimate)
- William G. Cochran, Sampling Techniques, third edition, Wiley, 1977, Section 9A.7, pp. 259 to 261 (the Horvitz-Thompson estimator and the Yates-Grundy variance estimate)
- An essay on the logical foundations of survey sampling, part one, the circus example (an unbiased estimate that is absurd for every sample)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag D95ZRB Edit this page History Report an error Markdown