Algorithm Search⌘K

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
Properties
design baseddeterministiclinear in yneeds pairwise probabilitiesunbiased
Origin
Daniel G. Horvitz, Donovan J. Thompson, 1952

The Horvitz-Thompson estimator estimates the total Y=∑i=1NyiY = \sum_{i=1}^N y_i of a finite population from a random sample SS by Y^=∑i∈Syi/πi\hat Y = \sum_{i \in S} y_i/\pi_i, where πi\pi_i is the probability that unit ii is in the sample. It works for every sampling design, with or without equal probabilities, and is unbiased whenever every unit has πi>0\pi_i > 0. Its variance depends on the pairwise inclusion probabilities πij\pi_{ij}, and with all πij>0\pi_{ij} > 0 the sample gives an unbiased estimate of that variance. The weight 1/πi1/\pi_i is the same weight as in importance sampling and inverse probability weighting. Designs that choose the πi\pi_i 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 NN units, labelled 1,…,N1, \ldots, N, with fixed unknown values y1,…,yNy_1, \ldots, y_N. A sampling design is a probability distribution pp on the subsets of {1,…,N}\{1, \ldots, N\}, chosen by the statistician and known. One subset SS is drawn from pp, and yiy_i is observed for i∈Si \in S. The randomness is in SS only; the yiy_i are constants. This is design-based inference.

The inclusion probabilities are

πi=Pr⁡[i∈S]=∑s∋ip(s),πij=Pr⁡[i∈S and j∈S]=∑s∋i,jp(s),\pi_i = \Pr[i \in S] = \sum_{s \ni i} p(s), \qquad \pi_{ij} = \Pr[i \in S \text{ and } j \in S] = \sum_{s \ni i, j} p(s),

with πii=πi\pi_{ii} = \pi_i. The design has fixed size nn if every subset with p(s)>0p(s) > 0 has nn units. The task is to estimate YY, to estimate the variance of that estimate, and to compute both from SS, the observed yiy_i and the πi\pi_i and πij\pi_{ij} of the sampled units.

The algorithm

  1. HT-ESTIMATE(S, y, π) ▷ every i ∈ S has π_i > 0
  2. 1T ← 0
  3. 2for each i ∈ S do
  4. 3T ← T + y_i / π_i ▷ unit i stands for 1/π_i units
  5. 4return T
  6. HT-VARIANCE(S, y, π, π2) ▷ needs π_ij > 0 for i, j ∈ S
  7. 5v ← 0
  8. 6for each i ∈ S do
  9. 7v ← v + (1 − π_i) · (y_i / π_i)²
  10. 8for each j ∈ S with j ≠ i do
  11. 9v ← v + (1 − π_i π_j / π_ij) · (y_i / π_i) · (y_j / π_j)
  12. 10return v
  13. SYG-VARIANCE(S, y, π, π2) ▷ fixed-size designs only
  14. 11v ← 0
  15. 12for each pair i < j in S do
  16. 13v ← v + (π_i π_j / π_ij − 1) · (y_i / π_i − y_j / π_j)²
  17. 14return v

Lines L1 to L4 compute the estimate Y^\hat Y. Lines L5 to L10 compute the Horvitz-Thompson variance estimate

vHT=∑i∈S(1−πi)yi2πi2+∑i∈S∑j∈S,j≠iπij−πiπjπij yiπiyjπj,v_{\mathrm{HT}} = \sum_{i \in S} (1 - \pi_i)\frac{y_i^2}{\pi_i^2} + \sum_{i \in S}\sum_{j \in S, j \ne i} \frac{\pi_{ij} - \pi_i\pi_j}{\pi_{ij}}\,\frac{y_i}{\pi_i}\frac{y_j}{\pi_j},

and lines L11 to L14 compute the Sen-Yates-Grundy estimate

vSYG=∑i<j, i,j∈Sπiπj−πijπij(yiπi−yjπj)2.v_{\mathrm{SYG}} = \sum_{i < j,\ i, j \in S} \frac{\pi_i\pi_j - \pi_{ij}}{\pi_{ij}}\left(\frac{y_i}{\pi_i} - \frac{y_j}{\pi_j}\right)^2.

Both estimate the same variance Var⁡[Y^]\operatorname{Var}[\hat Y]. The first works for every design with πij>0\pi_{ij} > 0; the second needs a fixed sample size, and then it is usually the better one, because it is zero when yi/πiy_i/\pi_i is the same for all sampled units, and nonnegative whenever πij≤πiπj\pi_{ij} \le \pi_i \pi_j 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 πi\pi_i and πij\pi_{ij} can be computed.

