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 , typical mean error is . But that formula describes a model in which data come from a law , 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 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:
- If you sample a large fraction without replacement, how much precision do you gain? (simple random sampling and finite population correction)
- If you know something about every unit before sampling, can you allocate the sample more intelligently? (stratification and Neyman allocation)
- If sampling groups (teams, hospitals, documents) is cheap, what does similarity among group members cost? (clusters and effective size)
- 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: , , and . An estimator such as (with constant ) has expectation and, by variance of a sum, variance . The lesson’s four designs are four ways of choosing .
This changes the meaning of “unbiased.” In a statistical model averaging is over realizations of . Here it is over the design: an estimator is design-unbiased if for every value vector . This powerful guarantee requires no assumption about the , 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 always and all units are exchangeable by symmetry, . Squaring, , giving . Then .
(2) .
(3) With and moments from (1),
Using , the bracket is . Since , this leaves .
(4) . Its expectation is . Substitute and use : the terms cancel, leaving .
∎The factor is the finite population correction. It says something intuitive: each unit you inspect is one you no longer need to guess, and when nothing remains to estimate. With replacement variance is with , the usual iid formula. Without replacement it is smaller by factor because : one unit’s inclusion makes another’s slightly less likely, and deviations compensate.
For the motivating repositories, , , and findings: typical error is , while the iid formula gives , almost 20% more. The first figure shows the mechanism.
Two practical consequences. First: the correction matters only when is not small. With , the square root of is and nobody notices. That is why national survey precision depends on and hardly on : 1000 people out of 300 million and 1000 out of one million are nearly equally precise, and 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 are independent because SRS draws in different strata are independent, and each is unbiased for with variance 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 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 . For the second, total sum of squares splits into within and between: . Then , and the terms sum to . Multiply by .
∎Except for a term of order , proportional allocation never loses, and its gain is times between-stratum variance, . 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 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 , , and the second term does not depend on . Minimize subject to . By Cauchy-Schwarz on vectors and ,
with equality if and only if is proportional to , or . This gives the allocation and minimum. Difference from proportional is , variance of when stratum is chosen with probability .
∎The rule is simple: more sample where there are more units and more variability, in proportion to . With different per-unit costs , the optimum is : spend less on expensive units. In practice the theorem ignores three details. An optimal allocation may request more units than a stratum has (): fix (a stratum census) and allocate the rest. Estimating requires . And 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 too. Three presets isolate the two sources of gain.
With the base population, and three strata of 1500, 1000, and 500 units with standard deviations 5, 12, and 45, proportional allocation is and Neyman : the smallest stratum, 17% of the population, receives 53% of the sample because it adds the most noise. Typical error falls from (SRS) to (proportional) and (Neyman): variance is times lower with proportional and 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 . Given , expectation of is the mean of the true cluster means: the sample mean of an SRS of values from a population of , with variance by the SRS theorem. Given , within-cluster subsamples are independent and each has variance ; hence , whose expectation over is because the clusters are a random sample of the .
∎The formula has two terms with very different roles. The first depends on , not : adding people to a team already sampled does not reduce it. The second decreases with but is usually the smaller. To see actual information, compare against an SRS of units. The key is correlation between two people in the same cluster.
Proof
The two identities for and follow by solving for and in the definitions of and . Substitute in the preceding theorem with : the bracket in is . For the bound, since , , and therefore .
∎With teams of people and , design effect is : surveying 2000 people is equivalent to independent ones. That 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.
The figure shows the second practical fact: at fixed , allocation matters. With and , 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 , with the cost of visiting a team and that of one more person, follows by minimizing :
When visiting a team costs ten times more than asking one extra person and , . 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 is used; Kish’s approximation with mean size 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 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 and , .
(3) If is constant, for every (including ). Then and
Terms with on the left are zero, giving the form with .
∎Formula (3) tells a clear story. Variance depends on how much ratios vary across units. If is proportional to (or something similar, such as repository size), ratios are nearly constant and variance almost disappears: the argument for PPS. If instead is unrelated to , unequal weights add variance without buying anything. Under Poisson sampling, each unit enters by an independent coin flip, , leaving .
HT has a weakness: if sample size is random, estimated total fluctuates with it even if all were equal. The remedy is the Hájek estimator, a ratio: . It has small bias, order , 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
. For the second form, and . The inequality is Cauchy-Schwarz: .
∎This is an optimistic bound: it assumes is unrelated to weights. It still shows the danger. If weights are lognormal with parameter , : with only 24% of the sample “counts.” The fourth figure compares four mean estimators when inclusion probability rises with a covariate also affecting .
The figure shows three things. At every unit has the same (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 the simple mean has bias around 12 points on a truth of 50 and deviation , 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 (sample size fluctuates) and the second’s , 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 typical weight, bias rises from to and deviation falls from to : root MSE improves from to . There is no universally correct cap; bias and variance are traded off and MSE guides selection, as in the next lesson.
When 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 ; 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
, with population covariance (divisor ). Since and , the ratio is .
∎Read carefully: error is the product of three factors. Data quality , problem difficulty , and data quantity, entering as . A million records reduces the third factor but does not touch the first. And is tiny under good design. Under SRS, is random with (compare the identity with and rearrange), that is : randomization keeps defect correlation of order , exactly what is needed for SRS error. A self-selected sample has a fixed that does not decrease with population.
The large sample’s “nominal” interval, calculated as if random, has standard error . Dividing by it, actual error is
And the SRS size with the same squared error is . With million, , and : and . One million responses are worth 161 random ones.
The readout translates into something understandable. With and Bernoulli(0.5) , corresponds to individuals with responding % more often than those with , and crossover with the 400 sample () to % 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 (in %). At the end of each year a fund closes if that year’s return is below threshold .
The mechanism is calculable. Each year of a survivor is a return conditional on exceeding , so mean annual survivor return converges to with . With and it is annually, and on average of 1000 survive after 5 years. Testing “funds have no skill” on those 233 gives a 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 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 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 , and compares four designs at the same 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.
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 ; proportional stratification reduces it to , Neyman to (allocating , more to high-tam, the variable stratum), and PPS with HT to because is almost proportional to tam. Clusters are worst, : design effect is . The final comparison is the warning: with the correct formula (team as unit), interval coverage is % (below 95% because teams are too few for a normal approximation), and with the naive one only %.
The second lab reweights a biased sample. Invite people, knowing covariate for all; they respond with increasing probability , and also rises with . 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.
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 there is no selection and all biases are zero. (2) As soon as , simple mean bias is to points with tiny deviation (root MSE is bias), while true weights remove it and deviation grows from to as Kish effective size falls from to (with estimated weights). (3) Estimated weights give smaller deviation than true ones in every case: logistic regression recalibrates the sample to the frame’s distribution, correcting random fluctuations among respondents too. Clipping at the 95th percentile reduces deviation at the cost of to points of bias: at root MSE is for simple mean, for clipped, and 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.
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 () doubles truth () while the weighted mean () is away, within its typical error of : the warning about stratifying without weights in numbers. IPW with scikit-learn propensity corrects the mean from to against truth , 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 on proportion , 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 .
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 , where is stratum error rate: . The final estimate uses weights , 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 . In m28, survivorship bias is the classic source of optimistic backtests.
Common mistakes
Exercises
More than one answer may be correct.
More than one answer may be correct.
Step 1 of 3. How do you rewrite the sample sum so you can take expectations?
Step 1 of 3. How do you reduce the problem to minimizing one sum?
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)Summary
- Variance of an SRS mean is with ; correction matters only when is not small (auditing 30% of repositories reduces error by 16%).
- Proportional stratification gains between-stratum variance; Neyman adds variance of standard deviations . Nonproportional allocation requires weighting.
- Clusters: and ; calculate standard error with cluster as unit, and .
- Horvitz–Thompson is unbiased for any design with ; Kish effective size measures the loss from extreme weights and clipping trades bias for variance.
- Selection biases: Meng’s identity is exact. A million responses with 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.