Module contents
Lesson 3 of 27Core 80 min

Survey sampling design: simple random, stratified, cluster and weighted

Study how observations are drawn from a finite population and how design determines estimator precision and bias. Cover simple random sampling with finite population correction, stratification with optimal Neyman allocation, clusters and design effect, Horvitz–Thompson estimation for unequal inclusion probabilities, and selection biases no sample size can correct.

After this lesson you can

  • Calculate variance of the sample mean without replacement with finite population correction.
  • Design a stratified sample with proportional and Neyman allocation and quantify precision gains.
  • Estimate cluster design effect from intraclass correlation and obtain effective sample size.
  • Implement Horvitz–Thompson estimation, prove unbiasedness, and measure precision loss from extreme weights (Kish effective size).
  • Diagnose selection, survivorship, and nonresponse biases in surveys, ML datasets, and backtests.

Before you start

Motivation: auditing 300 of 1000 repositories

Your organization has 1000 repositories and you want the mean number of critical findings per repository. Auditing all costs too much, so you choose 300, audit them, and calculate the mean. How much can you trust that number?

The previous lesson’s answer is standard error: if the 300 observations are independent draws from a law with standard deviation σ\sigma, typical mean error is σ/300\sigma/\sqrt{300}. But that formula describes a model in which data come from a law PθP_\theta, and that is not what you did: you took 30% of a specific finite population whose 1000 values already exist and are not random. Only which ones you chose is random. If you audited 999 instead of 300, the mean would be almost exact, and σ/999\sigma/\sqrt{999} would still predict error. Something fails: the formula, not intuition.

The same problem appears everywhere, even when you do not call it a “survey”:

  • Data labeling. You have a million-document unlabeled corpus and a budget to label 5000. Which do you choose, and how do you then estimate model error over the whole corpus?
  • Evaluation and validation. Test examples are rarely independent: they come from the same documents, users, or sessions. How many independent examples do you actually have?
  • Backtests. You study performance of funds or companies that exist today. What have you unknowingly left out?
  • Training data. Records from a production system are what that system chose to show, approve, or retain. They are not a sample of “all cases.”

This lesson answers four questions, each with a design and result:

  1. If you sample a large fraction without replacement, how much precision do you gain? (simple random sampling and finite population correction)
  2. If you know something about every unit before sampling, can you allocate the sample more intelligently? (stratification and Neyman allocation)
  3. If sampling groups (teams, hospitals, documents) is cheap, what does similarity among group members cost? (clusters and effective size)
  4. If some units are more likely to enter than others, how do you correct it, and what if entry probability depends on what you measure? (Horvitz–Thompson and selection bias)

The unifying idea is useful from the start: in sampling, randomness comes from the design, not nature. You control the lottery, so you can calculate what happens on average over it. When you do not control it (self-selection, survival, nonresponse), you lose precisely that.

Finite population, design, and inclusion probabilities

Everything following comes from three indicator identities: EIi=πi\E I_i = \pi_i, Var⁡(Ii)=πi(1−πi)\Var(I_i) = \pi_i(1 - \pi_i), and Cov⁡(Ii,Ij)=πij−πiπj\Cov(I_i, I_j) = \pi_{ij} - \pi_i\pi_j. An estimator such as ∑iIiai\sum_i I_i a_i (with constant aia_i) has expectation ∑iπiai\sum_i \pi_i a_i and, by variance of a sum, variance ∑i∑jaiaj Cov⁡(Ii,Ij)\sum_i\sum_j a_ia_j\,\Cov(I_i, I_j). The lesson’s four designs are four ways of choosing πij\pi_{ij}.

This changes the meaning of “unbiased.” In a statistical model averaging is over realizations of PθP_\theta. Here it is over the design: an estimator is design-unbiased if Ep[θ^]=θ(y1,…,yN)\E_p[\hat\theta] = \theta(y_1, \dots, y_N) for every value vector yy. This powerful guarantee requires no assumption about the yiy_i, making it standard in surveys. Its price is that it only addresses a well-defined population and known selection mechanism. When the “population” is hypothetical (next year’s customers), the bridge from sample to target is another modeling assumption and should be stated explicitly.

Simple random sampling and finite population correction

Proof

(1) Since ∑iIi=n\sum_i I_i = n always and all units are exchangeable by symmetry, n=E∑iIi=Nπin = \E\sum_i I_i = N\pi_i. Squaring, n2=E(∑iIi)2=∑iπi+∑i≠jπij=n+N(N−1)πijn^2 = \E(\sum_i I_i)^2 = \sum_i \pi_i + \sum_{i \ne j}\pi_{ij} = n + N(N-1)\pi_{ij}, giving πij\pi_{ij}. Then Cov⁡(Ii,Ij)=n(n−1)N(N−1)−n2N2=−nN⋅N−nN⋅1N−1\Cov(I_i, I_j) = \frac{n(n-1)}{N(N-1)} - \frac{n^2}{N^2} = -\frac{n}{N}\cdot\frac{N-n}{N}\cdot\frac{1}{N-1}.

(2) Eyˉs=1n∑iπiyi=1n⋅nN∑iyi=yˉU\E\bar y_s = \frac1n\sum_i \pi_i y_i = \frac1n\cdot\frac nN\sum_i y_i = \bar y_U.

(3) With yˉs=1n∑iIiyi\bar y_s = \frac1n\sum_i I_iy_i and moments from (1),

Var⁡(yˉs)=1n2[f(1−f)∑iyi2−f(1−f)N−1∑i≠jyiyj].\Var(\bar y_s) = \frac{1}{n^2}\Big[f(1-f)\sum_i y_i^2 - \frac{f(1-f)}{N-1}\sum_{i \neq j}y_iy_j\Big].

Using ∑i≠jyiyj=(∑iyi)2−∑iyi2\sum_{i \ne j}y_iy_j = (\sum_i y_i)^2 - \sum_i y_i^2, the bracket is f(1−f)NN−1[∑iyi2−1N(∑iyi)2]=f(1−f)NS2\frac{f(1-f)N}{N-1}\big[\sum_i y_i^2 - \frac1N(\sum_i y_i)^2\big] = f(1-f)N S^2. Since fN=nfN = n, this leaves (1−f)S2/n(1-f)S^2/n.

(4) (n−1)s2=∑iIiyi2−nyˉs2(n-1)s^2 = \sum_i I_iy_i^2 - n\bar y_s^2. Its expectation is f∑iyi2−n[(1−f)S2n+yˉU2]f\sum_i y_i^2 - n\big[\frac{(1-f)S^2}{n} + \bar y_U^2\big]. Substitute ∑iyi2=(N−1)S2+NyˉU2\sum_i y_i^2 = (N-1)S^2 + N\bar y_U^2 and use fN=nfN = n: the yˉU2\bar y_U^2 terms cancel, leaving S2[f(N−1)−(1−f)]=(n−1)S2S^2[f(N-1) - (1-f)] = (n-1)S^2.

∎

The factor 1−f1 - f is the finite population correction. It says something intuitive: each unit you inspect is one you no longer need to guess, and when n=Nn = N nothing remains to estimate. With replacement variance is σ2/n\sigma^2/n with σ2=N−1NS2\sigma^2 = \frac{N-1}{N}S^2, the usual iid formula. Without replacement it is smaller by factor (1−f)NN−1(1-f)\frac{N}{N-1} because Cov⁡(Ii,Ij)<0\Cov(I_i, I_j) < 0: one unit’s inclusion makes another’s slightly less likely, and deviations compensate.