Example

The population has N=4N = 4 units with y=(2,3,6,10)y = (2, 3, 6, 10), so Y=21Y = 21. The design draws one of six pairs with these probabilities.

sample SS {1,2}\{1,2\} {1,3}\{1,3\} {1,4}\{1,4\} {2,3}\{2,3\} {2,4}\{2,4\} {3,4}\{3,4\}
p(S)p(S) 0.1 0.1 0.2 0.1 0.2 0.3

Summing the rows gives π=(0.4,0.4,0.5,0.7)\pi = (0.4, 0.4, 0.5, 0.7), which add up to n=2n = 2, and each πij\pi_{ij} is the probability of the pair {i,j}\{i, j\} itself. For the sample {1,4}\{1, 4\}, line L3 adds 2/0.4=52/0.4 = 5 and 10/0.7=100/710/0.7 = 100/7, so Y^=135/7≈19.29\hat Y = 135/7 \approx 19.29. All six samples, in exact arithmetic:

SS Y^\hat Y vHTv_{\mathrm{HT}} vSYGv_{\mathrm{SYG}}
{1,2}\{1,2\} 12.512.5 3.753.75 3.753.75
{1,3}\{1,3\} 1717 −33-33 4949
{1,4}\{1,4\} 135/7≈19.29135/7 \approx 19.29 935/49≈19.08935/49 \approx 19.08 1690/49≈34.491690/49 \approx 34.49
{2,3}\{2,3\} 19.519.5 −74.25-74.25 20.2520.25
{2,4}\{2,4\} 305/14≈21.79305/14 \approx 21.79 1815/196≈9.261815/196 \approx 9.26 1805/98≈18.421805/98 \approx 18.42
{3,4}\{3,4\} 184/7≈26.29184/7 \approx 26.29 3728/49≈76.083728/49 \approx 76.08 128/147≈0.87128/147 \approx 0.87

Weighting by p(S)p(S), the mean of Y^\hat Y is exactly 21=Y21 = Y, and its variance is 127/7≈18.14127/7 \approx 18.14. The mean of vHTv_{\mathrm{HT}} and the mean of vSYGv_{\mathrm{SYG}} are both exactly 127/7127/7, so both are unbiased, but vHTv_{\mathrm{HT}} is negative on two of the six samples. Here πiπj≥πij\pi_i\pi_j \ge \pi_{ij} for every pair, so vSYGv_{\mathrm{SYG}} is never negative. For comparison, simple random sampling of 2 of the 4 units, with Y^=2(yi+yj)\hat Y = 2(y_i + y_j), has variance 155/3≈51.67155/3 \approx 51.67.

Correctness

Write IiI_i for the indicator of i∈Si \in S, so that Y^=∑i=1NIi yi/πi\hat Y = \sum_{i=1}^N I_i\,y_i/\pi_i with E[Ii]=πi\mathbb{E}[I_i] = \pi_i and E[IiIj]=πij\mathbb{E}[I_iI_j] = \pi_{ij}. By linearity of expectation, E[Y^]=∑iyi=Y\mathbb{E}[\hat Y] = \sum_i y_i = Y. The covariance of IiI_i and IjI_j is πij−πiπj\pi_{ij} - \pi_i\pi_j, which gives

Var⁡[Y^]=∑i=1N∑j=1N(πij−πiπj)yiπiyjπj.\operatorname{Var}[\hat Y] = \sum_{i=1}^N\sum_{j=1}^N (\pi_{ij} - \pi_i\pi_j)\frac{y_i}{\pi_i}\frac{y_j}{\pi_j}.

Each term of vHTv_{\mathrm{HT}} is a term of this sum divided by the probability πij\pi_{ij} that the sample contains it, so vHTv_{\mathrm{HT}} is unbiased. For a fixed-size design, ∑j(πij−πiπj)=0\sum_j (\pi_{ij} - \pi_i\pi_j) = 0 for each ii, which turns the sum into ∑i<j(πiπj−πij)(yi/πi−yj/πj)2\sum_{i<j}(\pi_i\pi_j - \pi_{ij})(y_i/\pi_i - y_j/\pi_j)^2, and the same argument shows that vSYGv_{\mathrm{SYG}} 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 {1,…,N}\{1, \ldots, N\} with fixed values y1,…,yNy_1, \ldots, y_N and total Y=∑iyiY = \sum_i y_i. The sample SS is drawn from a design pp; IiI_i is the indicator of i∈Si \in S, πi=E[Ii]\pi_i = \mathbb{E}[I_i], πij=E[IiIj]\pi_{ij} = \mathbb{E}[I_iI_j] and πii=πi\pi_{ii} = \pi_i. Write Δij=πij−πiπj=Cov⁡(Ii,Ij)\Delta_{ij} = \pi_{ij} - \pi_i\pi_j = \operatorname{Cov}(I_i, I_j) and, for units with πi>0\pi_i > 0, yˇi=yi/πi\check y_i = y_i/\pi_i. All expectations are over the design, and the arithmetic is exact.

