Chapter 8
Estimation
Lectures 19–22 · from data to numbers we can trust: estimators, bias and variance, the method of moments, maximum likelihood and confidence intervals
In the Second World War, the Allies badly wanted to know how many tanks Germany was building each month. Intelligence reports, based on spies, aerial photographs and interrogations, put the figure at well over a thousand. Statisticians tried something different. Captured German tanks carried serial numbers on their gearboxes and other parts, and the numbers ran in sequence. If you capture a handful of tanks at random and the largest serial number you see is 61, the enemy probably hasn't built thousands. After the war, German production records were compared with both sets of figures. The intelligence estimates had been wildly too high. The statistical estimates were remarkably close.
That is estimation: using data to put a number on something we can't see directly. Chapters 3 to 7 assumed that we knew the model's parameters: the rate , the probability , the mean . In practice we almost never do. This chapter turns the direction round. Given data, what values of the parameters are reasonable, and how sure can we be?
Estimation is the heart of inference. A point estimate is our best single guess at an unseen quantity: the true detection rate of a test, the true average speed of light, the true effect of a drug. A confidence interval adds an honest statement of how far off that guess might be. Estimation also serves prediction, because every prediction from a model uses estimated parameters, and the uncertainty in those estimates carries into the prediction. Section 8.4 shows the difference between an interval for a mean and an interval for a new observation, which is much wider.
Here is the route through the chapter.
- Section 8.1 describes what makes an estimator good: bias, standard error and mean squared error.
- Sections 8.2 and 8.3 give two general methods for building estimators: the method of moments and maximum likelihood.
- Section 8.4 builds confidence intervals for a mean, and Section 8.5 for a proportion.
- Section 8.6 explains what "95% confidence" means, and what it doesn't.
Think About It: Before You Start
Five captured tanks carry the serial numbers 19, 56, 24, 16 and 61. Tanks are numbered . Write down your best guess for , and the rule you used to get it. Is your rule more likely to guess too high or too low?
Many people say 61, the largest number seen. But the largest serial number in a sample can never be bigger than , and is usually smaller, so this rule always guesses too low (or exactly right). Others double the average: the average of 1 to is about , and the sample average is 35.2, giving about 70 (or 69.4 after a small correction, ). A third rule adds to the largest serial number the typical gap between the numbers seen: 61 plus the average gap,
Lecture 19 — Estimators and the method of moments
8.1 Estimators and their errors
Parameters, estimators and estimates
A parameter is a number that describes the population or the model: , , , , . We use the Greek letter (theta) for a generic parameter.
Definition: Estimator and Estimate
An estimator of a parameter is a statistic, a rule
An estimator is a random variable: it has a sampling distribution (Chapter 7). That's what lets us say how good it is. A single estimate can't be judged on its own, since we don't know ; but a rule can be judged by how it behaves over many possible samples.
Definition: Bias, Standard Error and Mean Squared Error
For an estimator of :
- its bias is
; the estimator is unbiased if the bias is 0; - its standard error is ;
- its mean squared error is
, and its square root, the root mean squared error (RMSE), is the typical size of its error.
The picture to keep in mind is a dartboard with the true at the bullseye and each estimate a dart. Bias is aiming at the wrong place; standard error is a shaky hand. Chapter 1's bathroom scale that always reads 2 kg light (Section 1.3) has large bias and no variance at all: precisely wrong.
Throw some darts yourself, and watch how the two sources of error add up:
Theorem: MSE = Variance + Bias²
Write and add and subtract it:
So the total error has two sources, and a little bias can be worth accepting if it buys a large cut in variance. This bias–variance trade-off runs through all of statistics and machine learning.
Example 8.1: How Many Tanks? ★ lecture example
Tanks are numbered , and we capture at random (without replacement). Let be the largest serial number among them. Compare three estimators of by simulation, with and :
- (twice the sample mean, minus 1);
- (the largest serial number);
(the largest, plus the average gap between serial numbers).
Then apply all three to the five tanks in "before you start".
Why these rules? The serial numbers are equally likely to be any of , whose mean is ; setting gives . The largest number seen, , can't exceed . And the numbers seen split the range to into gaps averaging about , so we expect a gap of about that size above as well, which gives .
Simulate 20,000 sets of 5 captured tanks:
set.seed(8)
N <- 300; k <- 5
sims <- replicate(20000, { s <- sample(1:N, k)
c(twice_mean = 2 * mean(s) - 1, largest = max(s), largest_plus_gap = max(s) * (1 + 1/k) - 1) })
round(rbind(average = rowMeans(sims), SE = apply(sims, 1, sd),
RMSE = sqrt(rowMeans((sims - N)^2))), 1)
twice_mean largest largest_plus_gap
average 300.4 251.3 300.5
SE 76.7 41.7 50.1
RMSE 76.7 64.1 50.1
d <- data.frame(estimate = as.vector(t(sims)),
rule = rep(c("twice the mean", "largest", "largest + gap"), each = 20000))
d$rule <- factor(d$rule, levels = c("twice the mean", "largest", "largest + gap"))
ggplot(d, aes(estimate)) + geom_histogram(binwidth = 15, boundary = 0, colour = "white") +
geom_vline(xintercept = N, linetype = "dashed") + facet_wrap(~ rule) +
scale_x_continuous(breaks = c(150, 300, 450)) +
labs(x = "estimate of N (true N = 300)", y = "count")
| rule | average | SE | RMSE |
|---|---|---|---|
| twice the mean | 300.4 | 76.7 | 76.7 |
| largest | 251.3 | 41.7 | 64.1 |
| largest + gap | 300.5 | 50.1 | 50.1 |
- Twice the mean is unbiased but very variable: one unusually large or small serial number moves it a lot.
- The largest is much less variable, but biased: on average it's 49 tanks too low, and it can never be too high.
- Largest plus gap is unbiased and less variable than twice the mean, so it has the smallest typical error. It is the best unbiased estimator possible here: no unbiased estimator has a smaller standard error (a fact we won't prove).
The five captured tanks (19, 56, 24, 16, 61) give
History: Counting Tanks from Serial Numbers
Allied economists in the Second World War read the serial numbers on captured German tanks, including those stamped on gearboxes and on the moulds of road wheels, and estimated monthly production. After the war, the figures were compared with German records. In one widely quoted comparison from Richard Ruggles and Henry Brodie's 1947 account, for June 1940 the statistical estimate was 169 tanks a month, intelligence estimates said about 1,000, and German records showed 122; for August 1942 the figures were 327, about 1,550, and 342. Similar methods were later used to estimate the production of other equipment, and the idea is still used, for example to estimate how many units of a product a company has sold from the serial numbers of a few.
Source: R. Ruggles and H. Brodie (1947), "An empirical approach to economic intelligence in World War II", Journal of the American Statistical Association 42, 72–91.
Why the sample variance divides by n − 1
Chapter 2 promised to explain why the sample variance divides by rather than . Here is the answer.
Theorem: The Sample Variance Is Unbiased
If is a random sample with variance , then
Expand the square:
The deviations are measured from , which sits closer to the data than the true does, so they're slightly too small on average; dividing by instead of compensates exactly.
Example 8.2: Is Unbiased Always Better?
For samples of size 5 from (so ), compare by simulation the unbiased with , which divides by .
set.seed(8)
v <- replicate(20000, { x <- rnorm(5); c(divide_by_4 = var(x), divide_by_5 = var(x) * 4 / 5) })
rbind(average = rowMeans(v), MSE = rowMeans((v - 1)^2))
divide_by_4 divide_by_5
average 1.0024569 0.8019656
MSE 0.5003244 0.3594214
averages 1.00 (unbiased), and averages 0.80 (biased low by 20%). But the MSEs are 0.50 and 0.36: the biased estimator has the smaller typical error, because shrinking every estimate by cuts the variance more than it adds in squared bias. "Unbiased" is a good property, not the only one. We still use by convention, and because the intervals of Section 8.4 are built on it.
One more property is worth naming. An estimator is consistent if it gets arbitrarily close to with probability approaching 1 as . The Law of Large Numbers (Section 7.3) says that is consistent for . Consistency is the least we should ask: with enough data, the estimator should find the truth.
Check Yourself
An estimator has bias 2 and standard error 3. What is its mean squared error?
, so its typical error is .
Compute both MSEs.
Compute both MSEs.
and
Think About It: A Biased Scale
A lab's scale reads, on average, 0.3 mg too heavy, with a measurement SD of 0.1 mg. A second scale is correctly calibrated but has SD 0.5 mg. A forensic chemist must weigh a seized sample once. Which scale would you use, and why? What would you do if you could weigh it 100 times?
For one weighing, the first scale's RMSE is
Key Takeaways
- An estimator is a rule; its bias, standard error and MSE describe how it behaves over repeated samples.
: total error has two sources, and they can be traded off. - (dividing by ) is unbiased for . Unbiased isn't always best.
- More data reduces variance, not bias.
8.2 The method of moments
The oldest general recipe for estimators is to make the model match the data's averages. Karl Pearson developed it in the 1890s.
Definition: Method of Moments
The th population moment is and the th sample moment is . For a model with unknown parameters, the method of moments sets the first population moments (which depend on the parameters) equal to the first sample moments, and solves for the parameters.
Equivalently, for two parameters, match the mean and the variance, using the variance with divisor .
Example 8.3: Suspicious Logins ★ lecture example
A security analyst models the time between suspicious login attempts as , and records five gaps, in minutes: 10.2, 12.6, 7.5, 8.3, 10.5. Estimate by the method of moments.
One parameter, so match the first moment. The population mean of is (Section 5.4), and the sample mean is minutes. Setting gives
Critical thinking. Is an exponential model plausible? For the exponential, the SD equals the mean. These five gaps have SD only 2.0 minutes, a fifth of their mean, so they're far more regular than exponential gaps would be. That suggests automated attempts at a near-steady rate, not random human ones. Estimating a parameter doesn't check the model; Chapter 9 gives tools that do.
Example 8.4: A Model for Rainfall ★ lecture example
R's precip gives the average annual rainfall, in inches, of 70 US cities. Rainfall is positive and right-skewed, so fit a gamma model, , by the method of moments. Does it fit?
Two parameters, two moments. A has mean and variance (Section 5.4). Matching them to the sample mean and the divide-by- variance : Dividing the first equation by the second gives , and then .
m <- mean(precip); v <- mean((precip - m)^2)
c(n = length(precip), mean = m, sd = sqrt(v))
c(alpha = m^2 / v, lambda = m / v)
n mean sd
70.00000 34.88571 13.60839
alpha lambda
6.5717576 0.1883796
With inches and inches, the estimates are and per inch.
ggplot(data.frame(precip), aes(precip)) +
geom_histogram(aes(y = after_stat(density)), binwidth = 5, boundary = 0, colour = "white") +
stat_function(fun = dgamma, args = list(shape = m^2 / v, rate = m / v), linewidth = 1) +
labs(x = "average annual rainfall (inches)", y = "density")
The fit is fair but not great. The data have a sharper peak around 35 to 45 inches and a handful of very dry desert cities in the left tail, which the smooth gamma curve can't capture: the cities come from two different climates. As in Chapter 5, a model that matches the mean and variance can still miss the shape.
The method of moments is quick and needs no calculus, but it doesn't always give sensible answers (in Example 8.1 it can even produce an estimate smaller than the largest serial number seen, which is impossible), and it usually isn't the most precise method. The next section's method usually is.
Check Yourself
A server receives 4, 3, 2, 5, 4, 6, 3, 2, 5, 3, 4, 3 packets in 12 consecutive one-second intervals. Fit a Poisson model by the method of moments.
A Poisson's mean is .
Key Takeaways
- Method of moments: match the first few population moments to the sample moments and solve.
- Easy and general, but not always sensible or efficient; check the fitted model against the data.
Lecture 20 — Maximum likelihood
8.3 Maximum likelihood
The likelihood
Here is a more principled idea. Different parameter values make the observed data more or less probable. Choose the value that makes the data we actually saw most probable.
Definition: Likelihood and Maximum Likelihood Estimator
Let be observed data from a model with PMF or density . The likelihood function is the probability (or density) of the observed data, viewed as a function of : for an IID sample. The maximum likelihood estimate (MLE) is the value of that maximizes . It is usually easier to maximize the log-likelihood
The likelihood is not a probability distribution for (it needn't integrate to 1 over ). It's a measure of how well each parameter value explains the data. The recipe is the calculus of Section 0.4: differentiate , set the derivative to zero, solve, and check that it's a maximum.
Example 8.5: Who Uses Two-Factor Authentication? ★ lecture example
In a random sample of 10 people, 3 use two-factor authentication (2FA) on their email: the 1st, 3rd and 10th. Model each person as . Find the MLE of .
Likelihood. Each user contributes a factor and each non-user :
Log-likelihood and its derivative:
Solve : , so . The second derivative,
p <- seq(0.02, 0.9, by = 0.005)
ggplot(data.frame(p, ll = 3 * log(p) + 7 * log(1 - p)), aes(p, ll)) +
geom_line(linewidth = 1) + geom_vline(xintercept = 0.3, linetype = "dashed") +
labs(x = "p", y = "log-likelihood")
In general, successes in Bernoulli trials give : the sample proportion, as in Section 0.4's preview. Only the number of successes matters, not which people they were; the same answer comes from the binomial likelihood , since the constant doesn't move the peak.
Example 8.6: Time to a Toxic Effect ★ lecture example
Researchers record the time, in minutes, until a compound produces a toxic effect in five test subjects: 36.2, 42.8, 47.2, 50.2, 51.7. Assuming an exponential model, find the MLE of .
Likelihood. Each time contributes :
Log-likelihood:
Critical thinking. As in Example 8.3, these times are much more regular (SD 6.3 minutes) than an exponential model allows (SD equal to the mean, about 46 minutes). A toxic effect that requires a dose to build up is better described by a gamma or Weibull model, which can have a rising risk over time (Sections 5.4 and 5.6).
Example 8.7: Weekly Burglaries
A precinct records 3, 3, 5 and 8 burglaries in four weeks. Assuming the weekly counts are IID , find the MLE of .
so
Example 8.8: The Tanks, by Maximum Likelihood ★ lecture example
Find the MLE of in the tank problem of Example 8.1, from distinct serial numbers with largest value .
Every set of distinct serial numbers from is equally likely, with probability , provided all the numbers are at most . So For , increases with , so decreases. The likelihood is largest at the smallest possible value, , the largest serial number seen. Calculus doesn't help here, since the maximum is at the edge of the allowed range.
So the MLE is the estimator of Example 8.1, which is biased: it's never too high, and it's too low on average. Maximum likelihood is a superb general method, but its estimates are not always unbiased, especially in small samples. Here the fix (
The likelihood for the five captured tanks (largest serial number 61) is zero below 61 and falls steadily above it, so its peak is at the edge:
N <- 40:150
lik <- ifelse(N >= 61, 1 / choose(N, 5), 0)
ggplot(data.frame(N, lik = lik / max(lik)), aes(N, lik)) +
geom_step(linewidth = 1) + geom_vline(xintercept = 61, linetype = "dashed") +
labs(x = "number of tanks N", y = "likelihood (scaled)")
Properties of maximum likelihood
Why is maximum likelihood the standard method? Because for large samples, under mild conditions on the model, MLEs have three excellent properties.
Theorem: Large-Sample Properties of the MLE
For an IID sample from a model satisfying mild smoothness conditions, as :
Consistent: converges to the true .
Approximately Gaussian: , with the standard error estimated by the curvature of the log-likelihood at its peak:
Efficient: in the large-sample limit its variance reaches the Cramér–Rao lower bound (Section 8.7), so no well-behaved estimator does better.
Also, MLEs are invariant: the MLE of any function is .
The curvature formula makes intuitive sense: a sharply peaked log-likelihood (large ) means the data rule out all but a narrow range of , so the estimate is precise. For the 2FA data,
Example 8.9: Gaussian Maximum Likelihood
For an IID sample from with both parameters unknown, find the MLEs.
The log-likelihood is
Then over . Writing and
Check Yourself
In 20 biometric database queries, 7 produce a match. Find the MLE of the match probability .
For Bernoulli trials, .
.
A flat peak still has a highest point. What does flatness say about other values?
Flatness is about precision, not fit. Could a well-fitting model still have a flat likelihood with little data?
Think About It: The Likelihood of What, Exactly?
A defence lawyer says: "The likelihood of the evidence under my client's innocence is 0.01, so the probability that my client is innocent is only 1%." What's wrong with this argument? How is it related to the likelihood in this section?
It confuses with : the prosecutor's fallacy of Section 3.6, here used by the defence. A likelihood measures how well a hypothesis explains the data. To turn it into a probability of the hypothesis, Bayes' theorem needs the prior probability and the likelihood under the alternatives as well. In this section the likelihood compares parameter values by how well they explain the data, and the MLE picks the best explainer, without claiming that it has any particular probability of being true. Bayesian statistics (Section 8.6's box) is what adds the prior and turns likelihoods into probabilities about parameters.
Key Takeaways
- The likelihood is the probability of the observed data as a function of ; the MLE maximizes it (usually via the log-likelihood and calculus).
- Common MLEs: , (Poisson), (exponential), and
(Gaussian). - For large samples MLEs are consistent, approximately Gaussian and efficient, with
. In small samples they can be biased.
Lecture 21 — Confidence intervals for a mean
8.4 Confidence intervals for a mean
The idea
A point estimate is almost never exactly right. A confidence interval gives a range of plausible values, built so that the method captures the true value a known fraction of the time. Here's the recipe, using the Gaussian sampling distribution of Chapter 7.
If
Definition: Confidence Interval
A confidence interval for is an interval computed from the sample by a rule that, over repeated samples, contains the true with probability , called the confidence level or coverage probability. Many intervals have the form
The critical value is the point with area above it under the standard Gaussian: qnorm(1 - alpha/2). For 90%, 95% and 99% confidence it is 1.645, 1.960 and 2.576.
Case 1: Gaussian population, σ known
Theorem: Z Interval for a Mean
If is a random sample from with known, then is an exact confidence interval for .
Example 8.10: A Well-Calibrated Instrument
An instrument measures the concentration of a heavy metal in water with Gaussian error of known SD mg/L, from long calibration studies. Forty measurements of one sample average mg/L. (a) Find 90%, 95% and 99% confidence intervals for the true concentration . (b) How many measurements would give a 95% interval of total width 0.02 mg/L?
(a) The standard error is
| confidence | zα/₂ | margin of error | interval |
|---|---|---|---|
| 90% | 1.645 | 0.026 | (5.400, 5.452) |
| 95% | 1.960 | 0.031 | (5.395, 5.457) |
| 99% | 2.576 | 0.041 | (5.385, 5.467) |
se <- 0.1 / sqrt(40)
sapply(c(0.90, 0.95, 0.99), function(cl) 5.426 + c(-1, 1) * qnorm(1 - (1 - cl) / 2) * se)
[,1] [,2] [,3]
[1,] 5.399993 5.39501 5.385273
[2,] 5.452007 5.45699 5.466727
More confidence requires a wider interval: to be more sure of catching , you cast a wider net.
(b) Sample size. The width is
Case 2: Gaussian population, σ unknown: the t interval
Knowing but not is rare. Usually we must estimate by the sample SD , and that adds uncertainty: in a small sample, may happen to be too small, making the interval too narrow. William Gosset ("Student", Section 5.6) found the exact correction in 1908; Fisher later gave the rigorous proof.
Theorem: Student's T
If is a random sample from , then has a distribution with degrees of freedom. Hence is an exact confidence interval for , where is qt(1 - alpha/2, n - 1).
The critical values are larger than the Gaussian ones, especially for small (with 9 degrees of freedom, instead of 1.96), and they approach the Gaussian values as grows (with 100 degrees of freedom, 1.98).
x <- seq(-4, 4, by = 0.02)
d <- rbind(data.frame(x, f = dnorm(x), dist = "Gaussian"),
data.frame(x, f = dt(x, 9), dist = "t, 9 df"),
data.frame(x, f = dt(x, 2), dist = "t, 2 df"))
d$dist <- factor(d$dist, levels = c("Gaussian", "t, 9 df", "t, 2 df"))
ggplot(d, aes(x, f, linetype = dist)) + geom_line(linewidth = 0.9) +
scale_linetype_manual(values = c("solid", "dashed", "dotted")) +
labs(x = NULL, y = "density", linetype = NULL)
Example 8.11: Student's Own Data ★ lecture example
In his 1908 paper, Student illustrated the distribution with data from a 1905 drug trial by Arthur Cushny and Alvin Peebles: 10 patients each took two sleeping drugs, and the extra hours of sleep were recorded. R's sleep data contain them. For each patient, take the difference between the two drugs. (a) Find a 95% confidence interval for the mean difference. (b) Find a 95% prediction interval for the difference in a new patient. Explain the difference between the two intervals.
(a) Paired differences. Each patient took both drugs, so we analyse one difference per patient, a single sample of 10:
d <- with(sleep, extra[group == 2] - extra[group == 1])
d
c(mean = mean(d), sd = sd(d), t_crit = qt(0.975, df = 9))
mean(d) + c(-1, 1) * qt(0.975, 9) * sd(d) / sqrt(10)
t.test(d)$conf.int # the same, built in
[1] 1.2 2.4 1.3 1.3 0.0 1.0 1.8 0.8 4.6 1.4
mean sd t_crit
1.580000 1.229995 2.262157
[1] 0.7001142 2.4598858
[1] 0.7001142 2.4598858
attr(,"conf.level")
[1] 0.95
The differences have mean hours and SD . With :
(b) A prediction interval for one new patient's difference must allow for two sources of uncertainty: how far is from , and how far one patient varies around . Since has variance , and assuming the individual differences are roughly Gaussian (a prediction for one patient can't lean on the CLT),
mean(d) + c(-1, 1) * qt(0.975, 9) * sd(d) * sqrt(1 + 1/10)
[1] -1.338251 4.498251
The two goals. The confidence interval is about inference: where is the average effect? It shrinks to nothing as grows. The prediction interval is about prediction: what will happen to the next patient? It can never be narrower than the spread of individual patients, however much data we collect. A drug can help on average and still do nothing, or harm, for a particular person.
ci <- mean(d) + c(-1, 1) * qt(0.975, 9) * sd(d) / sqrt(10)
pi <- mean(d) + c(-1, 1) * qt(0.975, 9) * sd(d) * sqrt(1 + 1/10)
ggplot() +
geom_point(aes(x = d, y = 3), size = 3, alpha = 0.7) +
geom_segment(aes(x = ci[1], xend = ci[2], y = 2, yend = 2), linewidth = 2, colour = "steelblue") +
geom_segment(aes(x = pi[1], xend = pi[2], y = 1, yend = 1), linewidth = 2, colour = "orange") +
geom_vline(xintercept = 0, linetype = "dashed") +
scale_y_continuous(breaks = 1:3, labels = c("prediction interval", "confidence interval", "data"),
limits = c(0.5, 3.5)) +
labs(x = "extra sleep (hours): drug 2 minus drug 1", y = NULL)
Case 3: any population, large n
If the population isn't Gaussian but is large, the Central Limit Theorem makes approximately Gaussian, and is close to . Then is an approximate confidence interval for . In practice most software uses the critical value anyway (it makes almost no difference for large , and it's exact when the population is Gaussian), which is what R's t.test does. How large "large" must be depends on the population's skewness (Section 7.4).
Example 8.12: Michelson and the Speed of Light ★ lecture example
In 1879, Albert Michelson made 100 measurements of the speed of light (R's morley, Section 2.3), recorded in km/s minus 299,000. (a) Find a 95% confidence interval for the mean of his measurements. (b) Michelson measured in air, where light travels at about 299,734.5 km/s (Section 2.3; in a vacuum it is exactly 299,792.458 km/s). Does the interval contain the true value? What went wrong?
(a) With , and :
t.test(morley$Speed)$conf.int
[1] 836.7226 868.0774
attr(,"conf.level")
[1] 0.95
(b) No. The true value, 734.5 on this scale, is about 102 km/s below the bottom of the interval, and
What went wrong is systematic error: something in the apparatus, its calibration or the corrections applied to the readings pushed every measurement upwards; historians of science have debated the exact cause. A confidence interval accounts only for random error, the scatter of measurements around their own average. It assumes that the average of the measurements is centred on the truth. If the instrument is biased, the interval is centred in the wrong place, and more measurements just give a narrower interval around the wrong value. Michelson's later measurements, with improved methods, came much closer. Every interval in this chapter carries the same unspoken assumption: no bias.
Check Yourself
Find the critical value for a 95% interval with a sample of 10. Use R: qt(0.975, 9).
Degrees of freedom are .
, compared with 1.960 for the Gaussian.
To be more confident of catching , do you need a wider or narrower net?
The margin of error is proportional to .
The margin is ; larger shrinks it. Higher confidence and larger both widen it.
Think About It: A Precise Wrong Answer
A breath-alcohol device is calibrated once a year. Between calibrations it drifts, reading on average up to 0.005 g/dL too high. A driver's three readings give a 95% confidence interval for their true level of (0.081, 0.085). Should the driver be convicted of being over 0.08? What would you want to know first?
The interval is built on the assumption that readings scatter around the true level. If the device reads up to 0.005 too high, the true level could be anywhere from about 0.076 to 0.085, which includes values under the limit. The interval's narrowness reflects the consistency of the three readings, not their accuracy. You'd want the device's calibration record, the date of its last calibration, and ideally a blood test analysed by a different method. Many jurisdictions require exactly these safeguards. Like Michelson's interval, a confidence interval is only as good as the assumption of no bias.
Key Takeaways
- A confidence interval is estimate ± critical value × standard error, built so that the method covers the truth of the time.
- Gaussian population, σ known: . σ unknown:
. Large , any population: approximately the same. - A prediction interval for one new observation,
, is much wider and never shrinks to zero. It needs the individual observations to be roughly Gaussian; the CLT doesn't rescue it. - Intervals capture random error only; they don't detect bias.
Lecture 22 — Intervals for proportions and what confidence means
8.5 Confidence intervals for a proportion
For a proportion, Section 7.5 gave
Theorem: Wald and Wilson Intervals for a Proportion
With successes in trials and :
The Wald (or traditional) interval replaces by in the standard error:
The Wilson (or score) interval keeps in the standard error and solves
for . Writing , the solution is
For Wilson's interval, square both sides of
The Wilson interval's centre is pulled from slightly towards , and it never extends below 0 or above 1. For large and not near 0 or 1, the two intervals nearly coincide. For small or extreme , Wilson's is much better: the Wald interval's actual coverage can fall well below its nominal 95%. In R, prop.test(x, n, correct = FALSE)$conf.int gives the Wilson interval.
Example 8.13: Pesticide Residues ★ lecture example
A lab tests a random sample of 150 agricultural products from a shipment, and 42 exceed the legal limit for pesticide residues. (a) Find the 95% Wald and Wilson intervals for the proportion over the limit in the whole shipment. (b) Compare them.
(a)
x <- 42; n <- 150; p_hat <- x / n
p_hat + c(-1, 1) * qnorm(0.975) * sqrt(p_hat * (1 - p_hat) / n) # Wald
prop.test(x, n, correct = FALSE)$conf.int # Wilson
[1] 0.2081465 0.3518535
[1] 0.2143304 0.3566565
attr(,"conf.level")
[1] 0.95
(b) With and , the intervals differ by only about 0.005 to 0.006 at each end; Wilson's is shifted slightly towards 0.5. Either way, between about a fifth and a third of the shipment is over the limit, which is far too many to release it.
Example 8.14: Zero Out of Twenty ★ lecture example
A new drug is given to 20 patients, and none has a serious side effect. (a) What does the Wald interval give? (b) What does the Wilson interval give? (c) The "rule of three" says that, after 0 events in trials, an approximate 95% upper bound for is . Where does it come from?
(a) , so the Wald standard error is 0, and the interval is , which claims certainty that the side effect never happens. That's absurd: 20 patients can't rule out a 1-in-50 risk.
(b) prop.test(0, 20, correct = FALSE)$conf.int gives : the risk could be as high as about 16%.
(c) If the true risk is , the chance of 0 events in patients is . The largest that still gives this outcome at least a 5% chance solves
prop.test(0, 20, correct = FALSE)$conf.int
1 - 0.05^(1/20) # exact one-sided 95% upper bound
3 / 20 # rule of three
[1] 0.0000000 0.1611252
attr(,"conf.level")
[1] 0.95
[1] 0.1391083
[1] 0.15
This is why drug regulators require large trials and post-marketing surveillance: to detect a side effect that occurs in 1 patient in 1,000, you need to watch thousands of patients.
How badly can the Wald interval fail? A simulation for and shows the Wald "95%" interval covering the truth only about 87% of the time, while Wilson's covers it about 96% of the time. For and , both cover about 95%. Try it in the widget below.
The coverage of each method can be computed exactly, for every possible true , by adding the binomial probabilities of all the outcomes whose interval contains :
cover <- function(p, n = 20, z = 1.96) {
x <- 0:n; ph <- x / n
wald <- abs(ph - p) <= z * sqrt(ph * (1 - ph) / n)
ctr <- (ph + z^2 / (2 * n)) / (1 + z^2 / n)
hw <- z / (1 + z^2 / n) * sqrt(ph * (1 - ph) / n + z^2 / (4 * n^2))
wil <- abs(ctr - p) <= hw
c(Wald = sum(dbinom(x, n, p)[wald]), Wilson = sum(dbinom(x, n, p)[wil])) }
p <- seq(0.01, 0.99, by = 0.002)
cv <- t(sapply(p, cover))
d <- rbind(data.frame(p, coverage = cv[, "Wald"], method = "Wald"),
data.frame(p, coverage = cv[, "Wilson"], method = "Wilson"))
ggplot(d, aes(p, coverage, colour = method)) + geom_line() +
geom_hline(yintercept = 0.95, linetype = "dashed") + coord_cartesian(ylim = c(0.5, 1)) +
scale_colour_manual(values = c(Wald = "steelblue", Wilson = "orange")) +
labs(x = "true proportion p (n = 20)", y = "actual coverage", colour = NULL)
Check Yourself
How many people must a poll survey for a 95% Wald margin of error of at most 3 percentage points, in the worst case ? (Round up.)
Solve
Think About It: Whose Rate Is It?
A hospital reports that 0 of its last 25 hip replacements became infected, and advertises "a 0% infection rate". A competitor reports 3 infections in 400 operations (0.75%). Which hospital has better evidence of a low infection rate? What would you want to know besides the numbers?
The rule of three gives the first hospital an upper bound of about : its data are consistent with a rate far higher than the competitor's. The competitor's Wilson interval is roughly 0.3% to 2.2%, much tighter. A "0% rate" from a small number of operations is weak evidence. Beyond the numbers, you'd want to know whether the hospitals treat similar patients (case mix), how infections are counted and over what follow-up period, and whether infections diagnosed elsewhere are included. Rates from different denominators and definitions aren't comparable, the same lesson as Section 7.5's funnel plots.
Key Takeaways
- Wald:
; simple, but poor for small or near 0 or 1. - Wilson: solves for inside the standard error; better coverage, stays within . In R,
prop.test(x, n, correct = FALSE). - After 0 events in trials, the 95% upper bound is about .
8.6 What "95% confidence" means
After computing a 95% interval such as (0.70, 2.46) hours, it's tempting to say "there's a 95% probability that the true mean is between 0.70 and 2.46". In classical statistics, that statement isn't correct. The true mean is a fixed number; it's either in that interval or it isn't. The 95% describes the method: if we repeated the study many times, computing an interval each time, 95% of those intervals would contain .
Definition: Interpreting a Confidence Interval
Correct: "This interval was produced by a method that captures the true value in 95% of samples." Or: "Before the data were collected, there was a 95% probability that the interval we were about to compute would contain the true value."
Incorrect: "There is a 95% probability that lies in (0.70, 2.46)"; "95% of the data lie in the interval"; "a repeat study would have a 95% chance of a mean in this interval".
The distinction matters most when we have information beyond the data. A 95% interval for the speed of light that misses the known value (Example 8.12) is not "95% likely" to contain it; we know it doesn't. The coverage guarantee is about the long run of intervals, and Michelson's was one of the 5%, or (more likely) its assumptions failed.
Bayesian Inference: Credible Intervals: The Probability Statement People Want
A Bayesian treats the unknown parameter as uncertain, gives it a prior distribution, and updates it with the data (Section 5.5). The middle 95% of the posterior distribution is a 95% credible interval, and for it the natural statement is correct: given the model, the prior and the data, there's a 95% probability that the parameter lies in the interval.
For the pesticide data (42 of 150 over the limit), a uniform prior gives the posterior :
qbeta(c(0.025, 0.975), 43, 109) # 95% credible interval: 0.214 to 0.357
prop.test(42, 150, correct = FALSE)$conf.int # 95% Wilson interval: 0.214 to 0.357
[1] 0.2143697 0.3568306
[1] 0.2143304 0.3566565
attr(,"conf.level")
[1] 0.95
The two intervals agree to three decimal places, though they mean different things. With plenty of data and a flat prior, Bayesian and classical intervals usually agree numerically (Section 7.5's box). They part company when data are scarce, when there is genuine prior information (the speed of light, a well-studied drug), or when the prior is strong. Which interpretation you prefer is one of the oldest debates in statistics.
p <- seq(0.1, 0.5, by = 0.001); d <- data.frame(p, f = dbeta(p, 43, 109))
ci <- qbeta(c(0.025, 0.975), 43, 109)
ggplot(d, aes(p, f)) +
geom_area(data = subset(d, p >= ci[1] & p <= ci[2]), fill = "steelblue", alpha = 0.35) +
geom_line(linewidth = 1) +
annotate("text", x = 0.285, y = 3, label = "95% of the\nposterior") +
labs(x = "proportion p over the limit", y = "posterior density")
History: Neyman, Fisher and the Meaning of Confidence
The theory of confidence intervals was set out in 1937 by the Polish-American statistician Jerzy Neyman, who insisted that probability statements should describe procedures, not fixed parameters. Ronald Fisher (Section 4.6) had proposed a rival idea, "fiducial probability", which tried to make probability statements about parameters without a prior; the two men disagreed bitterly for decades, and fiducial inference never became standard. The Wilson interval is older still: the American mathematician Edwin Bidwell Wilson published it in 1927, and it was largely ignored for the rest of the century, while textbooks taught the Wald interval, until a series of papers around 2000 showed how badly the Wald interval can perform.
Check Yourself
In classical statistics, is the true mean random?
Is this an interval for individuals or for the mean? Compare the prediction interval of Example 8.11.
The 95% is a property of the method. Statement 1 is the Bayesian credible-interval interpretation, which needs a prior; statement 2 confuses a confidence interval with a range for individuals.
Think About It: Reading a News Report
A news story says: "A new study found that people who drink coffee live 1.8 years longer, with a 95% confidence interval of 0.2 to 3.4 years." List three questions you'd ask before believing that coffee extends life.
(1) Was this an experiment or an observational study? If people chose whether to drink coffee, coffee drinkers may differ in income, health or habits (confounding, Chapter 1), and the interval measures only random error, not this bias. (2) How many outcomes did the researchers examine? If they looked at dozens of foods and outcomes, one interval excluding zero is expected by chance (Section 4.4's Paul the octopus, again). (3) Does the interval describe an average or an individual? Even if the average effect is real, an individual coffee drinker's lifespan varies by decades. A confidence interval answers one narrow question, about random sampling error, under the study's assumptions.
Key Takeaways
- "95% confidence" describes the long-run success rate of the method, not the probability that a particular interval contains .
- A Bayesian credible interval does carry that probability, given a prior; with lots of data the two often agree numerically.
- Coverage is guaranteed only if the model's assumptions (random sampling, no bias, the right distribution) hold.
Prediction and inference in this chapter
- Inference. This chapter is inference at its core. An estimator turns data into a guess at an unseen parameter, and its bias, standard error and MSE say how good the rule is. The method of moments and maximum likelihood are general recipes for building estimators, and confidence intervals attach an honest margin of error. We estimated tank production, a speed, a drug effect, a rate of residues and a side-effect risk.
- Prediction. Every prediction from a model uses estimated parameters. The prediction interval of Example 8.11 shows that predicting one new case carries two uncertainties, the estimate's and the individual's, and that the second never goes away.
- The limits. Intervals cover random error, not bias (Michelson, the drifting breathalyser), and their coverage depends on the model's assumptions. "95% confidence" is a statement about a procedure, which is easy to misreport.
- What comes next. Chapter 9 asks a related question: instead of "what values of the parameter are plausible?", it asks "is one particular value plausible?". That is a hypothesis test, and there is a close link: a 95% confidence interval contains exactly the values that the corresponding two-sided test at the 5% level would not reject.
8.7 Interludes
Interlude (Optional): Sufficient Statistics: Data Compression Without Loss
In Example 8.5, the MLE of depended only on the number of 2FA users, not on which people they were. In Example 8.7, only the total number of burglaries mattered. A statistic is sufficient for if, once you know , the rest of the data carry no more information about . Fisher introduced the idea in 1922, and the factorization theorem gives a test: is sufficient if the likelihood can be written as
Why it matters: sufficiency tells you what to record. A lab that stores only the total count and the number of trials has lost nothing for estimating a Poisson or binomial rate; but it has lost the ability to check whether the model fits, which needs the individual values.
Interlude (Optional): The Cramér–Rao Bound: A Speed Limit for Estimators
How precise can an unbiased estimator possibly be? In the 1940s Harald Cramér and C. R. Rao independently proved a lower bound: for an unbiased estimator from an IID sample of size ,
Why it matters: the bound tells you when to stop looking for a better estimator, and how much data an experiment needs before it starts.
Interlude (Optional): Maximum Likelihood for Classification: Logistic Regression
Chapter 1 asked whether a mother's smoking is associated with low birth weight (MASS::birthwt). Logistic regression models the probability of a yes/no outcome through its log-odds:
fit <- glm(low ~ smoke, data = MASS::birthwt, family = binomial)
coef(fit)
exp(coef(fit)["smoke"]) # odds ratio for smokers
(Intercept) smoke
-1.0870515 0.7040592
smoke
2.021944
The fitted odds ratio is about 2.0: the odds of a low-birth-weight baby are about twice as high for smokers. (With one yes/no predictor, this is exactly the odds ratio in the 2 × 2 table:
Why it matters: logistic regression is maximum likelihood in action, and it is often the first method a data scientist reaches for. Its coefficients are estimates with standard errors, so everything in this chapter applies, including the warning that they measure association, not cause.
8.8 Exercises
Each exercise has a hint and an answer. For interval questions, state which case applies (σ known, σ unknown, large sample, proportion) before calculating.
Exercises
Time to a toxic reaction. The times in minutes for a chemical to produce a toxic reaction in 7 mice are 4.2, 5.1, 6.7, 4.9, 5.5, 6.2, 5.0. Assuming an exponential model, find the MLE of . Is the exponential model plausible?
. Compare the sample SD with the sample mean.
, so
per minute. Not very plausible: the SD (0.84) is far smaller than the mean (5.37), whereas an exponential's SD equals its mean. Intrusion flags. Of 6 intrusion attempts, a system flagged the 1st, 4th, 5th and 6th. Find the MLE of the detection probability, and its approximate standard error.
and
. , with SE : with 6 attempts, the estimate is very imprecise. A geometric MLE. A phishing tester sends emails until someone clicks. In four campaigns the first click came on email 3, 1, 4 and 2. Assuming each email is clicked independently with probability , find the MLE of .
The probability that the first click is on email is . Write the likelihood for all four campaigns.
, so gives , which is . Counting tanks. Four captured tanks have serial numbers 37, 82, 15 and 104. Estimate with each of the three rules of Example 8.1. Which would you report?
, , .
Twice the mean: 118. Largest: 104. Largest plus gap:
. Report 129: it's unbiased and has the smallest typical error. Chemical concentration (σ known). Ten samples have concentrations 13.2, 12.8, 14.0, 13.5, 13.1, 13.3, 12.9, 13.6, 13.7, 13.0 ppm. The population is Gaussian with known SD 0.4 ppm. Find a 95% confidence interval for the mean.
; SE .
ppm. Time to a verdict (σ unknown). Eight court cases took 41, 39, 43, 38, 37, 42, 40 and 44 days to reach a verdict. Assuming a Gaussian population, find a 90% confidence interval for the mean.
, , $t_{7,,0.05} = $
qt(0.95, 7).days. Load times (large sample). Fifty measurements of a website's load time give seconds and . Find a 95% confidence interval for the mean load time. Why is a Gaussian population not needed?
With , the CLT makes approximately Gaussian.
seconds. The CLT covers the sampling distribution of the mean, whatever the shape of the population (unless it is extremely skewed). Phishing detection. A filter correctly flags 72 of 100 phishing emails. Find 95% Wald and Wilson intervals for its detection rate, and compare.
Use the formulas of Section 8.5, or
prop.test(72, 100, correct = FALSE).Wald ; Wilson . Similar, with Wilson's shifted slightly towards 0.5.
Blood alcohol. Six forensic cases had blood alcohol levels 0.082, 0.089, 0.075, 0.081, 0.085, 0.080 g/dL. Assume a Gaussian population. (a) Estimate and by the method of moments. (b) Are these estimates unbiased? (c) Find a 95% confidence interval for .
The method of moments divides by for the variance. For (c), use (dividing by ) and .
(a) and . (b) is unbiased; is biased low (Example 8.2), and so is . (Even , though is unbiased for , is slightly biased low for .) (c) With :
. Two estimators of a Poisson rate. For a Poisson population, both and are unbiased estimators of (why?). Simulate 20,000 samples of size 20 from and compare their standard errors. Which would you use?
A Poisson's mean and variance both equal . Use
replicatewithc(mean(x), var(x)).Both average about 4, but the SE of is about 0.45 and of about 1.37. Use , which is also the MLE.
Coverage by simulation. Simulate 10,000 samples of size 20 from a population with , compute the 95% Wald and Wilson intervals for each, and find the fraction of each that contains 0.1.
x <- rbinom(10000, 20, 0.1), then compute both intervals for eachxwith vector arithmetic.About 0.87 for Wald and 0.96 for Wilson. The Wald interval misses far more often than its 5% promise.
Galton's sons. For the 481 sons, and inches. (a) Find a 95% confidence interval for the mean height of the population they represent. (b) Find a 95% prediction interval for one more son's height. (c) Why might the interval in (a) be too narrow? (Hint: Section 7.1's warning box.)
For (b), use .
(a)
. (b) . (c) Brothers share families, so the 481 heights aren't independent; the effective sample size is smaller than 481, and the true standard error is larger. Planning a study. A toxicologist wants a 95% interval of total width 1 µg/dL for the mean blood lead level of workers, whose SD is believed to be about 5. How many workers should be sampled? What if the SD is actually 7?
Width
. , so 385 workers. If , the interval from 385 workers would be µg/dL wide; achieving width 1 would need workers. Interpreting intervals. For each statement about a 95% confidence interval of (12, 18) for a city's mean commute time in minutes, say whether it's correct, and fix it if not. (a) "95% of commuters take between 12 and 18 minutes." (b) "If we repeated the survey many times, about 95% of the intervals would contain the true mean." (c) "There's a 5% chance the true mean is above 18."
Is each statement about individuals, about the method or about the parameter?
(a) Wrong: that's a statement about individuals, which needs a prediction interval (much wider). (b) Correct. (c) Wrong in classical statistics: the true mean is fixed. A Bayesian credible interval could support a statement like it, given a prior, but even then a central 95% interval leaves 2.5% above 18, not 5%.