For the motivating repositories, N=1000N = 1000, n=300n = 300, and S=6S = 6 findings: typical error is 0.7⋅36/300=0.290\sqrt{0.7 \cdot 36/300} = 0.290, while the iid formula gives 6/300=0.3466/\sqrt{300} = 0.346, almost 20% more. The first figure shows the mechanism.

InteractiveThe finite population correction
Population (N=200N = 200) and sample n=60n = 60: yˉs=23.93\bar y_s = 23.93 versus yˉU=22.03\bar y_U = 22.03
  • low value
  • high value
  • outlined and opaque: in sample
Distribution of yˉ\bar y in 3000 samples
true mean
  • without replacement
  • with replacement
  • sample on the left
  • theoretical normal (with repl.)
60 (f = 0.30)
Correction 1−n/N1 - n/N0.700
Standard error without replacement (theory and simulation)1.12 and 1.13
Standard error with replacement (theory and simulation)1.34 and 1.34
Variance ratio without / with0.704
You sampled 30 % of the population: ignoring the correction overestimates standard error by 20 %.
A population of 200 units with skewed values. On the right, the distribution of sample mean in 3000 samples with and without replacement; the thin gray curve is the theoretical normal with replacement. With n=60n = 60, typical error without replacement is 16% smaller. Increase nn: when does the correction stop being a detail? What happens at n=200n = 200? Reduce to n=10n = 10: can you distinguish the curves?

Two practical consequences. First: the correction matters only when ff is not small. With f=0.01f = 0.01, the square root of 1−f1 - f is 0.9950.995 and nobody notices. That is why national survey precision depends on nn and hardly on NN: 1000 people out of 300 million and 1000 out of one million are nearly equally precise, and NN does not appear in survey intervals. Second: auditing 30% of repositories or evaluating a model on 40% of a finite labeled set, ignoring the correction makes you pay for 16% or 23% error that does not exist.

Stratification

SRS ignores everything known about units before measuring. If repositories are of three types with very different finding rates, SRS can miss the rare type and, even if it does not, random counts of each type add variance that could have been avoided. Stratification removes that randomness.

Proof

The yˉh\bar y_h are independent because SRS draws in different strata are independent, and each is unbiased for μh\mu_h with variance (1−nh/Nh)Sh2/nh(1 - n_h/N_h)S_h^2/n_h by the SRS theorem. A weighted mean of unbiased estimators with fixed weights is unbiased, and variance of an independent linear combination is the sum of Wh2W_h^2 times each variance.

∎

When stratification wins

Compare with SRS. The law of total variance does the work: population variance splits into what varies within strata and what varies between them. Under proportional allocation everything is explicit.

Proof

The first formula is the preceding theorem with nh/Nh=fn_h/N_h = f. For the second, total sum of squares splits into within and between: (N−1)S2=∑h(Nh−1)Sh2+∑hNh(μh−yˉU)2(N-1)S^2 = \sum_h (N_h - 1)S_h^2 + \sum_h N_h(\mu_h - \bar y_U)^2. Then (N−1)[S2−∑hWhSh2]=∑hNh(μh−yˉU)2+∑h(Nh−1)Sh2−N−1N∑hNhSh2(N-1)\big[S^2 - \sum_h W_hS_h^2\big] = \sum_h N_h(\mu_h - \bar y_U)^2 + \sum_h(N_h - 1)S_h^2 - \frac{N-1}{N}\sum_h N_hS_h^2, and the Sh2S_h^2 terms sum to −∑h(1−Wh)Sh2-\sum_h(1 - W_h)S_h^2. Multiply by (1−f)/n(1-f)/n.

∎

Except for a term of order 1/N1/N, proportional allocation never loses, and its gain is (1−f)/n(1-f)/n times between-stratum variance, ∑hWh(μh−yˉU)2\sum_h W_h(\mu_h - \bar y_U)^2. The more different stratum means and the more similar units within each stratum, the greater the gain. This guides stratum choice: it must be a variable known before measurement and as correlated with yy as possible.

But proportional allocation treats a stratum of 1000 nearly identical units the same as one of 1000 erratic units. That seems wasteful: should more sample not go where there is more to learn?

Neyman’s optimal allocation

Proof

With ah=WhSha_h = W_hS_h, (1−nh/Nh)Wh2Sh2/nh=ah2/nh−WhSh2/N(1 - n_h/N_h)W_h^2S_h^2/n_h = a_h^2/n_h - W_hS_h^2/N, and the second term does not depend on nhn_h. Minimize ∑hah2/nh\sum_h a_h^2/n_h subject to ∑hnh=n\sum_h n_h = n. By Cauchy-Schwarz on vectors (ah/nh)h(a_h/\sqrt{n_h})_h and (nh)h(\sqrt{n_h})_h,

(∑hah)2≤(∑hah2nh)(∑hnh)=n∑hah2nh,\Big(\sum_h a_h\Big)^2 \le \Big(\sum_h \frac{a_h^2}{n_h}\Big)\Big(\sum_h n_h\Big) = n\sum_h\frac{a_h^2}{n_h},

with equality if and only if ah/nha_h/\sqrt{n_h} is proportional to nh\sqrt{n_h}, or nh∝ahn_h \propto a_h. This gives the allocation and minimum. Difference from proportional is 1n[∑hWhSh2−(∑hWhSh)2]\frac1n\big[\sum_h W_hS_h^2 - (\sum_h W_hS_h)^2\big], variance of ShS_h when stratum hh is chosen with probability WhW_h.

∎

The rule is simple: more sample where there are more units and more variability, in proportion to NhShN_hS_h. With different per-unit costs chc_h, the optimum is nh∝NhSh/chn_h \propto N_hS_h/\sqrt{c_h}: spend less on expensive units. In practice the theorem ignores three details. An optimal allocation may request more units than a stratum has (nh>Nhn_h > N_h): fix nh=Nhn_h = N_h (a stratum census) and allocate the rest. Estimating Sh2S_h^2 requires nh≥2n_h \ge 2. And nhn_h are integers: round by largest remainders. Implement it in the code exercise.

The next figure lets you manipulate the entire population. Three sliders control strata; budget nn too. Three presets isolate the two sources of gain.

InteractiveHow much stratification gains
The three strata: mean, ±Sh\pm S_h and a sample of units
stratum 1: 50 % of populationstratum 2: 33 % of populationstratum 3: 17 % of population
Budget allocation nhn_h
755025Proportional274380Neyman
Distribution of estimated mean in 2000 samples
  • SRS
  • proportional stratified
  • Neyman stratified
  • population mean
SRS variance (per unit of nn), sources of gain: S2≈674S^2 \approx 674
196202276
  • remaining with Neyman
  • additional gain from Neyman
  • between strata: already gained by proportional allocation
Starting population
150
Stratum 1
1500
8
5
Stratum 2
1000
20
12
Stratum 3
500
55
45
SRS standard error (theory and simulation)2.07 and 1.99
Proportional standard error (theory and simulation)1.59 and 1.62
Neyman standard error (theory and simulation)1.08 and 1.11
Variance gain: proportional and Neyman1.69× and 3.63×
Both sources contribute: differing means (captured by proportional allocation) and differing deviations (only Neyman).
Three strata with adjustable size, mean, and standard deviation. Top left, each stratum (bar from μh−Sh\mu_h - S_h to μh+Sh\mu_h + S_h); below, how each allocation splits the budget. On the right, estimator distribution over 2000 samples and, below, the sources of gain from SRS to optimum. Start with 'Means only': how do proportional and Neyman differ? Switch to 'Standard deviations only': what happens to proportional? Return to 'Base' and raise S3S_3: do large or variable strata receive the sample?