Lemma 1 (the loops). HT-ESTIMATE returns Y^=∑i∈Syˇi\hat Y = \sum_{i \in S}\check y_i. HT-VARIANCE returns vHT=∑i∈S∑j∈SΔijπijyˇiyˇjv_{\mathrm{HT}} = \sum_{i \in S}\sum_{j \in S}\frac{\Delta_{ij}}{\pi_{ij}}\check y_i\check y_j, and SYG-VARIANCE returns vSYG=∑i<j; i,j∈S−Δijπij(yˇi−yˇj)2v_{\mathrm{SYG}} = \sum_{i<j;\ i,j \in S}\frac{-\Delta_{ij}}{\pi_{ij}}(\check y_i - \check y_j)^2.

Proof. Lines L2 and L3 add yˇi\check y_i once for each i∈Si \in S to T=0T = 0. In HT-VARIANCE, the diagonal term i=ji = j of the double sum is πi−πi2πiyˇi2=(1−πi)yˇi2\frac{\pi_i - \pi_i^2}{\pi_i}\check y_i^2 = (1 - \pi_i)\check y_i^2, which is line L7, and an off-diagonal term is πij−πiπjπijyˇiyˇj=(1−πiπj/πij)yˇiyˇj\frac{\pi_{ij} - \pi_i\pi_j}{\pi_{ij}}\check y_i\check y_j = (1 - \pi_i\pi_j/\pi_{ij})\check y_i\check y_j, which is line L9; lines L6 and L8 visit every ordered pair once. In SYG-VARIANCE, −Δij/πij=πiπj/πij−1-\Delta_{ij}/\pi_{ij} = \pi_i\pi_j/\pi_{ij} - 1, which is line L13, and line L12 visits every unordered pair once. □\square

Theorem 1 (unbiased estimate). If πi>0\pi_i > 0 for every ii, then E[Y^]=Y\mathbb{E}[\hat Y] = Y. In general, if Y^\hat Y sums over the sampled units with πi>0\pi_i > 0 (no other units can be sampled), then E[Y^]=Y−∑i:πi=0yi\mathbb{E}[\hat Y] = Y - \sum_{i : \pi_i = 0} y_i.

Proof. A unit with πi=0\pi_i = 0 is in SS with probability 0, so with probability 1, Y^=∑i:πi>0Iiyˇi\hat Y = \sum_{i : \pi_i > 0} I_i\check y_i. By linearity of expectation, E[Y^]=∑i:πi>0πi yi/πi=∑i:πi>0yi\mathbb{E}[\hat Y] = \sum_{i : \pi_i > 0}\pi_i\,y_i/\pi_i = \sum_{i : \pi_i > 0} y_i. □\square

Theorem 2 (variance). If πi>0\pi_i > 0 for every ii, then

Var⁡[Y^]=∑i=1N∑j=1NΔij yˇiyˇj.\operatorname{Var}[\hat Y] = \sum_{i=1}^N\sum_{j=1}^N \Delta_{ij}\,\check y_i\check y_j.

Proof. Y^=∑iyˇiIi\hat Y = \sum_i \check y_i I_i with constant coefficients, so Var⁡[Y^]=∑i∑jyˇiyˇjCov⁡(Ii,Ij)\operatorname{Var}[\hat Y] = \sum_i\sum_j \check y_i\check y_j \operatorname{Cov}(I_i, I_j), and Cov⁡(Ii,Ij)=E[IiIj]−E[Ii]E[Ij]=Δij\operatorname{Cov}(I_i, I_j) = \mathbb{E}[I_iI_j] - \mathbb{E}[I_i]\mathbb{E}[I_j] = \Delta_{ij}. For i=ji = j, E[Ii2]=E[Ii]=πi=πii\mathbb{E}[I_i^2] = \mathbb{E}[I_i] = \pi_i = \pi_{ii}. □\square

