Lecture 9 Consistency by Simulation

In this lecture we use simulation to watch an estimator get closer to the truth as the sample size grows, i.e. the consistency from lecture 2. We see this in three ways: through a single estimate as observations are added, through the sampling distribution at three sample sizes and through the mean squared error as a function of nn. On the way we extend the Monte Carlo skills from lecture 6 by a loop which varies the sample size. We conclude with a simulation which shows what lecture 8 means by a sufficient statistic. As before, appendix B contains a written reference for this topic.

9.1 A Running Estimate

In this section we simulate one long sample and watch the estimate change as the observations arrive one by one.

We will consider the exponential distribution with rate θ=2\theta=2, where the maximum likelihood estimator for the rate is θ^n=1/X¯n\hat{\theta}_{n}=1/\bar{X}_{n}, as found in example 5.2. This estimator is consistent for θ\theta by example 2.12 and proposition A.17. The most direct way to see the estimator at work is to simulate one long sample and to re-compute the estimate after each observation. The command cumsum can be used to compute the running totals X1X_{1}, X1+X2X_{1}+X_{2}, X1+X2+X3,…X_{1}+X_{2}+X_{3},\ldots in one step, and dividing the count nn by these totals gives all 20002000 running estimates at once. Before you look at the plot, sketch the path you expect. Where is it most volatile?

theta <- 2
set.seed(2026)
x <- rexp(2000, rate = theta)
n <- seq_len(2000)
running <- n / cumsum(x)
plot(n, running, type = "l", log = "x", ylim = c(1, 3.5),
xlab = "n", ylab = "running estimate")
abline(h = theta, lty = 2)
abline(h = theta + c(-0.1, 0.1), lty = 3)
A jagged path plotted against n on a logarithmic
axis, ranging from 1 to 2000. The path starts above 3.5, shows
large fluctuations for small n, drops below the dashed line at 2
early on and stays below it. Between n near 100 and n near 900 the
path crosses the lower dotted line at 1.9 several times; after that
it stays inside the band.
Figure 9.1: The running estimate 1/X¯n1/\bar{X}_{n} for the exponential rate θ=2\theta=2, plotted against nn on a logarithmic axis. The truth is given by the dashed line, the band θ±0.1\theta\pm 0.1 is given by the dotted lines.

Figure 9.1 shows the expected behaviour: the path fluctuates strongly for small nn, crosses the edge of the band θ±0.1\theta\pm 0.1 several times and ends inside it. A single path, however, cannot tell us how likely it is to be outside the band at a given nn, and this is what consistency is about.

9.2 The Sampling Distribution as nn Grows

In this section we compare the sampling distribution at three sample sizes and which fraction of estimates misses the truth by more than a fixed amount.

By definition 2.9, consistency means that for every band around the truth, here θ±0.1\theta\pm 0.1, the probability ℙθ⁢(|θ^n−θ|≥0.1)\mathbb{P}_{\theta}\bigl{(}|\hat{\theta}_{n}-\theta|\geq 0.1\bigr{)} of missing the band goes to zero as nn increases. A probability is a property of many repetitions, and thus, as in lecture 6, we use replicate to compute 1000010000 independent estimates, at each of the sample sizes n=10n=10, n=100n=100 and n=1000n=1000. The fraction of estimates outside the band estimates the probability; as in appendix B, the mean of a condition is the fraction of cases where it holds. Before you run the code, write down three guesses for the three fractions. Will the fraction for n=1000n=1000 be close to zero?

set.seed(2026)
est10 <- replicate(10000, 1 / mean(rexp(10, rate = theta)))
est100 <- replicate(10000, 1 / mean(rexp(100, rate = theta)))
est1000 <- replicate(10000, 1 / mean(rexp(1000, rate = theta)))
c(mean(abs(est10 - theta) >= 0.1),
mean(abs(est100 - theta) >= 0.1),
mean(abs(est1000 - theta) >= 0.1))
## [1] 0.8756 0.6211 0.1160