With the base population, n=150n = 150 and three strata of 1500, 1000, and 500 units with standard deviations 5, 12, and 45, proportional allocation is (75,50,25)(75, 50, 25) and Neyman (27,43,80)(27, 43, 80): the smallest stratum, 17% of the population, receives 53% of the sample because it adds the most noise. Typical error falls from 2.072.07 (SRS) to 1.591.59 (proportional) and 1.081.08 (Neyman): variance is 1.71.7 times lower with proportional and 3.63.6 with optimal allocation. The two mechanisms are independent: under “Means only” proportional captures everything and Neyman adds nothing, while under “Standard deviations only” proportional gains nothing and Neyman gains entirely.

Clusters

Sampling individual units requires a full list and traveling to each. Sampling groups is often cheaper: development teams, hospitals, schools, corpus documents, user sessions. Choose a few groups and inspect all or some members. It is much cheaper, but has a systematically underestimated statistical cost.

Proof

Apply the law of total variance conditioning on selected clusters ss. Given ss, expectation of yˉ\bar y is the mean of the kk true cluster means: the sample mean of an SRS of kk values from a population of KK, with variance (1−k/K)S12/k(1 - k/K)S_1^2/k by the SRS theorem. Given ss, within-cluster subsamples are independent and each has variance (1−m/M)S2i2/m(1 - m/M)S_{2i}^2/m; hence Var⁡(yˉ∣s)=1k2∑i∈s(1−m/M)S2i2/m\Var(\bar y \given s) = \frac{1}{k^2}\sum_{i \in s}(1 - m/M)S_{2i}^2/m, whose expectation over ss is (1−m/M)S22/(km)(1 - m/M)S_2^2/(km) because the kk clusters are a random sample of the KK.

∎

The formula has two terms with very different roles. The first depends on kk, not mm: adding people to a team already sampled does not reduce it. The second decreases with kmkm but is usually the smaller. To see actual information, compare against an SRS of nn units. The key is correlation between two people in the same cluster.

Proof

The two identities for S12S_1^2 and S22S_2^2 follow by solving for S12S_1^2 and S22S_2^2 in the definitions of ρ\rho and σ2\sigma^2. Substitute in the preceding theorem with k/K≈0k/K \approx 0: the bracket in σ2/(km)\sigma^2/(km) is m [1+(M−1)ρ]/M+(1−m/M)(1−ρ)=1+(m−1)ρm\,[1 + (M-1)\rho]/M + (1 - m/M)(1 - \rho) = 1 + (m-1)\rho. For the bound, since ρ<1\rho < 1, 1+(m−1)ρ>(m−1)ρ+ρ=mρ>01 + (m-1)\rho > (m-1)\rho + \rho = m\rho > 0, and therefore nef=km/(1+(m−1)ρ)<km/(mρ)=k/ρn_{\text{ef}} = km/(1 + (m-1)\rho) < km/(m\rho) = k/\rho.

∎

With teams of m=20m = 20 people and ρ=0.05\rho = 0.05, design effect is 1+19⋅0.05=1.951 + 19 \cdot 0.05 = 1.95: surveying 2000 people is equivalent to 10261026 independent ones. That ρ\rho seems tiny, but ML test sets commonly have values of this order or greater: correlation between two answers from one document, or questions generated from the same source, is often much higher.

InteractiveClusters and effective sample size
60 teams of 20 people, colored by value. Sample: 12 teams, 10 people each
Actual information: nef=n/(1+(m−1)ρ)n_{\text{ef}} = n/(1 + (m-1)\rho) versus ρ\rho, for different mm and the same nn (point: your design)
m = 2m = 5m = 20ceiling: n = 120 (ρ = 0)
Distribution of estimated mean in 2000 samples of equal size nn
  • SRS of nn people
  • 12 teams × 10 people
  • population mean
Variance between team means S12=0.1925S_1^2 = 0.1925 and within-team variance S22=0.8500S_2^2 = 0.8500. The design pays S12/kS_1^2/k for the first stage and only S22/(km)S_2^2/(km) for the second: adding people to an included team does not reduce the first term. The exact design effect differs from 1+(m−1)ρ1 + (m-1)\rho because a substantial fraction of teams is sampled (k/K=0.20k/K = 0.20): the approximation assumes k/K≈0k/K \approx 0.
0.15
12
10
10
People surveyed n=k mn = k\,m120
Design effect: exact and 1+(m−1)ρ1 + (m-1)\rho2.19 and 2.35
Effective size n/deffn/\text{deff}: exact and approximate54.8 and 51.1
SRS and cluster standard error (theory)0.0865 and 0.128
Simulated SRS and cluster standard error0.0872 and 0.131
Optimal mm at this cost: (c1/c2)(1−ρ)/ρ\sqrt{(c_1/c_2)(1-\rho)/\rho}7.5
Every 2.2 respondents are worth one. Using σ/n\sigma/\sqrt{n} would make standard error 1.48 times too small and a 95 % interval cover much less.
60 teams of 20 people, colored by value (blue low, red high): with high ρ\rho, colors cluster by team. Sample kk teams and mm people each. Right, estimator across 2000 samples under the design and an SRS with the same nn. Bottom left, nefn_{\text{ef}} versus ρ\rho. Increase ρ\rho from 0 to 0.4: at what ρ\rho does actual standard error double SRS (design effect 4)? Fix n=120n = 120 and allocate differently (k=6k = 6 and m=20m = 20; k=40k = 40 and m=3m = 3): which design is more precise, and which cheaper at relative cost c1/c2=10c_1/c_2 = 10?

The figure shows the second practical fact: at fixed nn, allocation matters. With ρ=0.15\rho = 0.15 and n=120n = 120, eight teams of 15 people are much less informative than forty of 3. But forty team visits cost more than eight. The optimum when budget is C=k(c1+c2m)C = k(c_1 + c_2m), with c1c_1 the cost of visiting a team and c2c_2 that of one more person, follows by minimizing deff⁡⋅(c1+c2m)/m\operatorname{deff}\cdot(c_1 + c_2m)/m:

(1−ρ+mρ)(c1+c2m)m=(1−ρ)c1m+(1−ρ)c2+ρc1+ρc2m⟹mopt=c1c2⋅1−ρρ.\frac{(1 - \rho + m\rho)(c_1 + c_2m)}{m} = \frac{(1-\rho)c_1}{m} + (1-\rho)c_2 + \rho c_1 + \rho c_2m \quad \Longrightarrow \quad m_{\text{opt}} = \sqrt{\frac{c_1}{c_2}\cdot\frac{1-\rho}{\rho}}.

When visiting a team costs ten times more than asking one extra person and ρ=0.15\rho = 0.15, mopt≈7.5m_{\text{opt}} \approx 7.5. The more similar members are, the less useful it is to persist within each group and the more useful to open new groups.

With unequal cluster sizes, the mean of means ceases to be unbiased and the ratio estimator ∑i∈sti/∑i∈sMi\sum_{i \in s}t_i / \sum_{i\in s}M_i is used; Kish’s approximation deff⁡≈1+(mˉ−1)ρ\operatorname{deff} \approx 1 + (\bar m - 1)\rho with mean size mˉ\bar m remains useful, though very unequal sizes add a penalty.

Unequal probabilities: Horvitz–Thompson estimator

Everything above gave similar units equal inclusion probability. Sometimes unequal probabilities are intentional: a huge repository concentrates more findings than a small one, so it should be more likely to enter (probability proportional to size, PPS). Sometimes they are not: survey respondents differ from nonrespondents. Both cases have different πi\pi_i across units and the simple mean is biased. The natural estimator corrects each unit’s weight.