Theorem 3 (HT variance estimate). If πij>0\pi_{ij} > 0 for all i,ji, j, then E[vHT]=Var⁡[Y^]\mathbb{E}[v_{\mathrm{HT}}] = \operatorname{Var}[\hat Y].

Proof. By Lemma 1, vHT=∑i∑jIiIjΔijπijyˇiyˇjv_{\mathrm{HT}} = \sum_{i}\sum_{j} I_iI_j\frac{\Delta_{ij}}{\pi_{ij}}\check y_i\check y_j, the sum over all N2N^2 ordered pairs, since IiIj=1I_iI_j = 1 exactly when both units are in SS (and IiIi=IiI_iI_i = I_i). Taking expectations term by term, E[IiIj]=πij\mathbb{E}[I_iI_j] = \pi_{ij} cancels the denominator, which leaves the sum of Theorem 2. □\square

Lemma 4 (fixed size). If every sample with p(s)>0p(s) > 0 has exactly nn units, then ∑j=1NΔij=0\sum_{j=1}^N \Delta_{ij} = 0 for every ii.

Proof. ∑jIj=n\sum_j I_j = n with probability 1. Multiply by IiI_i and take expectations: ∑jπij=nπi\sum_j \pi_{ij} = n\pi_i. Taking expectations of ∑jIj=n\sum_j I_j = n gives ∑jπj=n\sum_j \pi_j = n. So ∑jΔij=nπi−πi⋅n=0\sum_j \Delta_{ij} = n\pi_i - \pi_i\cdot n = 0. □\square

Theorem 5 (Sen-Yates-Grundy form). For a fixed-size design with all πi>0\pi_i > 0,

Var⁡[Y^]=∑i<j(πiπj−πij)(yˇi−yˇj)2.\operatorname{Var}[\hat Y] = \sum_{i<j}(\pi_i\pi_j - \pi_{ij})(\check y_i - \check y_j)^2.

Proof. Expand the double sum ∑i∑jΔij(yˇi−yˇj)2=∑iyˇi2∑jΔij+∑jyˇj2∑iΔij−2∑i∑jΔijyˇiyˇj\sum_i\sum_j \Delta_{ij}(\check y_i - \check y_j)^2 = \sum_i \check y_i^2\sum_j\Delta_{ij} + \sum_j \check y_j^2\sum_i\Delta_{ij} - 2\sum_i\sum_j\Delta_{ij}\check y_i\check y_j. Δ\Delta is symmetric, so by Lemma 4 both row and column sums vanish, and the double sum is −2Var⁡[Y^]-2\operatorname{Var}[\hat Y] by Theorem 2. The diagonal terms of the double sum are 0 and each unordered pair appears twice, so Var⁡[Y^]=−12∑i∑jΔij(yˇi−yˇj)2=∑i<j(−Δij)(yˇi−yˇj)2\operatorname{Var}[\hat Y] = -\frac12\sum_i\sum_j\Delta_{ij}(\check y_i - \check y_j)^2 = \sum_{i<j}(-\Delta_{ij})(\check y_i - \check y_j)^2, and −Δij=πiπj−πij-\Delta_{ij} = \pi_i\pi_j - \pi_{ij}. □\square

Theorem 6 (SYG variance estimate). For a fixed-size design with πij>0\pi_{ij} > 0 for all i≠ji \ne j, E[vSYG]=Var⁡[Y^]\mathbb{E}[v_{\mathrm{SYG}}] = \operatorname{Var}[\hat Y]. If moreover πij≤πiπj\pi_{ij} \le \pi_i\pi_j for all i≠ji \ne j, then vSYG≥0v_{\mathrm{SYG}} \ge 0 for every sample.

Proof. By Lemma 1, vSYG=∑i<jIiIjπiπj−πijπij(yˇi−yˇj)2v_{\mathrm{SYG}} = \sum_{i<j} I_iI_j\frac{\pi_i\pi_j - \pi_{ij}}{\pi_{ij}}(\check y_i - \check y_j)^2 over all unordered pairs of the population. With E[IiIj]=πij\mathbb{E}[I_iI_j] = \pi_{ij}, the expectation is the sum of Theorem 5. Under the extra condition every term is a nonnegative number times a square. □\square

