এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।
University Economics — Year 1 · স্নাতক প্রথম বর্ষ
31Sampling and Inference
The US unemployment rate is estimated each month from a survey of about 60,000 households. At a rate of around , the statistical office gives a confidence interval of about point for the change from one month to the next. A rise of point, reported as news, cannot be told apart from the noise of drawing a different sample. This chapter is about what one sample can say about a population: estimators and their errors, confidence intervals, tests, and how surveys are designed and weighted.
Both series are survey estimates. Germany’s seasonally adjusted rate stays within a standard deviation of point of its trend; Estonia’s jumps around it with a standard deviation of point, and moves by point from one quarter to the next on average, against in Germany. Part of the gap is that Estonia’s labour market moves more; part is that the survey of a small country samples far fewer people, and its estimates are noisier.
You already know
Sampling distributions, the normal and Student’s laws and the central limit theorem are Chapter 30; conditional means are Chapter 29. The unemployment survey and its definitions were met at school.
31.1 Population and sample
Definition 31.1 (Population parameter)
A population, in statistics, is the set of units about which a question is asked; a population parameter is a number that describes it, such as its mean or its unemployment rate. It is fixed and unknown. (A model’s parameters, Chapter 1, are a different use of the word.)
Definition 31.2 (Estimator, unbiased, consistent)
An estimator is a rule that turns a sample into a guess of a parameter ; the number it gives in one sample is an estimate. An estimator is unbiased when , and consistent when, for every , as the sample size grows.
31.2 Estimators: bias, variance, consistency
Proposition 31.3 (The sample mean)
For independent draws with mean and variance , the sample mean is unbiased and consistent for .
Proof. . Its variance is (Chapter 30), so by Chebyshev’s inequality . ∎
Proposition 31.4 (Dividing by )
is an unbiased estimator of .
Proof. . Taking expectations, . ∎
"""Dividing by n or by n - 1: the average of the sample variance, n = 5."""
import numpy as np
from econdata import nsw
y = nsw("psid_controls").re78.to_numpy()
rng = np.random.default_rng(2026)
samples = rng.choice(y, size=(200_000, 5))
print(f"population variance {y.var() / 1e6:7.1f} million")
for ddof in (0, 1):
v = samples.var(axis=1, ddof=ddof).mean()
print(f"average, divided by n - {ddof} {v / 1e6:7.1f} million")
$ python sample_variance.py
population variance 241.9 million
average, divided by n - 0 194.4 million
average, divided by n - 1 243.0 million
Definition 31.5 (Mean squared error)
The mean squared error of an estimator is .
"""Two estimators of mean earnings from samples of 10: bias, variance, MSE."""
import numpy as np
from econdata import nsw
y = nsw("psid_controls").re78.to_numpy()
mu = y.mean()
rng = np.random.default_rng(2026)
samples = rng.choice(y, size=(20_000, 10))
estimators = {
"sample mean": samples.mean(axis=1),
"0.8 x mean": 0.8 * samples.mean(axis=1),
}
print(f"population mean {mu:,.0f}")
for name, est in estimators.items():
bias, var = est.mean() - mu, est.var()
print(
f"{name:12s} bias {bias:7,.0f} sd {np.sqrt(var):6,.0f}"
f" root MSE {np.sqrt(bias**2 + var):6,.0f}"
)
$ python bias_variance.py
population mean 21,554
sample mean bias 18 sd 4,917 root MSE 4,917
0.8 x mean bias -4,297 sd 3,934 root MSE 5,825
Shrinking the mean towards zero trades bias for variance. Here the trade is bad — the root mean squared error rises from 4,917 to 5,825 dollars — because the mean is far from zero; for a parameter close to the point of shrinkage, it can be good. Several estimators of the later volumes make this trade on purpose.
31.3 The standard error and confidence intervals
Definition 31.6 (Standard error)
The standard error of an estimator is the standard deviation of its sampling distribution; for the sample mean it is , estimated by .
Definition 31.7 (Confidence interval)
A confidence interval at level is an interval computed from the sample that contains the parameter in a share of repeated samples. For a mean, , with close to for and large .
The level describes the procedure, not one interval: once computed, an interval contains the parameter or it does not.
"""Mean 1978 earnings of the experiment's control group, with a 95% interval."""
import numpy as np
from econdata import nsw
from scipy import stats
y = nsw("nsw_dw").query("treat == 0").re78
n, mean, s = len(y), y.mean(), y.std() # pandas divides by n - 1
se = s / np.sqrt(n)
c = stats.t.ppf(0.975, n - 1)
print(f"n {n}, mean {mean:,.0f}, s {s:,.0f}, standard error {se:,.0f}")
print(
f"95% interval: {mean - c * se:,.0f} to {mean + c * se:,.0f} (t quantile {c:.3f})"
)
$ python interval.py
n 260, mean 4,555, s 5,484, standard error 340
95% interval: 3,885 to 5,224 (t quantile 1.969)
"""100 samples of 30 men, a 95% interval from each: how many miss the truth?"""
import numpy as np
from econdata import nsw
from scipy import stats
def intervals(reps=100, n=30, seed=2026):
y = nsw("psid_controls").re78.to_numpy()
rng = np.random.default_rng(seed)
s = rng.choice(y, size=(reps, n))
half = stats.t.ppf(0.975, n - 1) * s.std(axis=1, ddof=1) / np.sqrt(n)
lo, hi = s.mean(axis=1) - half, s.mean(axis=1) + half
return lo, hi, y.mean()
if __name__ == "__main__":
lo, hi, mu = intervals()
miss = (lo > mu) | (hi < mu)
print(f"true mean {mu:,.0f}; intervals that miss it: {miss.sum()} of 100")
print(
"first misses:",
[f"{a:,.0f}-{b:,.0f}" for a, b in zip(lo[miss][:3], hi[miss][:3])],
)
$ python coverage.py
true mean 21,554; intervals that miss it: 10 of 100
first misses: ['11,767-20,207', '12,052-20,867', '22,399-34,092']
Ten misses in a hundred is more than five, but one hundred intervals are a small sample of intervals: over 20,000 of them, contain the mean.
The shortfall from is real and comes from the skewness of earnings: with 30 draws, the interval is only approximately right.
31.4 Tests
Definition 31.8 (Null hypothesis, alternative, test statistic)
A test confronts a null hypothesis (say, ) with an alternative hypothesis (say, ). A test statistic is a function of the sample whose distribution under is known, at least approximately, such as .
Definition 31.9 (Significance level, -value)
A test rejects when the statistic falls in a rejection region. The significance level, or size, is the probability of rejecting when it is true. The -value is the probability, computed under , of a statistic at least as extreme as the one observed; a test at level rejects when .
On the record — What a -value is not
In 2016 the American Statistical Association published six principles on -values (Wasserstein and Lazar 2016). Two of them: a -value does not measure the probability that the studied hypothesis is true, or the probability that the data were produced by random chance alone; and it does not measure the size of an effect or the importance of a result. A -value of says that data this far from would be rare if held — not that has a chance of being true.
Model — The randomised comparison
Assumes. People are assigned to a programme or to a control group at random, and one person’s assignment does not affect another’s outcome.
Predicts. The difference in mean outcomes estimates the programme’s average effect without bias, with the standard error of a difference of two means.
Tested. Two checks of the job-training experiment. Earnings before the programme, which assignment cannot have changed, are close in the two groups ( in 1974 and in 1975, Output 31.5), as random assignment predicts. And LaLonde (1986) used the experimental estimate as a benchmark that many non-experimental procedures failed to reproduce (record below).
Breaks. People who leave the study before the outcome is measured, in a way related to the treatment; samples so small that the interval is too wide to say anything; and effects that do not carry over to other people, places or scales, which the second university year takes up under causality and experiments.
"""The experiment's estimate: treated against controls, 1978 earnings."""
import numpy as np
from econdata import nsw
from scipy import stats
d = nsw("nsw_dw")
t1, t0 = d.re78[d.treat == 1], d.re78[d.treat == 0]
diff = t1.mean() - t0.mean()
se = np.sqrt(t1.var() / len(t1) + t0.var() / len(t0))
t = diff / se
p_normal = 2 * stats.norm.sf(abs(t))
print(f"treated {len(t1)}, mean {t1.mean():,.0f}", end="; ")
print(f"controls {len(t0)}, mean {t0.mean():,.0f}")
print(f"difference {diff:,.1f}, standard error {se:,.1f}, t {t:.3f}")
print(f"p-value (normal) {p_normal:.4f}")
r = stats.ttest_ind(t1, t0, equal_var=False)
print(f"scipy (Welch): t {r.statistic:.3f}, p-value {r.pvalue:.4f}")
print(f"95% interval: {diff - 1.96 * se:,.0f} to {diff + 1.96 * se:,.0f}")
for v in ("re74", "re75"): # a check of the random assignment: earnings before
a1, a0 = d[v][d.treat == 1], d[v][d.treat == 0]
b = stats.ttest_ind(a1, a0, equal_var=False)
print(f"{v}: treated {a1.mean():,.0f}, controls {a0.mean():,.0f}, p {b.pvalue:.2f}")
$ python nsw_effect.py
treated 185, mean 6,349; controls 260, mean 4,555
difference 1,794.3, standard error 671.0, t 2.674
p-value (normal) 0.0075
scipy (Welch): t 2.674, p-value 0.0079
95% interval: 479 to 3,109
re74: treated 2,096, controls 2,107, p 0.98
re75: treated 1,532, controls 1,267, p 0.39
The standard error of a difference of two independent means is , with and the standard deviations and and the sizes of the two groups. It lets each group keep its own variance, and the test built on it is Welch’s test. The pooled form, which assumes one common variance, would be wrong here: the treated men’s earnings in 1978 have a standard deviation of 7,867 dollars, the controls’ 5,484. The listing gives two -values for the same . The first uses the normal distribution, as the interval does with its ; Welch’s uses a Student with a degrees-of-freedom correction. With groups of 185 and 260 they agree: and .
On the record — The job-training experiment
A job-training programme in the United States assigned applicants at random to training or to a control group. The experiment gives an estimate that needs no model of who chooses to train. LaLonde (1986) replaced the experimental controls by comparison samples from two large surveys — the PSID and CPS samples of Chapter 29 — and found that many of the econometric procedures in use did not reproduce the experimental result. Dehejia and Wahba (1999) re-examined the samples with other methods.
The lesson: who is compared with whom matters more than the formula.
Definition 31.10 (Power of a test)
The power of a test against an alternative is the probability that it rejects when that alternative is true.
"""Power to detect a 1,000-dollar effect with the experiment's sample sizes."""
import numpy as np
from econdata import nsw
from scipy import stats
d = nsw("nsw_dw")
y0 = d.re78[d.treat == 0].to_numpy()
n1, n0, effect = 185, 260, 1_000
se = np.sqrt(y0.var(ddof=1) * (1 / n1 + 1 / n0)) # one sd for both groups
power = stats.norm.sf(1.96 - effect / se) + stats.norm.cdf(-1.96 - effect / se)
print(f"standard error {se:,.0f}; power by the formula {power:.3f}")
rng = np.random.default_rng(2026)
reject = 0
for _ in range(4_000): # draws from the control earnings, shifted by the effect
a, b = rng.choice(y0, n1) + effect, rng.choice(y0, n0)
reject += stats.ttest_ind(a, b, equal_var=False).pvalue < 0.05
print(f"power by simulation {reject / 4_000:.3f}")
$ python power.py
standard error 527; power by the formula 0.474
power by simulation 0.482
31.5 Many tests at once
Definition 31.11 (Family-wise error rate)
The family-wise error rate of a set of tests is the probability that at least one of them rejects a true null hypothesis. Testing each of hypotheses at level (the Bonferroni correction) keeps it at most .
The bound follows from . With 20 independent tests at and every null true, the chance of at least one rejection is .
"""Twenty placebo tests: random halves of the PSID sample compared."""
import numpy as np
from econdata import nsw
from scipy import stats
y = nsw("psid_controls").re78.to_numpy()
rng = np.random.default_rng(7)
p = []
for _ in range(20):
mask = rng.permutation(len(y)) < len(y) // 2 # a random half, no treatment at all
p.append(stats.ttest_ind(y[mask], y[~mask], equal_var=False).pvalue)
p = np.array(p)
print("smallest p-values:", np.round(np.sort(p)[:3], 4))
print(f"rejections at 5%: {(p < 0.05).sum()} of 20; expected 1")
print(f"Bonferroni threshold 0.05/20 = {0.05 / 20}; rejections: {(p < 0.0025).sum()}")
$ python many_tests.py
smallest p-values: [0.0397 0.0581 0.0795]
rejections at 5%: 1 of 20; expected 1
Bonferroni threshold 0.05/20 = 0.0025; rejections: 0
The seed, 7, was chosen to show a typical draw, with the one rejection that twenty tests at give on average; of the seeds 0 to 99, 40 give no rejection, 38 one and 22 two or more. A study that runs twenty comparisons and reports the one with has shown nothing. The third university year returns to the search for specifications and how credible work guards against it.
31.6 Survey design and weights
Definition 31.12 (Stratified sample, sampling weight, design effect)
A stratified sample divides the population into groups (strata) and draws a separate random sample in each. A unit’s sampling weight is the inverse of its probability of being drawn: the number of population units it stands for. The design effect is the variance of an estimate under the design divided by its variance under a simple random sample of the same size.
"""A stratified sample of Brenland households: owners over-sampled."""
import numpy as np
import pandas as pd
from country import load
h = load("households")
rng = np.random.default_rng(2026)
take = {1: 150, 0: 150} # 150 owners and 150 renters
parts = [h[h.owner == k].sample(m, random_state=rng) for k, m in take.items()]
sample = pd.concat(parts)
N = h.owner.value_counts() # households in each stratum
sample["weight"] = sample.owner.map(N) / sample.owner.map(take) # 1 / P(drawn)
y, w = sample.disposable, sample.weight
print(f"true mean {h.disposable.mean():,.0f}")
print(f"unweighted {y.mean():,.0f}; weighted {(w * y).sum() / w.sum():,.0f}")
print("weights:", sample.groupby("owner").weight.first().round(2).to_dict())
deff = 1 + (w.std(ddof=0) / w.mean()) ** 2 # Kish's design effect of weighting
print(f"design effect {deff:.3f}; effective sample size {len(sample) / deff:.0f}")
$ python weights.py
true mean 24,920
unweighted 26,475; weighted 24,822
weights: {0: 9.12, 1: 4.21}
design effect 1.135; effective sample size 264
Owners are a third of households but half the sample, and they have higher incomes, so the unweighted mean is too high. Unequal weights cost precision: the design effect of makes 300 households worth 264 drawn at random. (The formula of the weights is Kish’s approximation for weighting alone; stratification itself usually lowers the variance.)
How it is measured — The monthly unemployment survey
A labour-force survey asks a sample of households about each member’s work and job search in a reference week, and classifies each person as employed, unemployed or out of the labour force. The rate is the weighted number of unemployed divided by the weighted labour force. A interval spans about standard errors on each side; for the US monthly change, it is about point at a rate around . Households stay in the sample for several months, so successive samples overlap, which makes the standard error of a change smaller than that of two independent samples.
"""A monthly survey of 100,000 people in the labour force, true rate 6.0%."""
import numpy as np
rng = np.random.default_rng(2026)
n, rate = 100_000, 0.060
months = rng.binomial(n, rate, size=2) / n # two independent monthly samples
se = np.sqrt(rate * (1 - rate) / n)
print(
f"estimates {100 * months[0]:.2f}% and {100 * months[1]:.2f}%; standard error"
f" {100 * se:.3f} points"
)
change = months[1] - months[0]
se_change = np.sqrt(2) * se # independent samples; overlapping samples do better
print(
f"change {100 * change:+.2f} points; its standard error {100 * se_change:.3f};"
f" 90% margin {100 * 1.645 * se_change:.2f}"
)
$ python unemployment_survey.py
estimates 5.94% and 6.04%; standard error 0.075 points
change +0.10 points; its standard error 0.106; 90% margin 0.17
Exercises
Exercise 31.1 ★
A sample of 400 has a standard deviation of 9,000. Find the standard error of its mean.
Solution
Solution of Exercise 31.1.
.
Exercise 31.2 ★
From Output 31.5, give the estimated effect, its standard error and the -value of Welch’s test.
Solution
Solution of Exercise 31.2.
1,794.3 dollars, with a standard error of 671.0; Welch’s test gives .
Exercise 31.3 ★
A test gives . Which statement is right? (a) has a chance of being true. (b) The effect is large. (c) If were true, a statistic at least this extreme would occur in of samples. (d) The result has a chance of being replicated.
Solution
Solution of Exercise 31.3.
(c). A -value is computed assuming , so it is not the probability of (a); it does not measure the size of the effect (b); and it is not a probability of replication (d).
Exercise 31.4 ★
Predict the width of a interval when the sample size is multiplied by 4.
Exercise 31.5 ★★
Find the bias of as an estimator of . Is it consistent?
Solution
Solution of Exercise 31.5.
, a bias of . It is consistent: , the factor tends to 1 and is consistent.
Exercise 31.6 ★★
In two random samples of 400, 120 and 90 people say they are looking for another job. Test at whether the two population shares differ.
Solution
Solution of Exercise 31.6.
, , pooled . The standard error under is , so and : the shares differ at .
Exercise 31.7 ★★
With the standard deviations of the experiment’s two groups (7,867 and 5,484 dollars), how many people per group give a power of to detect an effect of 1,000 dollars at , two-sided?
Solution
Solution of Exercise 31.7.
Power at two-sided needs a standard error of dollars. With people per group, gives : 1,444 people in all, more than three times the experiment’s 445.
Exercise 31.8 ★★
Fifty true null hypotheses are tested at . How many rejections do you expect? What is the Bonferroni threshold?
Solution
Solution of Exercise 31.8.
rejections on average; the Bonferroni threshold is .
Exercise 31.9 ★★
A survey over-samples young households, whose income is lower than average. Predict which of the weighted and unweighted mean incomes is closer to the population’s, and why.
Solution
Solution of Exercise 31.9.
The weighted mean: young households are over-represented in the sample, so the unweighted mean is pulled down; the weights give each household the share of the population it stands for.
Exercise 31.10 ★★★
Write out the proof of Proposition 31.4, justifying the decomposition of and each expectation.
Solution
Solution of Exercise 31.10.
Write . Squaring and summing, the cross term is , so . Each , and by independence. The expectation is ; dividing by gives .
Exercise 31.11 ★★★
Show that an estimator can be biased and consistent, with an example from this chapter.
Solution
Solution of Exercise 31.11.
The variance divided by , , has expectation : biased, as Output 31.1 shows for . Its bias tends to zero and its variance too (when the fourth moment is finite), so it is consistent. The estimator of Exercise 31.5 is another example.
Exercise 31.12 ★★★
What pattern among published -values would show that many tests were run and only the significant ones reported?
Solution
Solution of Exercise 31.12.
Too many -values just below and too few just above it, compared with the smooth distribution that honest reporting of all tests would give; and too few studies with insignificant results.
31.7 Problem: The Brenland Labour-Force Survey
Problem 31.1
Weekend problem — how big must the survey be?
Brenland (invented) has three regions: the Capital (2.0 million in the labour force, true unemployment rate ), the North (1.5 million, ) and the South (1.0 million, ). Each month the statistical office samples 4,000 people in the labour force of each region, independently from month to month. In month 2 every regional rate rises by point. A script simulates the two months; its seed, 2028, was chosen to show a typical draw, one whose measured change is within half a standard error of the true one.
Part I — Design.
- Give each region’s share of the labour force and the true national rate.
- Give each region’s probability of selection.
- Give the sampling weights.
- Why sample the same number in each region?
- Which way would an unweighted rate be biased?
- Give the design effect of the weights by Kish’s formula.
Part II — The estimate.
- Give the unemployed counted in each region’s sample in month 1.
- Give the regional rates and their standard errors.
- Give the unweighted national rate.
- Give the weighted national rate.
- Give its standard error, , with the regions’ shares.
- Compare with the standard error of a simple random sample of 12,000.
- Give a interval.
Part III — The change.
- Give the weighted rate in month 2.
- Give the change.
- Give the standard error of the change.
- Give the statistic and the -value.
- Does the survey detect the rise at ?
- Is the drawn change far from the true one?
- How would keeping the same people in the sample from one month to the next change the standard error of the change?
Part IV — The sample size.
- What standard error of the change gives a power of to detect a -point rise at , two-sided?
- Give the standard error of the change with 12,000 people, from the true rates.
- How many people a month, with the same design, give the power of item 21?
- And with a simple random sample?
- How many with overlapping samples whose estimates have a correlation of between months?
- State the result.
Solution
Solution of Problem 31.1.
1. Shares , , ; true rate .
2. ; ; .
3. 500, 375 and 250 people each.
4. To estimate each region’s rate with the same precision, the small regions included.
5. Upwards: the South, with the highest rate, is over-represented.
6. .
7. 201, 272 and 298.
8. , and , with standard errors , and point.
9. .
10. .
11. point.
12. point: the design is slightly less precise for the national rate, as the design effect predicts.
13. to .
14. .
15. point.
16. point.
17. , .
18. No.
19. No: point from the true , a third of a standard error.
20. With a correlation between the two months’ estimates, the variance of the change is multiplied by : overlap makes changes more precise.
21. point.
22. point.
23. people a month.
24. .
25. Half as many: about 115,000.
26. To detect a -point monthly change with power, Brenland’s survey needs about 229,000 people a month, not 12,000 — about 115,000 if the samples overlap enough for a correlation of .