Proof

(1) This is an exercise in the lesson: one line with indicators.

(2) With ai=yi/πia_i = y_i/\pi_i and cij=Cov⁡(Ii,Ij)=πij−πiπjc_{ij} = \Cov(I_i, I_j) = \pi_{ij} - \pi_i\pi_j, Var⁡(∑iIiai)=∑i∑jcijaiaj\Var(\sum_i I_ia_i) = \sum_i\sum_j c_{ij}a_ia_j.

(3) If ∑jIj=n\sum_j I_j = n is constant, ∑jcij=Cov⁡(Ii,∑jIj)=0\sum_j c_{ij} = \Cov(I_i, \sum_j I_j) = 0 for every ii (including j=ij = i). Then ∑i∑jcij(ai2+aj2)=0\sum_i\sum_j c_{ij}(a_i^2 + a_j^2) = 0 and

12∑i,j(−cij)(ai−aj)2=−12∑i,jcij(ai2+aj2)+∑i,jcijaiaj=∑i,jcijaiaj=Var⁡(t^HT).\tfrac12\sum_{i,j}(-c_{ij})(a_i - a_j)^2 = -\tfrac12\sum_{i,j}c_{ij}(a_i^2 + a_j^2) + \sum_{i,j}c_{ij}a_ia_j = \sum_{i,j}c_{ij}a_ia_j = \Var(\hat t_{\text{HT}}).

Terms with i=ji = j on the left are zero, giving the form with i≠ji \ne j.

∎

Formula (3) tells a clear story. Variance depends on how much ratios yi/πiy_i/\pi_i vary across units. If πi\pi_i is proportional to yiy_i (or something similar, such as repository size), ratios are nearly constant and variance almost disappears: the argument for PPS. If instead πi\pi_i is unrelated to yiy_i, unequal weights add variance without buying anything. Under Poisson sampling, each unit enters by an independent coin flip, πij=πiπj\pi_{ij} = \pi_i\pi_j, leaving ∑i(1−πi)yi2/πi\sum_i (1 - \pi_i)y_i^2/\pi_i.

HT has a weakness: if sample size is random, estimated total fluctuates with it even if all yiy_i were equal. The remedy is the Hájek estimator, a ratio: yˉw=∑i∈swiyi/∑i∈swi\bar y_w = \sum_{i \in s}w_iy_i\big/\sum_{i \in s}w_i. It has small bias, order 1/n1/n, and is usually more stable. It is used with reweighting.

Extreme weights and Kish effective size

Weights have a cost measured by a Kish result (1965).

Proof

Var⁡(yˉw)=∑iwi2σ2/(∑iwi)2=σ2/nef\Var(\bar y_w) = \sum_i w_i^2\sigma^2/(\sum_i w_i)^2 = \sigma^2/n_{\text{ef}}. For the second form, ∑iwi2=nwˉ2(1+CV⁡w2)\sum_i w_i^2 = n\bar w^2(1 + \operatorname{CV}_w^2) and (∑iwi)2=n2wˉ2(\sum_i w_i)^2 = n^2\bar w^2. The inequality is Cauchy-Schwarz: (∑iwi⋅1)2≤∑iwi2⋅n(\sum_i w_i\cdot 1)^2 \le \sum_i w_i^2 \cdot n.

∎

This is an optimistic bound: it assumes yy is unrelated to weights. It still shows the danger. If weights are lognormal with parameter γ\gamma, 1+CV⁡w2=eγ21 + \operatorname{CV}_w^2 = e^{\gamma^2}: with γ=1.2\gamma = 1.2 only 24% of the sample “counts.” The fourth figure compares four mean estimators when inclusion probability rises with a covariate also affecting yy.

InteractiveReweighting: bias, variance, and extreme weights
A sample of 193 units: larger points have greater weight 1/πi1/\pi_i
population mean
  • population (700 units)
  • sample
  • sample mean
  • Hájek
Distribution of each estimator across 1000 samples
  • sample mean
  • Hájek
  • clipped Hájek
  • truth
Top 48 sample weights, in multiples of typical weight N/E[n]=10.5N/\mathbb{E}[n] = 10.5
1.20
200
8.0×
sample mean: bias, deviation and root MSE11.96, 0.66, 11.98
Horvitz-Thompson: bias, deviation and root MSE0.51, 5.79, 5.82
Hájek: bias, deviation and root MSE0.19, 2.24, 2.25
Hájek with clipped weights: bias, deviation and root MSE1.13, 1.51, 1.89
Average Kish effective size versus average nn54 versus 192
Maximum weight in this sample (in typical weights)6.7×
Weighting removes bias (12.0 becomes 0.19) but multiplies variance: Kish effective size is 28 % of actual size. Try clipping weights.
A population of 2000 units with covariate xx and y=50+10x+noisey = 50 + 10x + \text{noise}. Each unit enters with probability πi∝eγxi\pi_i \propto e^{\gamma x_i} (Poisson sampling). Left: one sample, with point size increasing with weight. Top right: distributions of simple mean, Hájek estimator, and Hájek with clipped weights across 1000 samples. Bottom right: largest weights. At γ=1.2\gamma = 1.2, which estimator wins, biased or unbiased? Lower clipping from 'no clipping' to 2 or 3: what do you buy and pay? Raise γ\gamma to 2: what happens to Kish effective size?

The figure shows three things. At γ=0\gamma = 0 every unit has the same πi\pi_i (Bernoulli sampling, which conditional on realized size is SRS): simple mean, Hájek, and clipped coincide, but HT does not, because it divides by expected size and inherits actual-size fluctuation; its deviation is several times larger. This is HT’s weakness from the preceding paragraph, so Hájek is the reference for the rest of the figure. At γ=1.2\gamma = 1.2 the simple mean has bias around 12 points on a truth of 50 and deviation 0.70.7, so total error is all bias. HT and Hájek remove it but pay variance from weights concentrated on unlikely units: the first’s deviation is 5.85.8 (sample size fluctuates) and the second’s 2.22.2, with root MSE five times smaller than the simple mean. Clipping weights (capping them) is a trade: reduce variance while reintroducing bias. With initial cap 8×8\times typical weight, bias rises from 0.20.2 to 1.11.1 and deviation falls from 2.22.2 to 1.51.5: root MSE improves from 2.252.25 to 1.891.89. There is no universally correct cap; bias and variance are traded off and MSE guides selection, as in the next lesson.

When πi\pi_i are unknown because they arise from nonresponse, estimate them, usually by logistic regression of “responded” on variables known for the entire frame: this is inverse probability weighting (IPW). Two cautions. Correction is valid only if, conditional on the variables used, response does not depend on yy; what matters about the mechanism must be in the covariates. And estimated weights can sometimes be more efficient than true ones because estimation recalibrates the sample to the true covariate distribution. The second lab demonstrates this.

Selection biases

So far inclusion probabilities were known. Now they are unknown and also depend on what we measure. An enormous sample does not fix this, and the reason is an exact identity.

The specific mechanisms are few and recur:

  • Survivorship bias. You observe only what still exists: funds that did not close, firms currently in an index, customers who did not leave, published models. Survival is decided after outcomes, so observed outcomes are better than those of the original cohort.
  • Nonresponse. Some respond more than others. In Rubin’s classification data are missing completely at random (MCAR), at random conditional on observed covariates (MAR), or nonignorable (MNAR, depending on the value itself). Reweighting fixes MAR, never MNAR.
  • Self-selection and coverage. Volunteers for a survey are not a random sample; a frame missing part of the population (people without internet) cannot sample them.
  • Dataset bias in machine learning. Training data were generated by a previous system deciding what to see, approve, or label: if a credit model sees only people granted credit, it learns nothing about rejected applicants.