Corollary 7 (simple random sampling). For nn of NN units without replacement, n≥2n \ge 2, Y^=NyˉS\hat Y = N\bar y_S, and vHT=vSYG=N2(1−f)s2/nv_{\mathrm{HT}} = v_{\mathrm{SYG}} = N^2(1 - f)s^2/n with f=n/Nf = n/N and s2=1n−1∑i∈S(yi−yˉS)2s^2 = \frac{1}{n-1}\sum_{i \in S}(y_i - \bar y_S)^2.

Proof. Here πi=f\pi_i = f and πij=n(n−1)N(N−1)\pi_{ij} = \frac{n(n-1)}{N(N-1)} for i≠ji \ne j, so Y^=∑i∈Syi/f=NyˉS\hat Y = \sum_{i \in S} y_i/f = N\bar y_S. Then 1−f2/πij=−1−fn−11 - f^2/\pi_{ij} = -\frac{1-f}{n-1}, so by Lemma 1

vHT=1−ff2(∑i∈Syi2−1n−1∑i≠j∈Syiyj)=1−ff2⋅nn−1(∑i∈Syi2−nyˉS2)=N2(1−f)ns2,v_{\mathrm{HT}} = \frac{1-f}{f^2}\Big(\sum_{i \in S}y_i^2 - \frac{1}{n-1}\sum_{i \ne j \in S}y_iy_j\Big) = \frac{1-f}{f^2}\cdot\frac{n}{n-1}\Big(\sum_{i \in S}y_i^2 - n\bar y_S^2\Big) = \frac{N^2(1-f)}{n}s^2,

using ∑i≠jyiyj=n2yˉS2−∑iyi2\sum_{i \ne j}y_iy_j = n^2\bar y_S^2 - \sum_i y_i^2. For vSYGv_{\mathrm{SYG}}, the coefficient f2−πijπijf2\frac{f^2 - \pi_{ij}}{\pi_{ij}f^2} equals (1−f)N2n2(n−1)\frac{(1-f)N^2}{n^2(n-1)}, and ∑i<j∈S(yi−yj)2=n(n−1)s2\sum_{i<j \in S}(y_i - y_j)^2 = n(n-1)s^2, which gives the same value. □\square

Cost. HT-ESTIMATE does one division and one addition per sampled unit, 2n2n operations. HT-VARIANCE runs line L7 nn times and line L9 n(n−1)n(n-1) times, and SYG-VARIANCE runs line L13 n(n−1)/2n(n-1)/2 times, each a constant number of operations given πij\pi_{ij}; so both take Θ(n2)\Theta(n^2) time and Θ(1)\Theta(1) extra space. All loops are over the finite set SS, so the procedures terminate. □\square

Complexity

Lines L1 to L4 do one division and one addition per sampled unit: 2n2n operations, Θ(n)\Theta(n) time. Lines L5 to L10 visit all ordered pairs of sampled units, and lines L11 to L14 all unordered pairs, so both take Θ(n2)\Theta(n^2) time if each πij\pi_{ij} can be looked up or computed in O(1)O(1). The extra space is Θ(1)\Theta(1) 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 πi\pi_i and πij\pi_{ij} is the design's cost, not the estimator's. For simple random sampling of nn from NN they are the closed forms n/Nn/N and n(n−1)/(N(N−1))n(n-1)/(N(N-1)). For Bernoulli sampling with unequal probabilities, πij=πiπj\pi_{ij} = \pi_i\pi_j. For a design given as a list of samples and probabilities, as in the example, summing over the list costs Θ(n)\Theta(n) per sample.

Properties

  • Unbiased for every design. The only condition is πi>0\pi_i > 0 for every unit with yi≠0y_i \ne 0. It does not need the design to be simple, stratified or of fixed size.
  • Linear in yy. The estimate of Y+Y′Y + Y' is the sum of the estimates, so the estimate of a domain total is the estimate with yiy_i set to 0 outside the domain, and stratified estimates add over strata.
  • Exact recovery. If yi=c πiy_i = c\,\pi_i for all ii in a fixed-size design, then Y^=cn=Y\hat Y = cn = Y for every sample and the variance is zero. The closer πi\pi_i is to proportional to yiy_i, the smaller the variance; this is the reason for PPS sampling.
  • Simple random sampling. With πi=n/N\pi_i = n/N, Y^=NyˉS\hat Y = N\bar y_S, and both variance estimates reduce to N2(1−f)s2/nN^2(1 - f)s^2/n with f=n/Nf = n/N and s2s^2 the sample variance of the sampled values with divisor n−1n - 1.
  • Not equivariant to a shift. Adding a constant cc to every yiy_i adds c∑i∈S1/πic\sum_{i \in S}1/\pi_i to Y^\hat Y, not cNcN, unless ∑i∈S1/πi=N\sum_{i \in S}1/\pi_i = N for every sample.