The probability of missing the band decreases from 0.880.88 at n=10n=10 to 0.120.12 at n=1000n=1000, as consistency requires, but at n=1000n=1000 it is still far from zero: the band is narrow, and consistency only says that the probability goes to zero eventually. To see the whole sampling distribution we draw the three histograms with a common horizontal axis, as in lecture 6. New is the argument freq = FALSE, which draws the histogram on the density scale, so that the total area of the bars is one and a narrower histogram must be a taller one. Values outside the horizontal range are not shown; for n=10n=10 these are about 8%8\% of the estimates, almost all of them in the long right tail. The dotted lines mark the band.

par(mfrow = c(3, 1))
hist(est10, breaks = 60, freq = FALSE, col = "grey85", main = "n = 10",
xlab = "estimate", xlim = c(1, 3.5))
abline(v = theta + c(-0.1, 0.1), lty = 3)
hist(est100, breaks = 40, freq = FALSE, col = "grey85", main = "n = 100",
xlab = "estimate", xlim = c(1, 3.5))
abline(v = theta + c(-0.1, 0.1), lty = 3)
hist(est1000, breaks = 40, freq = FALSE, col = "grey85", main = "n = 1000",
xlab = "estimate", xlim = c(1, 3.5))
abline(v = theta + c(-0.1, 0.1), lty = 3)
Three histograms stacked vertically, all on the
horizontal range from 1 to 3.5, with dotted vertical lines at 1.9
and 2.1. For n = 10 the histogram is wide and right-skewed,
covering the whole range with its peak near 1.9 and heights up to
about 0.65. For n = 100 it is a bell shape between about 1.5 and
2.7, peaking near 2 with heights up to 2. For n = 1000 it is a
narrow spike between 1.8 and 2.25, peaking at about 6, lying mostly
inside the dotted lines.
Figure 9.2: Histograms of 1000010000 simulated values of 1/X¯n1/\bar{X}_{n} for the exponential rate θ=2\theta=2, at n=10n=10, n=100n=100 and n=1000n=1000, on the density scale and with a common horizontal axis. The dotted lines mark the band θ±0.1\theta\pm 0.1.

Figure 9.2 is the picture promised in lectures 3 and 6: the histogram gets tighter around the truth as nn grows. For n=10n=10 it is also visibly skewed to the right, since 1/X¯n1/\bar{X}_{n} is large whenever the sample mean is small, while for n=1000n=1000 it is close to symmetric.

9.3 The Mean Squared Error as a Function of the Sample Size

In this section we estimate the mean squared error of two estimators for a range of sample sizes, collect the results in a table and plot them.

For a report a single number per sample size is often more useful than a histogram. In lecture 6 we estimated the mean squared error of the two uniform estimators 2⁢X¯2\bar{X} and maxi⁡Xi\max_{i}X_{i} for n=10n=10. We now repeat this study for several sample sizes, which is the usual shape of a simulation study: an outer loop over a setting, an inner Monte Carlo run and a table of results. We first put both estimates into one function, so that both are computed from the same sample and returned as a vector of length two. The command replicate then collects the 1000010000 repetitions into a matrix, a rectangular table of numbers with two rows, one per estimator, and 1000010000 columns, one per repetition, and the command rowMeans can be used to average each row.

est_both <- function(n, theta) {
sample <- runif(n, min = 0, max = theta)
c(2 * mean(sample), max(sample))
}

The outer loop runs over a vector ns of sample sizes, using seq_along(ns) to count through its positions. The command matrix(0, nrow = length(ns), ncol = 2) can be used to set aside a matrix for the results, mse[j, ] refers to the jj-th row of this matrix, and row and column names, set using rownames and colnames, can be used to make the matrix a readable table. As in lecture 6, the box below shows the complete script, with the lines of the loop kept together for clarity, but with the lines in a shuffled order.

Exercise. Before you read the script, you need to work out the correct order of lines to make the script work.

signif(mse, 3)
for (j in seq_along(ns)) {
ests <- replicate(10000, est_both(ns[j], theta))
mse[j, ] <- rowMeans((ests - theta)^2)
}
mse <- matrix(0, nrow = length(ns), ncol = 2)
set.seed(2026)
rownames(mse) <- ns
theta <- 1
colnames(mse) <- c("2 * mean", "max")
ns <- c(5, 10, 20, 50, 100, 200, 500, 1000)