An exact identity

Proof

yˉs−yˉU=∑iRiyin−yˉU=1N∑iRi(yi−yˉU)n/N=Cov⁡U(R,Y)f\bar y_s - \bar y_U = \frac{\sum_i R_i y_i}{n} - \bar y_U = \frac{\frac1N\sum_i R_i(y_i - \bar y_U)}{n/N} = \frac{\Cov_U(R, Y)}{f}, with population covariance (divisor NN). Since Cov⁡U(R,Y)=ρ σRσY\Cov_U(R, Y) = \rho\,\sigma_R\sigma_Y and σR=f(1−f)\sigma_R = \sqrt{f(1-f)}, the ratio is ρ σY(1−f)/f\rho\,\sigma_Y\sqrt{(1-f)/f}.

∎

Read carefully: error is the product of three factors. Data quality ρ\rho, problem difficulty σY\sigma_Y, and data quantity, entering as (N−n)/n\sqrt{(N - n)/n}. A million records reduces the third factor but does not touch the first. And ρ\rho is tiny under good design. Under SRS, ρ\rho is random with Eρ2=1/(N−1)\E\rho^2 = 1/(N-1) (compare the identity with Var⁡(yˉs)=(1−f)S2/n\Var(\bar y_s) = (1-f)S^2/n and rearrange), that is ρ∼±1/N\rho \sim \pm 1/\sqrt{N}: randomization keeps defect correlation of order 1/N1/\sqrt{N}, exactly what is needed for SRS error. A self-selected sample has a fixed ρ\rho that does not decrease with population.

The large sample’s “nominal” interval, calculated as if random, has standard error σY(1−f)/n\sigma_Y\sqrt{(1-f)/n}. Dividing by it, actual error is

z=error realerror tıˊpico nominal=ρN¡sea cual sea n!z = \frac{\text{error real}}{\text{error típico nominal}} = \rho\sqrt{N} \qquad \text{¡sea cual sea } n!

And the SRS size with the same squared error is nef≈n(N−n)ρ2n_{\text{ef}} \approx \dfrac{n}{(N - n)\rho^2}. With N=250N = 250 million, n=106n = 10^6, and ρ=0.005\rho = 0.005: z=79z = 79 and nef≈161n_{\text{ef}} \approx 161. One million responses are worth 161 random ones.

InteractiveSize does not compensate for bias
Percentage estimates (truth: 50 %)
400 random: 40 repetitions and a 95 % CI1 000 000 self-selected: nominal 95 % CI (±0.098 points)error 7.91 points
  • truth
  • random sample
  • self-selected
  • its bias
Error in percentage points versus size (log-log scale)
SRS: standard errorself-selected: actual error
The blue curve is SRS standard error and the large sample’s nominal error. The curves are parallel: actual error is always ρN\rho\sqrt{N} times nominal. An orange point above blue means nn biased observations are worth less than nsn_s random observations.
0.01
1 000 000
400
251 188 643
0.50
Random-sample standard error (points)2.50
Self-selected sample actual error (points)7.91
Its nominal standard error (points)0.0499
Bias in standard errors, ρN\rho\sqrt{N}, and actual coverage of nominal 95 % CI158.5 and 0.0 %
Equivalent random sample of40 people
Crossover: ρ∗\rho^* above which it loses0.0032
If yy is Bernoulli(pp): response rate of y=1y=1 versus y=0y=037.6 % more
The huge sample errs more than the 400-person sample (7.91 versus standard error 2.50 points); its nominal 95 % interval is ±0.0978 points and covers truth 0.0 % of the time. With ρN=158.5\rho\sqrt{N} = 158.5 standard errors of bias, more data do not fix it.
Compare a random sample of nsn_s people with a self-selected sample of nn, whose defect correlation with the variable is ρ\rho. Left: estimates on a line, truth as a vertical line. Right: error versus size on log-log axes; curves are parallel because actual error is ρN\rho\sqrt{N} times nominal. At ρ=0.01\rho = 0.01, a million-person sample loses to 400 random people. Lower ρ\rho to the crossover: what is it? Increase nn to 10810^8: what improves and what does not? What difference in response rates between y=1y = 1 and y=0y = 0 corresponds to a small ρ\rho?

The readout translates ρ\rho into something understandable. With f=0.004f = 0.004 and Bernoulli(0.5) yy, ρ=0.01\rho = 0.01 corresponds to individuals with y=1y = 1 responding 3737% more often than those with y=0y = 0, and crossover with the 400 sample (ρ∗≈0.0032\rho^* \approx 0.0032) to 1111% more. Such a small response difference is normal in any voluntary survey and suffices for the giant sample to lose against 400 random people.

Survivorship bias in a backtest

Survivorship is the most dangerous mechanism in finance and ML because it gives no warning. Simulate 1000 funds with no skill: independent annual returns N(0,152)\Normal(0, 15^2) (in %). At the end of each year a fund closes if that year’s return is below threshold θ\theta.

InteractiveSurvivorship bias in funds
Cumulative return (%) of 45 funds: closed funds in gray (×), survivor mean in orange
××××××××××××××××××××××××××dashed: true average outcome
  • surviving fund
  • closed fund
  • survivor mean
  • truth: μ·t
Mean annual return (%) by observed horizon
  • survivors only
  • entire cohort
  • true μ
-10 %
5
0.0 %
Funds alive after 5 years (of 1000)262
Survivors’ annual mean5.99 %
Survivors’ tt and pp value (against μ=0\mu = 0)20.0 and < 0.0001
Mean of entire cohort, including closed funds0.19 %
True μ\mu0.0 %
No fund has skill (μ = 0), yet the 262 survivors “earn” 6.0 % annually with t=20.0t = 20.0. Any test would give enormous significance. Including closed funds, cohort mean is 0.2 %.
1000 funds without skill: independent annual returns N(μ,152)\Normal(\mu, 15^2), with μ=0\mu = 0. A fund closes if its annual return falls below θ\theta. Left: cumulative trajectories of 45 funds (closed funds in gray), and survivors' mean in orange. Right: mean annual return of survivors and the whole cohort against required years of history. With θ=−10 %\theta = -10\,\% and T=5T = 5: how many remain and what 'skill' is seen? Move TT from 1 to 10. Increase μ\mu to 3: how much is skill and how much selection?

The mechanism is calculable. Each year of a survivor is a return conditional on exceeding θ\theta, so mean annual survivor return converges to E[r∣r≥θ]=σ φ(a)/(1−Φ(a))\E[r \mid r \ge \theta] = \sigma\,\varphi(a)/(1 - \Phi(a)) with a=θ/σa = \theta/\sigma. With θ=−10 %\theta = -10\,\% and σ=15 %\sigma = 15\,\% it is 6.4 %6.4\,\% annually, and on average 1000⋅0.74755≈2331000 \cdot 0.7475^5 \approx 233 of 1000 survive after 5 years. Testing “funds have no skill” on those 233 gives a tt statistic around 20: overwhelming evidence of something nonexistent. In contrast, the mean of the whole cohort (including closed funds’ years until closure) is zero: a fund’s year tt is observed if alive at its start, depending on previous years and independent of that year’s return.

