Lecture 9 Consistency by Simulation
This is the R session for week 3. In the previous two sessions we were promised that we would watch an estimator converge to the truth, i.e. the consistency from lecture 2. Today we will see this convergence in two different ways: we will watch an estimate converge to the truth as observations are added, and we will plot the mean squared error against . On the way there we will extend the Monte Carlo skills we acquired in lecture 6 by introducing a loop which varies the sample size and a matrix to store the results. We will conclude by doing a computation which shows what lecture 8 means by a sufficient statistic. As before, appendix B contains a written reference for this topic. We will predict the outcome of the simulations before we start each one.
9.1 A Running Estimate
Consistency, definition 2.8, is a statement about the sequence of estimators as the sample size increases. The most direct way to visualise this sequence is to simulate a long sample and to re-compute the estimate after each observation. We will consider the exponential distribution with rate , where the maximum likelihood estimator for the rate is , as found in example 5.2, and we will see that this estimator is consistent for , by theorems 2.9 and A.17.
The command cumsum can be used to compute the running totals , and so on in one step, and dividing the count by these totals gives all running estimates at once. Before you look at the output, predict the five printed numbers. How far from do you expect the estimate after one observation to be? How far after ?
The first estimate is , which could be any number; in this example it is more than twice the truth. By the estimate is within of the truth. To get a better understanding of the path taken by the estimate, we plot the estimate against . The argument log = "x" for the plot command tells R to plot on a logarithmic axis, so that we can still see the early part of the path. Before we look at the plot, try to sketch the path you expect the estimate to take. Where is the curve most volatile? Once the curve enters the band , does it stay there?

Figure 9.1 shows the expected behaviour: the path is wild for small and ends inside the band. It does not converge in the sense of a sequence of numbers where, after some point, no term is outside the band; the path leaves and re-enters the band at random times. What decreases is the probability of being outside the band at a given , as given in definition 2.8.
9.2 The Mean Squared Error as a Function of the Sample Size
In lecture 6 we estimated the mean squared error of the two uniform estimators and for . To see how each decreases with we repeat the study for several sample sizes, and this is the everyday shape of a simulation study in the practical report: 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 collects the repetitions into a matrix, a rectangular table of numbers with two rows, one per estimator, and the command rowMeans can be used to average each row.
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 -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. Before you read the script, you should try 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) <- nstheta <- 1colnames(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, i.e. theta and ns must come first, the seed of the random number generator must be set before the loop starts, and the names and the display (using the signif function to round the numbers) require the matrix to be complete. Before you try the reconstructed script, try to predict the last row of the output. What will the two mean squared errors be for ? For the second mean squared error was approximately half of the first one. Will the ratio between the two mean squared errors stay close to two, or will it change?
theta <- 1ns <- 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) <- nscolnames(mse) <- c("2 * mean", "max")signif(mse, 3)The row for coincides with the two numbers from lecture 6 up to simulation error (the samples are not the same, since the loop has already sampled the values first), and the values for each column decrease as increases, as expected from the sufficient condition for consistency given in corollary 2.11. The ratio between the mean squared errors is not close to two anymore: for the mean squared error for the maximum is smaller by a factor of approximately . The exact values from exercises 2.2 and 4.4 show that this is expected, since decreases like while decreases like . If we plot the data on log-log axes, i.e. if we use the argument log = "xy" for the plot, then a quantity proportional to can be plotted as a straight line with slope . What will the two sets of points look like on a log-log plot? Will the two sets of points be parallel?

Both sets of points lie on straight lines: the slope is for and the slope is for the maximum. The usual rate of decrease for a mean squared error is like . All the estimators we will consider in the R strand of this module will have slope . The faster rate for the maximum is a consequence of the support of the uniform distribution moving with . We will consider this example again in lecture 13.
We can also consider the full sampling distribution of the maximum at , since in lecture 8 we know the exact density: by proposition 8.9 and example 8.10, the maximum of observations from has density for . To plot this density on top of a histogram, we need to plot the histogram using the density scale. This can be achieved by using the argument freq = FALSE of hist. Then the command curve can be used to plot any function of x on the horizontal axis, on top of the existing plot, if add = TRUE is used. Sketch the density before the plot appears. Where is the density largest? What is the density at ?
The curve closely follows the tops of the bars, and reaches the value at the boundary of the interval. The histogram is not a bell-shaped distribution as in figure 6.1: a sampling distribution can be concentrated around the truth, without being normal. In figure B.1 in appendix B you can see the same construction for a normal sample.
9.3 A Sufficient Statistic in R
To conclude these notes, we consider an example for use in lecture 8: for Poisson samples, the total number of counts is sufficient by example 8.4. The factorisation theorem 8.2 states that for data sets with the same total count, the likelihoods are proportional, differing by a constant shift on the log scale. We consider three data sets of size , where the first two have the same total count. We compute the log-likelihood for these data sets using the dpois function in R, with the log = TRUE option to get the log-likelihoods, and without any manual simplification of the results. The sapply command can be used to evaluate a function on every element of a vector; here we use it to evaluate the log-likelihoods on a grid of -values. Will the difference between the first two curves be the same at every grid point? Will the same be true for the first and third curves? Do the three maxima coincide?
x1 <- c(2, 0, 3, 1, 4)x2 <- c(2, 2, 2, 2, 2)x3 <- c(0, 1, 0, 2, 1)c(sum(x1), sum(x2), sum(x3))loglik <- function(theta, data) { sum(dpois(data, lambda = theta, log = TRUE))}grid <- seq(0.5, 4, by = 0.01)ll1 <- sapply(grid, loglik, data = x1)ll2 <- sapply(grid, loglik, data = x2)ll3 <- sapply(grid, loglik, data = x3)range(ll1 - ll2)range(ll1 - ll3)grid[c(which.max(ll1), which.max(ll2), which.max(ll3))]The difference between the first two curves is constant at every grid point, taking the value . This is equal to , the logarithm of the ratio of the two factors , which do not depend on . The difference to the third curve varies between and . The first two maxima are both at while the third maximum is at . The likelihood does not allow us to infer anything about beyond what is already known from the total count: for x1 and x2, the information about is the same, once the total count is known.
9.4 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.2, for the exponential rate with and sample sizes given in ns, estimate the bias and mean squared error of the maximum likelihood estimator using repetitions each, in a table with named rows and columns. Create a plot of the mean squared error against , 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 .
Just like it is important to understand the syntax of a programming language, it is also important to be able to read the output of R commands. Before the next session, type in the commands from this session, and check that the output matches what is shown in the text.
-
•
Appendix B is the written reference for cumsum, the matrices returned by replicate and curve.
-
•
The command cumsum can be used to compute all running estimates of a growing sample at once. Plotted against , the path keeps leaving and re-entering a band around the truth; what decreases is the probability of being outside it.
-
•
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 . On log-log axes a mean squared error proportional to is a straight line with slope : for the uniform parameter, shows slope , the usual rate, and slope .
-
•
With the argument freq = FALSE a histogram is drawn on the density scale, and curve(..., add = TRUE) can be used to superimpose a theoretical density on top of it.
-
•
Two Poisson data sets with the same total have log-likelihoods which differ by a constant: the total is sufficient.