The rule for writing R scripts is still in force: all names must be defined before they are used, so ns must come before the matrix is created and theta before the loop, the seed must be set before the loop starts, and the display (using signif to round the numbers) must come last. As in lecture 6, several orders satisfy these rules.

For n=10n=10 the mean squared error of the maximum was approximately half of the one for 2⁢X¯2\bar{X}. Before you run the reconstructed script, make a prediction. Will this ratio stay close to two for n=1000n=1000?

theta <- 1
ns <- c(5, 10, 20, 50, 100, 200, 500, 1000)
mse <- matrix(0, nrow = length(ns), ncol = 2)
set.seed(2026)
for (j in seq_along(ns)) {
ests <- replicate(10000, est_both(ns[j], theta))
mse[j, ] <- rowMeans((ests - theta)^2)
}
rownames(mse) <- ns
colnames(mse) <- c("2 * mean", "max")
signif(mse, 3)
## 2 * mean max
## 5 0.065900 4.58e-02
## 10 0.033300 1.52e-02
## 20 0.016600 4.48e-03
## 50 0.006610 7.51e-04
## 100 0.003310 1.91e-04
## 200 0.001660 5.07e-05
## 500 0.000668 7.86e-06
## 1000 0.000331 1.99e-06

The values in each column decrease towards zero as nn increases, and thus both estimators are consistent by lemma 2.11. The ratio between the two columns is not close to two anymore: for n=1000n=1000 the mean squared error for the maximum is smaller by a factor of approximately 170170. This is expected, since the exact mean squared error θ2/(3⁢n)\theta^{2}/(3n) of exercise 2.2 decreases like 1/n1/n, while the exact value 2⁢θ2/((n+1)⁢(n+2))2\theta^{2}/\bigl{(}(n+1)(n+2)\bigr{)} of exercise 4.4 decreases like 1/n21/n^{2}. On log-log axes, which the argument log = "xy" selects, a quantity proportional to n−kn^{-k} is a straight line with slope −k-k. The command points can be used to add a second set of points to an existing plot, with the plotting symbol chosen by the argument pch, and the command legend can be used to add a key. Will the two sets of points be parallel?

plot(ns, mse[, 1], log = "xy", pch = 16, xlab = "n", ylab = "MSE",
ylim = range(mse))
points(ns, mse[, 2], pch = 1)
lines(ns, theta^2 / (3 * ns), lty = 2)
lines(ns, 2 * theta^2 / ((ns + 1) * (ns + 2)), lty = 3)
legend("bottomleft", legend = c("2 * mean", "max"),
pch = c(16, 1), lty = c(2, 3))
Eight filled and eight open circles on log-log
axes, for n ranging from 5 to 1000. The filled circles lie on a
dashed straight line with a moderate negative slope, the exact
mean squared error of 2 times the mean. The open circles lie on a
dotted line, the exact mean squared error of the maximum, with a
slope twice as negative as the dashed line. The two lines
separate as n increases.
Figure 9.3: Simulated mean squared errors for 2⁢X¯2\bar{X} (filled circles) and maxi⁡Xi\max_{i}X_{i} (open circles), for the uniform parameter θ=1\theta=1, on logarithmic axes. The exact values θ2/(3⁢n)\theta^{2}/(3n) (dashed line) and 2⁢θ2/((n+1)⁢(n+2))2\theta^{2}/\bigl{(}(n+1)(n+2)\bigr{)} (dotted line) are also shown.

Both sets of points lie on straight lines: the slope is −1-1 for 2⁢X¯2\bar{X} and the slope is −2-2 for the maximum. The rate 1/n1/n is the usual rate of decrease for a mean squared error; it is the rate of the sample mean in example 2.8. The faster rate for the maximum is a consequence of the support of the uniform distribution moving with θ\theta, the same feature which, by the remark after example 7.4 in lecture 7, keeps the uniform distribution out of the exponential families. We will consider this example again in lecture 13.

9.4 A Sufficient Statistic in R

In this section we check by simulation that the conditional distribution of a Poisson sample given its total does not depend on θ\theta.