The remedies are the same in all cases. Define the population and cohort before looking at outcomes (all funds existing in 2015, not those existing today). Keep the denominator (who entered, who left, and why). Compare sample to known population margins. And measure when possible: a small clean random sample can estimate ρ\rho and calibrate the rest, as Meng recommends.

Four designs, by simulation

The first lab builds a finite population of 3000 people in 100 teams, with known auxiliary variable (tam, for example repository size) affecting yy, and compares four designs at the same n=120n = 120 over 2000 repetitions: SRS, stratified (tam tertiles) with proportional and Neyman allocation, two-stage (12 teams of 10 people), and systematic PPS with HT estimator. For each it measures bias, actual and theoretical standard deviation, and 95% interval coverage using variance estimated from the sample itself, with the correct and “naive” SRS formulas.

[ ]Four sampling designs from scratch: bias, variance, and coverageBrowser
import numpy as np

rng = np.random.default_rng(7)

# Población finita: 100 equipos de 30 personas. `tam` es una variable auxiliar conocida para TODA la población
# (por ejemplo, el tamaño de cada repositorio); `y` es lo que queremos promediar y solo se mide en la muestra.
K, M = 100, 30
N = K * M
equipo = np.repeat(np.arange(K), M)
tam = rng.lognormal(0.0, 0.5, N)
y = 2 + 6 * tam + rng.normal(0, 1.5, K)[equipo] + rng.normal(0, 1.0, N) * (0.5 + 2.0 * tam)
verdad = y.mean()
S2 = y.var(ddof=1)

def muestras_mas(R, n):
    """R muestras aleatorias simples sin reemplazamiento de n índices de 0..N-1 (ordenando números aleatorios)."""
    return np.argpartition(rng.random((R, N)), n, axis=1)[:, :n]

def neyman(Nh, Sh, n):
    """Afijación de Neyman con restos mayores (sin topes: aquí ningún n_h supera N_h)."""
    ideal = n * Nh * Sh / np.sum(Nh * Sh)
    nh = np.floor(ideal).astype(int)
    for h in np.argsort(-(ideal - nh))[: n - nh.sum()]:
        nh[h] += 1
    return nh

R, n = 2000, 120
z = 1.96
filas = []   # (diseño, estimaciones, DE teórica, SE propio estimado, SE ingenuo estimado)

# ---- 1. MAS ----------------------------------------------------------------------
yy = y[muestras_mas(R, n)]
est = yy.mean(1)
se_hat = np.sqrt((1 - n / N) * yy.var(1, ddof=1) / n)
filas.append(("MAS", est, np.sqrt((1 - n / N) * S2 / n), se_hat, se_hat))

# ---- 2. Estratificado (terciles de `tam`) con afijación proporcional y de Neyman ---------
estrato = np.digitize(tam, np.quantile(tam, [1 / 3, 2 / 3]))
Nh = np.bincount(estrato).astype(float)
W = Nh / N
Sh = np.array([y[estrato == h].std(ddof=1) for h in range(3)])
for nombre, nh in [("Estrat. proporcional", np.round(n * W).astype(int)), ("Estrat. Neyman", neyman(Nh, Sh, n))]:
    est = np.zeros(R)
    var_hat = np.zeros(R)
    for h in range(3):
        idx = np.flatnonzero(estrato == h)
        pos = np.argpartition(rng.random((R, idx.size)), nh[h], axis=1)[:, : nh[h]]
        yh = y[idx][pos]
        est += W[h] * yh.mean(1)
        var_hat += W[h] ** 2 * (1 - nh[h] / Nh[h]) * yh.var(1, ddof=1) / nh[h]
    v_teo = np.sum(W**2 * (1 - nh / Nh) * Sh**2 / nh)
    se_hat = np.sqrt(var_hat)
    filas.append((nombre + f" {tuple(int(v) for v in nh)}", est, np.sqrt(v_teo), se_hat, se_hat))

# ---- 3. Conglomerados bietápico: k equipos y m personas por equipo ---------------------
k, m = 12, n // 12
Y2 = y.reshape(K, M)
cl = np.argpartition(rng.random((R, K)), k, axis=1)[:, :k]                       # (R, k)
pos = np.argpartition(rng.random((R, k, M)), m, axis=2)[:, :, :m]                 # (R, k, m)
ycl = Y2[cl[:, :, None], pos]                                                      # (R, k, m)
medias = ycl.mean(2)
est = medias.mean(1)
S1 = Y2.mean(1).var(ddof=1)
S2w = Y2.var(1, ddof=1).mean()
v_teo = (1 - k / K) * S1 / k + (1 - m / M) * S2w / (k * m)
se_cl = np.sqrt((1 - k / K) * medias.var(1, ddof=1) / k)               # unidad = el equipo
se_iid = np.sqrt((1 - k * m / N) * ycl.reshape(R, -1).var(1, ddof=1) / (k * m))  # ¡ignora los equipos!
filas.append((f"Conglomerados {k}x{m}", est, np.sqrt(v_teo), se_cl, se_iid))

# ---- 4. PPS sistemático con Horvitz-Thompson: pi_i = n tam_i / sum(tam) -----------------
pi = n * tam / tam.sum()
assert pi.max() <= 1, "alguna unidad tendría probabilidad mayor que 1"
orden = rng.permutation(N)
acum = np.cumsum(tam[orden])
paso = acum[-1] / n
puntos = rng.random((R, 1)) * paso + paso * np.arange(n)
sel = orden[np.searchsorted(acum, puntos)]
est = (y[sel] / pi[sel]).sum(1) / N
filas.append(("PPS + Horvitz-Thompson", est, None, None, None))

print(f"verdad = {verdad:.3f}   (N = {N}, n = {n}, {R} muestras por diseño)\n")
print(f"{'diseño':34s} {'sesgo':>7s} {'DE real':>8s} {'DE teoría':>9s} {'cobertura':>10s} {'cob. ingenuo':>12s}")
for nombre, est, sd_teo, se, se_ing in filas:
    sd = est.std(ddof=1)
    cub = f"{100 * np.mean(np.abs(est - verdad) <= z * se):9.1f} %" if se is not None else f"{'n/d':>10s}"
    cub_i = f"{100 * np.mean(np.abs(est - verdad) <= z * se_ing):11.1f} %" if se is not None else f"{'n/d':>12s}"
    teo = f"{sd_teo:9.3f}" if sd_teo is not None else f"{'n/d':>9s}"
    print(f"{nombre:34s} {est.mean() - verdad:7.3f} {sd:8.3f} {teo} {cub} {cub_i}")

The table tells the whole lesson in five rows. All designs are unbiased (biases of hundredths within noise from 2000 repetitions) and actual deviation agrees with the formula for each. Precision differs: SRS typical error is 0.450.45; proportional stratification reduces it to 0.360.36, Neyman to 0.340.34 (allocating (28,32,60)(28, 32, 60), more to high-tam, the variable stratum), and PPS with HT to 0.260.26 because yy is almost proportional to tam. Clusters are worst, 0.630.63: design effect is (0.63/0.45)2≈2(0.63/0.45)^2 \approx 2. The final comparison is the warning: with the correct formula (team as unit), interval coverage is 91.591.5% (below 95% because k=12k = 12 teams are too few for a normal approximation), and with the naive one only 8181%.

The second lab reweights a biased sample. Invite N=8000N = 8000 people, knowing covariate xx for all; they respond with increasing probability ϕ(x)\phi(x), and yy also rises with xx. Compare simple mean to Hájek with true weights, weights estimated by logistic regression fit from scratch (Newton-Raphson, or IRLS), and estimated weights clipped at the 95th percentile.