Variants and improvements

  • Mean and proportion. Y^/N\hat Y / N estimates the mean, with variance estimate v/N2v/N^2. For a 0-1 variable it estimates a proportion, and it can exceed 1; see the pitfalls.
  • Hájek ratio. yˉ^H=∑i∈S(yi/πi)/∑i∈S(1/πi)\hat{\bar y}_{\mathrm{H}} = \sum_{i \in S} (y_i/\pi_i) \big/ \sum_{i \in S} (1/\pi_i) divides by the estimate N^\hat N of NN instead of NN. It is a ratio of two unbiased estimates, so it is biased: in the example its mean is 2159/396≈5.4522159/396 \approx 5.452 against the true mean 5.255.25. 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, πij=πiπj\pi_{ij} = \pi_i\pi_j for i≠ji \ne j, so all cross terms vanish: Var⁡[Y^]=∑i(1−πi)yi2/πi\operatorname{Var}[\hat Y] = \sum_i (1 - \pi_i)y_i^2/\pi_i and vHT=∑i∈S(1−πi)yi2/πi2v_{\mathrm{HT}} = \sum_{i \in S}(1 - \pi_i)y_i^2/\pi_i^2. The sample size is random, so vSYGv_{\mathrm{SYG}} does not apply.
  • A normal interval. For large samples from designs where a central limit theorem holds, Y^±z1−α/2v\hat Y \pm z_{1-\alpha/2}\sqrt{v} is an approximate 1−α1 - \alpha 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 1/πi1/\pi_i 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 yy. Under simple random sampling it is the ordinary expansion estimate NyˉSN\bar y_S. When yy is not related to the πi\pi_i, 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 πi=0\pi_i = 0. A unit that can never be sampled is missing from every estimate, and E[Y^]=Y−∑πi=0yi\mathbb{E}[\hat Y] = Y - \sum_{\pi_i = 0} y_i. No weighting can repair a frame that leaves units out.
  • Pairs with πij=0\pi_{ij} = 0. In systematic sampling, many pairs never occur together. Then neither vHTv_{\mathrm{HT}} nor vSYGv_{\mathrm{SYG}} can be computed, and dropping the missing terms gives a biased estimate of the variance.
  • Negative variance estimates. vHTv_{\mathrm{HT}} can be negative, as for the samples {1,3}\{1, 3\} and {2,3}\{2, 3\} of the example. vSYGv_{\mathrm{SYG}} is nonnegative when πij≤πiπj\pi_{ij} \le \pi_i\pi_j 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 y=(1,1,0,1)y = (1, 1, 0, 1), the true proportion is 3/43/4, but the sample {1,2}\{1, 2\} gives (1/0.4+1/0.4)/4=1.25(1/0.4 + 1/0.4)/4 = 1.25. The Hájek ratio gives 1 on the same sample.
  • The wrong probabilities. The πi\pi_i must be those of the design actually used. Successive draws proportional to size, for instance, do not give πi\pi_i proportional to size; the PPS page shows the bias that follows.
  • With-replacement formulas. In mm independent draws with probabilities pip_i, the Hansen-Hurwitz estimator divides each draw by mpim p_i. The Horvitz-Thompson estimator applies to the set of distinct units, with πi=1−(1−pi)m\pi_i = 1 - (1 - p_i)^m. Mixing the two, by using mpim p_i as πi\pi_i for the distinct units or by counting a unit once per draw with weight 1/πi1/\pi_i, 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 99/10099/100 and each of the other 49 with probability 1/49001/4900 makes Y^\hat Y about 1.011.01 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 s2s^2 in the simple random sampling formula uses n−1n - 1, and the population S2S^2 in Var⁡[Y^]=N2(1−f)S2/n\operatorname{Var}[\hat Y] = N^2(1 - f)S^2/n uses N−1N - 1. 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.

horvitz_thompson_estimator.pyI0RawGitHub
# 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 ∑i∈Syi/πi\sum_{i \in S} y_i/\pi_i, its variance in terms of the πij\pi_{ij}, 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 vSYGv_{\mathrm{SYG}}. 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

  1. 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)
  2. On the estimate of the variance in sampling with varying probabilities, the whole paper (the variance estimator for fixed-size designs)
  3. 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)
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example