To conclude this lecture, we consider an example from lecture 8: for Poisson samples, the total ∑iXi\sum_{i}X_{i} is sufficient by example 8.6. By definition of sufficiency, given the total, the conditional distribution of the sample does not depend on θ\theta. We can see this by simulation, without any algebra. We generate many Poisson samples of size n=5n=5, keep only those whose total equals 1010, and look at the first observation in the kept samples; we do this for two different values of θ\theta.

The command replicate returns a matrix with 55 rows and one column per sample, colSums computes the column totals, and samples[1, totals == 10] selects from the first row the columns where the condition holds. The command table can be used to count how often each value occurs, and dividing by the number of kept samples turns the counts into proportions. Before you run the code, make a prediction. Will the two tables of proportions be different, since the two values of θ\theta are different? What will the mean of the first observation be in each case?

first_given_total <- function(theta, N) {
samples <- replicate(N, rpois(5, lambda = theta))
totals <- colSums(samples)
samples[1, totals == 10]
}
set.seed(2026)
first1 <- first_given_total(1.5, 100000)
first3 <- first_given_total(3, 100000)
c(length(first1), length(first3))
round(table(first1) / length(first1), 3)
round(table(first3) / length(first3), 3)
c(mean(first1), mean(first3))
## [1] 8749 4870
## first1
## 0 1 2 3 4 5 6 7
## 0.110 0.269 0.296 0.203 0.087 0.028 0.006 0.001
## first3
## 0 1 2 3 4 5 6 7
## 0.105 0.266 0.300 0.210 0.087 0.025 0.007 0.001
## [1] 2.002857 2.014168

The total equals 1010 for about 9%9\% of the samples when θ=1.5\theta=1.5 and for about 5%5\% when θ=3\theta=3, so the two values of θ\theta clearly matter for how often the total is 1010. Once the total is fixed, however, the two tables agree up to simulation error, and both means are close to 10/5=210/5=2: given the total, the first observation has the same distribution whether θ=1.5\theta=1.5 or θ=3\theta=3. This is definition 8.1 in action. All that the data can tell us about θ\theta is carried by the total, and the distribution of the individual counts around it is the same for every θ\theta. (The proportions in the table are themselves estimates; with about 90009000 and 50005000 kept samples the simulation error is between 0.0050.005 and 0.0070.007 for the larger entries.)

9.5 A Task to Take Home

The following task is a review of the topics of this lecture, in the style of a practical report. Following the structure of section 9.3, for the exponential rate with θ=2\theta=2 and sample sizes given in ns, estimate the bias and mean squared error of the maximum likelihood estimator 1/X¯1/\bar{X} using 1000010000 repetitions each, in a table with named rows and columns. Create a plot of the mean squared error against nn, using logarithmic axes. From the plot, determine the slope. Compare the empirical bias to the exact value from exercise 2.3. Write three sentences about what the table and plot show about the consistency of the estimator 1/X¯1/\bar{X}.

Before the next session, type in the commands from this session and check that the output matches what is shown in the text.

Summary.
  • •
    ​

    Appendix B is the written reference for cumsum, the matrices returned by replicate, colSums, rpois, table and legend.

  • •
    ​

    The command cumsum can be used to compute all running estimates of a growing sample at once. One path shows an estimate settling down, but consistency is a statement about the probability of missing a band at a fixed nn, which only many repetitions can show.

  • •
    ​

    When the Monte Carlo study is repeated at several sample sizes, the fraction of estimates outside the band decreases and the histograms get tighter around the truth. With freq = FALSE a histogram is drawn on the density scale.

  • •
    ​

    A loop over a vector of sample sizes, with the results of each Monte Carlo run stored in one row of a matrix, gives the mean squared error as a function of nn. On log-log axes a mean squared error proportional to n−kn^{-k} is a straight line with slope −k-k: for the uniform parameter, 2⁢X¯2\bar{X} shows slope −1-1, the usual rate, and maxi⁡Xi\max_{i}X_{i} slope −2-2.

  • •
    ​

    Keeping only the Poisson samples with a given total, the distribution of the first observation is the same for two different values of θ\theta: the total is sufficient, in the sense of definition 8.1.