[ ]Reweighting a biased sample: true, estimated, and clipped weightsBrowser
import numpy as np

rng = np.random.default_rng(11)

N = 8000
x = rng.normal(size=N)                       # covariable conocida para todo el marco (invitados)
y = 50 + 10 * x + 6 * rng.normal(size=N)     # solo se observa en quienes responden
verdad = y.mean()

def sigmoide(t):
    return 1 / (1 + np.exp(-t))

def ajusta_logistica(x, r, iters=8):
    """Regresión logística de r sobre (1, x) por Newton-Raphson (IRLS), desde cero."""
    X = np.column_stack([np.ones_like(x), x])
    b = np.zeros(2)
    for _ in range(iters):
        p = sigmoide(X @ b)
        H = X.T @ (X * (p * (1 - p))[:, None])
        b = b + np.linalg.solve(H, X.T @ (r - p))
    return b

def kish(w):
    """Tamaño efectivo de Kish: (suma de pesos)^2 / suma de pesos al cuadrado."""
    return w.sum() ** 2 / (w**2).sum()

def una_encuesta(gamma, rng):
    phi = sigmoide(-2.3 + gamma * x)                      # probabilidad de responder
    r = rng.random(N) < phi
    yr, xr = y[r], x[r]
    b = ajusta_logistica(x, r.astype(float))              # phi se estima con TODO el marco
    phi_hat = sigmoide(b[0] + b[1] * xr)
    out = {"simple": yr.mean()}
    for nombre, w in [("IPW phi real", 1 / phi[r]), ("IPW phi estimada", 1 / phi_hat)]:
        out[nombre] = np.sum(w * yr) / np.sum(w)          # estimador de Hájek
    w = 1 / phi_hat
    wr = np.minimum(w, np.quantile(w, 0.95))
    out["IPW recortado (P95)"] = np.sum(wr * yr) / np.sum(wr)
    return out, r.sum(), kish(w)

print(f"verdad = {verdad:.3f}\n")
for gamma in [0.0, 0.5, 1.0, 1.5]:
    res, n_r, k_r = [], [], []
    for _ in range(150):
        o, n, k = una_encuesta(gamma, rng)
        res.append(o); n_r.append(n); k_r.append(k)
    print(f"gamma = {gamma}: respondentes ~ {np.mean(n_r):.0f}, tamaño efectivo de Kish ~ {np.mean(k_r):.0f}")
    for clave in res[0]:
        v = np.array([o[clave] for o in res])
        print(f"   {clave:22s} sesgo {v.mean() - verdad:7.3f}   DE {v.std(ddof=1):6.3f}   raíz ECM {np.sqrt(np.mean((v - verdad) ** 2)):6.3f}")

Three observations. (1) At γ=0\gamma = 0 there is no selection and all biases are zero. (2) As soon as γ>0\gamma > 0, simple mean bias is 44 to 1010 points with tiny deviation (root MSE is bias), while true weights remove it and deviation grows from 0.470.47 to 1.11.1 as Kish effective size falls from 0.81n0.81n to 0.24n0.24n (with estimated weights). (3) Estimated weights give smaller deviation than true ones in every case: logistic regression recalibrates the sample to the frame’s xx distribution, correcting random xx fluctuations among respondents too. Clipping at the 95th percentile reduces deviation at the cost of 0.50.5 to 33 points of bias: at γ=1.5\gamma = 1.5 root MSE is 9.99.9 for simple mean, 3.03.0 for clipped, and 1.01.0 for estimated unclipped weights. Clipping buys stability; it is not free.

With libraries

With pandas, stratified sampling is groupby(...).sample(...) and design weights are a column. With scikit-learn, propensity is a LogisticRegression and stratified validation splits are in StratifiedShuffleSplit.

[ ]Stratification with pandas, IPW with scikit-learn, and stratified validationBrowser
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedShuffleSplit, ShuffleSplit

rng = np.random.default_rng(3)

# 1) Muestreo estratificado con pandas: una fila por unidad y una columna de estrato
N = 6000
df = pd.DataFrame({"estrato": rng.choice(["A", "B", "C"], N, p=[0.6, 0.3, 0.1])})
S = {"A": 5.0, "B": 12.0, "C": 45.0}
df["y"] = df["estrato"].map({"A": 8.0, "B": 20.0, "C": 55.0}) + df["estrato"].map(S) * rng.normal(size=N)
Nh = df["estrato"].value_counts().sort_index()
Sh = df.groupby("estrato")["y"].std()
nh = (200 * Nh * Sh / (Nh * Sh).sum()).round().astype(int)
print("Afijación de Neyman con n = 200:", nh.to_dict())
muestra = pd.concat([g.sample(nh[h], random_state=1) for h, g in df.groupby("estrato")])
muestra["peso"] = muestra["estrato"].map(Nh / nh)                   # pesos de diseño N_h / n_h
est = np.average(muestra["y"], weights=muestra["peso"])
print(f"media estratificada (ponderada) {est:.2f}   media simple de la muestra {muestra['y'].mean():.2f}   verdad {df['y'].mean():.2f}")

# 2) Propensity scores con scikit-learn y pesos inversos
x = rng.normal(size=(5000, 2))
y = 50 + 10 * x[:, 0] + 4 * x[:, 1] + rng.normal(0, 6, 5000)
resp = rng.random(5000) < 1 / (1 + np.exp(2.3 - 1.0 * x[:, 0] - 0.5 * x[:, 1]))
modelo = LogisticRegression(C=1e6).fit(x, resp)                      # sin regularizar, para parecerse a la versión a mano
w = 1 / modelo.predict_proba(x[resp])[:, 1]
print(f"\nverdad {y.mean():.2f}   simple {y[resp].mean():.2f}   IPW {np.average(y[resp], weights=w):.2f}   Kish {w.sum()**2 / (w**2).sum():.0f} de {resp.sum()}")

# 3) Validación estratificada: la fracción de positivos en el test, con y sin estratificar
yc = (rng.random(1000) < 0.05).astype(int)
Xc = np.zeros((1000, 1))
for nombre, cv in [("ShuffleSplit", ShuffleSplit(n_splits=300, test_size=100, random_state=0)),
                   ("StratifiedShuffleSplit", StratifiedShuffleSplit(n_splits=300, test_size=100, random_state=0))]:
    frac = [yc[te].mean() for _, te in cv.split(Xc, yc)]
    print(f"{nombre:24s} fracción de positivos en test: media {np.mean(frac):.4f}, DE {np.std(frac, ddof=1):.4f}")
p = yc.mean()
print(f"DE teórica sin estratificar (hipergeométrica): {np.sqrt(p * (1 - p) / 100 * (1 - 100 / 1000) * 1000 / 999):.4f}")

All three results fit theory. Under Neyman allocation, stratum C (10% of the population, deviation 45) receives 84 of 200 units, and the simple sample mean (31.831.8) doubles truth (16.216.2) while the weighted mean (16.816.8) is 0.60.6 away, within its typical error of 0.80.8: the warning about stratifying without weights in numbers. IPW with scikit-learn propensity corrects the mean from 59.059.0 to 50.950.9 against truth 50.250.2, with effective size 316 out of 674 respondents. Stratified validation completely removes noise in test-set positive proportion, which under ordinary ShuffleSplit fluctuates with hypergeometric standard deviation 0.0220.022 on proportion 0.060.06, 37% relative: this is class stratification, and why StratifiedKFold is the default for imbalanced classes.

Connections to machine learning

The four designs recur in data work under other names.

Stratified and grouped cross-validation. Stratifying by label keeps class proportion in each fold, exactly the stratified SRS of the preceding lab. Grouping by document, user, or patient is cluster sampling in reverse: examples from one group are one unit of information, and if they occur in both training and test, the test is not independent. GroupKFold respects ρ\rho.

Sampling for labeling. To estimate model error over an unlabeled corpus, stratify examples by model confidence and label more where uncertainty is higher. This is Neyman allocation with Sh=ph(1−ph)S_h = \sqrt{p_h(1 - p_h)}, where php_h is stratum error rate: nh∝Nhph(1−ph)n_h \propto N_h\sqrt{p_h(1-p_h)}. The final estimate uses weights Nh/nhN_h/n_h, or Horvitz–Thompson. Without weights measured error describes the oversampled sample, not the corpus.

Causal inference and importance sampling. Inverse propensity weighting is the same idea with another interpretation: “treatment” or “response” is the selection mechanism. It returns in m27 as IPW with the same benefits (unbiasedness under ignorability) and cost (extreme weights, measured by Kish effective size). Importance sampling in m29 uses weights similarly, a density ratio rather than 1/πi1/\pi_i. In m28, survivorship bias is the classic source of optimistic backtests.

Common mistakes

Exercises

QuizWhen finite population correction matters
A simple random sample without replacement of nn units out of NN is audited. Which statements are true?

More than one answer may be correct.

NumericStandard error in an audit
An organization has N=2000N = 2000 repositories with S=12S = 12 findings (population standard deviation with divisor N−1N - 1). An SRS without replacement of n=600n = 600 is audited. What is the sample mean's standard error? (Three decimals.)
NumericNeyman allocation
A population has three strata with Nh=(6000,3000,1000)N_h = (6000, 3000, 1000) and standard deviations Sh=(10,20,60)S_h = (10, 20, 60). With budget n=500n = 500, how many units does Neyman allocation assign (without rounding) to the third stratum?
NumericEffective sample size
Survey 2000 people in clusters of m=20m = 20 with intraclass correlation ρ=0.05\rho = 0.05. What is effective sample size? (Approximation deff⁡=1+(m−1)ρ\operatorname{deff} = 1 + (m-1)\rho.)
NumericKish effective size
In a sample of 100 units, 90 have weight 1 and 10 have weight 10. What is the Kish effective size of the weighted mean?
NumericA million biased responses
A self-selected survey obtains n=2×106n = 2\times 10^6 responses in a population of N=2.5×108N = 2.5\times 10^8, with defect correlation ρ=0.002\rho = 0.002. What simple random sample size would have the same mean squared error? Use nef=n/((N−n)ρ2)n_{\text{ef}} = n/\big((N - n)\rho^2\big).
QuizStandard error of a team survey
Survey 30 people in each of 20 randomly chosen teams (n=600n = 600), and compute mean score as if they were 600 independent observations, with standard error 0.0400.040. Estimate ρ≈0.1\rho \approx 0.1 and teams are a small fraction of all teams. Which standard-error procedures are valid?

More than one answer may be correct.

QuizIdentify the dominant bias
Three scenarios: (A) a customer-churn model trains only on customers still active; (B) a backtest uses current stock-index constituents for the last 20 years; (C) a voluntary online survey of product satisfaction. What bias dominates each?
ProofHorvitz–Thompson is unbiased
Prove: For any sampling design with πi>0\pi_i > 0 for every unit i∈Ui \in U, estimator t^HT=∑i∈syi/πi\hat t_{\text{HT}} = \sum_{i \in s} y_i/\pi_i satisfies E t^HT=∑i∈Uyi\E\,\hat t_{\text{HT}} = \sum_{i \in U} y_i.
0
Population values yiy_i are constant; randomness is only in sample ss.

Step 1 of 3. How do you rewrite the sample sum so you can take expectations?

ProofDerive Neyman allocation
Prove: Among all real allocations with ∑hnh=n\sum_h n_h = n, variance of yˉst\bar y_{\text{st}} is minimized at nh∝WhShn_h \propto W_hS_h.
0
Use Var⁡(yˉst)=∑hWh2(1−nh/Nh)Sh2/nh\Var(\bar y_{\text{st}}) = \sum_h W_h^2(1 - n_h/N_h)S_h^2/n_h and Cauchy-Schwarz.

Step 1 of 3. How do you reduce the problem to minimizing one sum?

CodeInteger Neyman allocation
Implement neyman_entera(Nh, Sh, n, minimo=2), returning a list of integer n_h summing exactly to n. Algorithm: (1) ideal allocation is proportional to Nh[h] * Sh[h]; (2) strata with ideal below minimo are fixed at min(minimo, Nh[h]), and those above Nh[h] at Nh[h]; (3) repeat ideal allocation of the remaining budget among free strata until none changes; (4) round free strata by largest remainders (first the integer part of each ideal, then missing ones to largest fractional parts; ties go to lower index). Use only NumPy or the standard library.
def neyman_entera(Nh, Sh, n, minimo=2):
  """Devuelve la lista de enteros n_h con suma n, mínimo 2 por estrato y tope Nh[h]."""
  # tu código
  return [0] * len(Nh)
Shift+Enter to run

Summary

Key idea
In sampling randomness comes from design, and everything reduces to inclusion-indicator moments: EIi=πi\E I_i = \pi_i and Cov⁡(Ii,Ij)=πij−πiπj\Cov(I_i, I_j) = \pi_{ij} - \pi_i\pi_j. SRS without replacement has variance (1−n/N)S2/n(1 - n/N)S^2/n; stratification removes between-stratum variance, and Neyman allocation (nh∝NhShn_h \propto N_hS_h) also the spread of standard deviations; cluster sampling costs design effect 1+(m−1)ρ1 + (m-1)\rho; with unequal probabilities, Horvitz–Thompson ∑yi/πi\sum y_i/\pi_i is unbiased at the cost of weight variance. No sample size corrects selection bias: error is ρ σY(N−n)/n\rho\,\sigma_Y\sqrt{(N-n)/n} and bias in standard errors is ρN\rho\sqrt{N} regardless of nn.
  • Variance of an SRS mean is (1−f)S2/n(1 - f)S^2/n with f=n/Nf = n/N; correction matters only when ff is not small (auditing 30% of repositories reduces error by 16%).
  • Proportional stratification gains between-stratum variance; Neyman adds variance of standard deviations ∑hWh(Sh−Sˉ)2/n\sum_h W_h(S_h - \bar S)^2/n. Nonproportional allocation requires weighting.
  • Clusters: nef=n/(1+(m−1)ρ)n_{\text{ef}} = n/(1 + (m-1)\rho) and nef<k/ρn_{\text{ef}} < k/\rho; calculate standard error with cluster as unit, and mopt=(c1/c2)(1−ρ)/ρm_{\text{opt}} = \sqrt{(c_1/c_2)(1-\rho)/\rho}.
  • Horvitz–Thompson is unbiased for any design with πi>0\pi_i > 0; Kish effective size (∑w)2/∑w2(\sum w)^2/\sum w^2 measures the loss from extreme weights and clipping trades bias for variance.
  • Selection biases: Meng’s identity yˉs−yˉU=ρσY(N−n)/n\bar y_s - \bar y_U = \rho\sigma_Y\sqrt{(N-n)/n} is exact. A million responses with ρ=0.005\rho = 0.005 are worth about 160 random ones, and surviving funds appear profitable even if none has skill.
  • Reweighting fixes selection on observed variables (MAR), never selection depending on the value itself (MNAR); define population and cohort before examining outcomes.