Properties of estimators — R practice with simulations of bias, MSE, the Cramér–Rao bound and consistency (and the 10,000 variances I did not ask for)

The night before practical 11 I tried to compute the variance of each fleet estimator with apply(sims, 2, var) and R gave me back 10,000 variances instead of three. I had typed a 2 where a 1 belonged: in apply, 1 goes along rows and 2 along columns, and in my matrix each row was an estimator and each column a sample. I was computing the variance of the three numbers in each sample, which means nothing. I noticed because the console filled up with numbers; had I taken the mean() of that result, I would have got a perfectly calm number and never known. Since then, before summarising a simulation, I look at dim() and ask myself what a row is and what a column is.

This practice puts into R everything from the properties of estimators theory and checks with numbers what was proved in the proofs. There are three medium-level programs, with the rental scooter fleet in Las Palmas: the first simulates the three estimators of the fleet size and summarises them with a function of our own; the second measures the Cramér–Rao bound with the trips per hour and the duration; the third watches the maximum likelihood estimator of the duration become consistent and normal as the sample grows. Simulations are the way to “repeat the sampling many times”, which is exactly what the properties measure.

Before you start

It helps to be clear about:

  • What the bias E(θ^)−θ E(\hat\theta) – \theta , the MSE E[(θ^−θ)2]=Var+b2 E[(\hat\theta – \theta)^2] = \text{Var} + b^2 and the Cramér–Rao bound 1/(n i(θ)) 1/(n\,i(\theta)) are.
  • How replicate(B, { … }) works: it repeats the block B times and, if the block returns a vector, it stacks the results by columns.
  • The difference between apply(m, 1, f) (applies f to each row) and apply(m, 2, f) (to each column).
  • That var() divides by n − 1 (it is the sample variance S²).

If any of these sounds shaky, go over the theory before carrying on.

Put a set.seed() at the start of each simulation. That way, if you run the script again, you get the same numbers as here, and if something changes you will know it is your code and not chance.

Program 1: the three fleet estimators, simulated and summarised

We want to compare the three estimators of the fleet size (2Xˉ 2\bar X , the maximum and the corrected maximum n+1nX(n) \frac{n+1}{n}X_{(n)} ) with a fleet of θ = 2400 scooters and samples of 12 serial numbers. The tricky part: making the simulation and the summary work for any θ and any n, getting mean, bias, variance and MSE at once from the summary, and making the identity MSE=Var+b2 \text{MSE} = \text{Var} + b^2 hold.

The idea

Two functions. simulate(theta, n, B) generates B samples and returns a matrix with one estimator per row. summarise_est(sims, theta) walks the rows with apply(…, 1, …) and computes the four numbers for each estimator. So that the MSE identity comes out exact with the simulation numbers, the variance is computed dividing by B (the mean of the squared deviations), not with var(). Then, three histograms in a row with par(mfrow = c(1, 3)).

Put into words: in real life you only have one sample of 12 serial numbers and one estimate. To know whether an estimator is good, you have to imagine 10,000 classmates, each with their own sample of 12 scooters from the same fleet, and look at where their 10,000 estimates land. That is what simulate does: since I choose the fleet (2400), I can see who gets it right on average (the bias), who moves around less (the variance) and who makes the smallest error overall (the MSE).

Before coding, think about the shape sims will have. If the replicate block returns 3 numbers and you repeat it 10,000 times, the matrix is 3 × 10,000.

The code

# Program 1: the three estimators of the fleet size, simulated
simulate <- function(theta, n, B = 10000) {
  replicate(B, {
    x <- runif(n, 0, theta)                     # n serial numbers from a fleet of theta
    c(moments   = 2 * mean(x),                  # the three estimators for this sample
      maximum   = max(x),
      corrected = (n + 1) / n * max(x))
  })                                            # 3 x B matrix: one estimator per row
}

summarise_est <- function(sims, theta) {
  mean_est <- apply(sims, 1, mean)              # 1 = by rows: one value per estimator
  bias     <- mean_est - theta
  variance <- apply(sims, 1, function(v) mean((v - mean(v))^2))   # over B, not B - 1
  mse      <- apply(sims, 1, function(v) mean((v - theta)^2))
  round(data.frame(mean = mean_est, bias, variance, mse, root_mse = sqrt(mse)), 1)
}

set.seed(19)
sims <- simulate(2400, 12)
dim(sims)
summarise_est(sims, 2400)

par(mfrow = c(1, 3))                            # three plots in a row
for (k in 1:3) {
  hist(sims[k, ], breaks = seq(0, 4400, by = 100), freq = FALSE,
       xlim = c(1000, 3600), main = rownames(sims)[k], xlab = "scooters")
  abline(v = 2400, col = "red", lwd = 2)        # the real fleet
}

Output

[1]     3 10000
            mean   bias variance      mse root_mse
moments   2398.9   -1.1 161284.8 161286.1    401.6
maximum   2215.3 -184.7  29386.4  63503.8    252.0
corrected 2399.9   -0.1  34488.2  34488.2    185.7
The three histograms of program 1Three density histograms, from 1000 to 3600 scooters, with a red line at 2400. The moments one is a wide bell centred on the line. The maximum one rises up to 2400 and stops right at the line, with its tallest bar against it. The corrected one has the same shape stretched to the right and ends at 2600, with the red line inside.0.0000.0020.004100024003600momentsscooters0.0000.0020.004100024003600maximumscooters0.0000.0020.004100024003600correctedscooters
What par(mfrow = c(1, 3)) draws with the three hist calls and their abline at 2400.

How to read it

  • dim(sims) 3 10000: three rows (the estimators) and ten thousand columns (the samples). It is the check that would have saved me the story.
  • Column mean: 2398.9 for 2Xˉ 2\bar X , 2215.3 for the maximum and 2399.9 for the corrected one. The two unbiased ones are around 2400; the maximum sits on the formula 1213⋅2400=2215.38 \frac{12}{13}\cdot 2400 = 2215.38 .
  • Column bias: −1.1 and −0.1 are noise; −184.7 is the real bias of the maximum (the formula gives −2400/13=−184.6 -2400/13 = -184.6 ).
  • Columns variance and mse: for the unbiased ones they are almost equal (the squared bias is 1.2 and 0.0). For the maximum, 29,386.4+184.72=29,386.4+34,114=63,500 29{,}386.4 + 184.7^2 = 29{,}386.4 + 34{,}114 = 63{,}500 : that is the MSE in the table (63,503.8; the difference is the bias rounded to one decimal).
  • Column root_mse: the typical error in scooters. The corrected one is off by about 186 scooters; the maximum, 252; the moments one, 402.
  • The histograms: in the picture, the 2Xˉ 2\bar X one (left) is a wide bell centred on the red line. The maximum’s (center) rises to 2400 and stops dead: no sample crosses the line. The corrected one (right) has the same shape, stretched a twelfth to the right, and the red line falls inside it. That is the shape of nxn−1/θn n x^{n-1}/\theta^n from proof 3.

One sample, from the inside

The table summarises 10,000 samples at once and doesn’t let you see any of them. To see what is inside a single column of sims, repeat the first turn of the replicate by hand. With the same seed, the first runif gives exactly the same sample that simulate() used (with sims from the program already created):

set.seed(19)
x <- runif(12, 0, 2400)               # the same first sample that simulate() used
round(sort(x))                        # its 12 serial numbers, sorted
round(c(mean = mean(x), moments = 2 * mean(x), maximum = max(x),
        corrected = 13 / 12 * max(x)), 1)
round(sims[, 1], 1)                   # column 1 of the program's matrix

Output:

 [1]  164  281  537  701  877  976 1079 1162 1376 1563 1743 2008
     mean   moments   maximum corrected 
   1038.8    2077.6    2007.9    2175.2 
  moments   maximum corrected 
   2077.6    2007.9    2175.2 
EstimatorCalculationResultWhy
2Xˉ 2\bar X 2⋅1038.8 2 \cdot 1038.8 2077.6the mean of a uniform on (0, θ) is θ/2, so the mean is doubled
maximumthe largest of the 122007.9the fleet has at least as many scooters as the highest number seen
corrected1312⋅2007.9 \frac{13}{12} \cdot 2007.9 2175.2the maximum falls short on average; it is stretched by a twelfth to make up for it

The last line is column 1 of sims, and it matches number for number: a column is a sample and each row, an estimator. This sample came out with low numbers (the highest, 2008) and all three estimators fall short. It is one of 10,000: the program’s table looks at all 10,000 together.

Check you’ve got it: how would you get the maximum of sample number 5000?

With sims[2, 5000], or sims["maximum", 5000]. The row comes first, and it says which estimator you want (the maximum is the second one); then the column, which says which sample. If you write it the other way round, sims[5000, 2], R gives an error: the matrix only has 3 rows. It is the same rows-and-columns mix-up as in the story, but this time R warns you.

Questions you might ask

Why don’t I compute the variance with var()? Because var() divides by B − 1 = 9999, and then the variance plus the squared bias does not give exactly the mean of the squared errors (which divides by B). With 10,000 simulations the difference is one ten-thousandth, but this way the identity matches to the decimal and doubles as a check of the code.

Why breaks = seq(0, 4400, by = 100) instead of letting R choose? So that the three histograms have the same bins and can be compared at a glance. With automatic breaks, each would get a different bar width. The 4400 covers the highest value the corrected one can give (13/12 · 2400 = 2600) and those of 2Xˉ 2\bar X , which can go past 3500.

Why freq = FALSE? So that the vertical axis is density and the area of each histogram is 1. That way it can be compared with the theoretical density of the maximum if you draw it on top with curve.

Where does rownames(sims)[k] come from? From the names I put in c(moments = …, maximum = …, corrected = …): replicate keeps them as row names. Without them, the titles would be NULL.

Why a simulate function rather than copying the replicate? Because in “Try it yourself” you will repeat it with other θ and n. With the function, changing fleets means changing two numbers.

apply(sims, 2, mean). With the 2 you go along the columns (the samples) and get 10,000 means of three numbers each. If a summary has as many elements as simulations, you have the margin the wrong way round.

What would happen if you drew the sample outside the replicate?

R doesn’t complain, and that is why it is worth seeing. Same seed, same function, but with x generated only once, before repeating:

simulate_bad <- function(theta, n, B = 10000) {
  x <- runif(n, 0, theta)             # the sample OUTSIDE the replicate: drawn only once
  replicate(B, c(moments = 2 * mean(x), maximum = max(x), corrected = (n + 1) / n * max(x)))
}
set.seed(19)
summarise_est(simulate_bad(2400, 12), 2400)

Output:

            mean   bias variance      mse root_mse
moments   2077.6 -322.4        0 103945.2    322.4
maximum   2007.9 -392.1        0 153751.2    392.1
corrected 2175.2 -224.8        0  50529.3    224.8

The means are 2077.6, 2007.9 and 2175.2: the three numbers of the first sample, which you have just seen from the inside. With the sample outside, the 10,000 “simulations” repeat that same sample, so the variance is 0 and the whole MSE is squared bias (322.42≈103,942 322.4^2 \approx 103{,}942 ; the difference from 103,945.2 is the rounding of the bias). And the ranking comes out the other way round from the real one: here the maximum looks like the worst. The clue that gives it away is the variance column full of zeros.

Try it yourself

  • Repeat with simulate(2400, 50): the bias of the maximum should fall to about −2400/51=−47 -2400/51 = -47 and the MSE ratio of moments to corrected rise to 52/3≈17 52/3 \approx 17 .
  • Add a fourth estimator, Xˉ+3S \bar X + 3S (“the mean plus three standard deviations”, a rule-of-thumb trick) and look at its bias and MSE. Hint: S S is sd(x).

Program 2: the Cramér–Rao bound, measured

We want to see the Cramér–Rao bound for what it is, a floor, for several sample sizes. With the trips per hour (Poisson with λ = 3), we compare the variance of Xˉ \bar X and that of S2 S^2 (both unbiased) with the bound λ/n \lambda/n . With the duration (exponential with mean 12 minutes, λ = 1/12), that of the unbiased estimator λ∗=n−1nXˉ \lambda^* = \frac{n-1}{n\bar X} with its formula λ2/(n−2) \lambda^2/(n-2) and with the bound λ2/n \lambda^2/n . The tricky part: building a table with one row per n without writing five loops, and plotting it on a log scale.

The idea

sapply goes through the n values and, for each one, runs a simulation with replicate and returns a named vector. sapply sticks them together as columns; with t() they become rows, one per n. Since the variances fall like 1/n, with a log scale on both axes (log = "xy") they look like straight lines, and those of Xˉ \bar X and the bound should sit on top of each other.

Put into words: the Cramér–Rao bound answers “how much, at the very least, will an unbiased estimator move around?”. In the Poisson the information of one hour is i(λ)=1/λ i(\lambda) = 1/\lambda , so the bound is λ/n=3/n \lambda/n = 3/n . No unbiased estimator can go below it. The program measures how much two unbiased estimators really move and puts the floor next to them: if one touches it, it is efficient, and there is nothing better without accepting bias. In the exponential the same is done with λ∗ \lambda^* . The code writes it as (n - 1) / sum(…), which is the same as n−1nXˉ \frac{n-1}{n\bar X} because the sum is nXˉ n\bar X . There the theory already warns that it will stay a little above the floor, nn−2 \frac{n}{n-2} times.

Before coding, write down what you expect: Var(Xˉ)=3/n \text{Var}(\bar X) = 3/n , equal to the bound; Var(λ∗)=(1/12)2/(n−2) \text{Var}(\lambda^*) = (1/12)^2/(n-2) , somewhat above (1/12)2/n (1/12)^2/n .

The code

# Program 2: the Cramér-Rao bound in the Poisson (trips per hour) and the exponential (duration)
ns <- c(5, 10, 20, 40, 80)

set.seed(32)
pois <- t(sapply(ns, function(n) {
  e <- replicate(5000, { x <- rpois(n, 3); c(mean(x), var(x)) })   # row 1: means, row 2: S^2
  c(n = n, var_mean = var(e[1, ]), var_S2 = var(e[2, ]), bound = 3 / n)
}))
round(pois, 4)

set.seed(33)
lam <- 1 / 12
expo <- t(sapply(ns, function(n) {
  l <- replicate(5000, (n - 1) / sum(rexp(n, lam)))   # lambda* = (n - 1) / (n * mean)
  c(n = n, mean = mean(l), var_sim = var(l), var_theo = lam^2 / (n - 2), bound = lam^2 / n)
}))
signif(expo, 3)

plot(ns, pois[, "var_S2"], log = "xy", pch = 17, ylim = c(0.03, 6),
     xlab = "n (hours)", ylab = "variance", main = "Poisson(3): two unbiased estimators and the bound")
points(ns, pois[, "var_mean"], pch = 19)
lines(ns, pois[, "bound"], lty = 2, col = "red")
legend("topright", c("S^2", "mean", "bound"), pch = c(17, 19, NA), lty = c(NA, NA, 2), col = c(1, 1, 2))

Output

      n var_mean var_S2  bound
[1,]  5   0.5927 5.1044 0.6000
[2,] 10   0.2999 2.2772 0.3000
[3,] 20   0.1512 1.0840 0.1500
[4,] 40   0.0760 0.5266 0.0750
[5,] 80   0.0374 0.2637 0.0375
      n   mean  var_sim var_theo    bound
[1,]  5 0.0840 2.74e-03 0.002310 1.39e-03
[2,] 10 0.0836 9.23e-04 0.000868 6.94e-04
[3,] 20 0.0834 3.90e-04 0.000386 3.47e-04
[4,] 40 0.0833 1.78e-04 0.000183 1.74e-04
[5,] 80 0.0837 8.76e-05 0.000089 8.68e-05
The plot of program 2Plot with both axes on a log scale, with n equal to 5, 10, 20, 40 and 80. The triangles of the sample variance fall in a straight line from 5.1 to 0.26. The mean points fall in a parallel line, from 0.59 to 0.037, right on the dashed red line of the bound, 3 over n.0.050.10.515n (hours)variance510204080Poisson(3): two unbiased estimators and the boundS^2meanbound
What plot(…, log = "xy"), points, lines and legend draw: the mean on the bound, S² parallel and far above.

How to read it

  • Table pois, column var_mean: 0.5927, 0.2999, 0.1512, 0.0760 and 0.0374. Next to it, the bound: 0.6, 0.3, 0.15, 0.075 and 0.0375. They match in every row (within 2 %): Xˉ \bar X is efficient for any n, not just large n.
  • Column var_S2: between 7 and 8.5 times the bound. S2 S^2 is also unbiased for λ, but it moves around much more: with 20 hours, 1.08 against 0.15.
  • Table expo, column mean: around 0.0833 = 1/12 in every row: λ* is unbiased.
  • Columns var_sim and var_theo: they match from n = 10 on (9.23·10⁻⁴ against 8.68·10⁻⁴, and closer and closer). With n = 5 the simulation gives 2.74·10⁻³ and the formula 2.31·10⁻³: with such small samples, 1/Xˉ 1/\bar X has a very long tail (a mean of 5 very short trips blows up the ratio) and 5000 simulations are not enough to pin the variance down.
  • Column bound: always below var_theo, in the ratio n−2n \frac{n-2}{n} : with n = 5 the variance is 5/3 of the bound; with n = 80, 80/78. λ* is not efficient, but it is asymptotically efficient.
  • The plot: in the picture, on the log scale, the mean points fall on the dashed red bound line, and the S² triangles run along a parallel line far above. Parallel means both fall like 1/n; the gap between them (constant on a log scale) is the inefficiency of S2 S^2 .

Why S² stays seven or eight times above

The output says how much S2 S^2 moves, but not why. There is a general formula for the variance of the sample variance, Var(S2)=μ4n−σ4(n−3)n(n−1) \text{Var}(S^2) = \frac{\mu_4}{n} – \frac{\sigma^4 (n-3)}{n(n-1)} . With the moments of the Poisson (σ2=λ \sigma^2 = \lambda and μ4=λ+3λ2 \mu_4 = \lambda + 3\lambda^2 ) it simplifies to:

Var(S2)=λn+2λ2n−1 \text{Var}(S^2) = \frac{\lambda}{n} + \frac{2\lambda^2}{n-1}

With 5 hours and λ = 3, step by step:

StepCalculationResultWhy
first termλ/n=3/5 \lambda/n = 3/5 0.6it is exactly the bound: how much Xˉ \bar X moves
second term2λ2/(n−1)=18/4 2\lambda^2/(n-1) = 18/4 4.5what S2 S^2 adds by working with squares; with λ = 3 it weighs much more than the first
total0.6+4.5 0.6 + 4.5 5.1the simulation gives 5.1044
times the bound5.1/0.6 5.1/0.6 8.5the first row of “between 7 and 8.5”

If you divide the formula by the bound, you get 1+2λnn−1=1+6nn−1 1 + \frac{2\lambda n}{n-1} = 1 + \frac{6n}{n-1} . As n grows, nn−1 \frac{n}{n-1} gets closer to 1 and the ratio gets closer to 7. That is why the range is “between 7 and 8.5”: it is not a fluke of the simulation, and with more hours S2 S^2 never goes below 7 times the floor. Checked with the five rows (with program 2 just run):

nn <- pois[, "n"]                                  # the five sizes, taken from the table itself
var_S2_theo <- 3 / nn + 2 * 3^2 / (nn - 1)         # lambda / n + 2 lambda^2 / (n - 1)
round(cbind(pois[, c("n", "var_S2")], var_S2_theo,
            times_bound = var_S2_theo / pois[, "bound"]), 4)

Output:

      n var_S2 var_S2_theo times_bound
[1,]  5 5.1044      5.1000      8.5000
[2,] 10 2.2772      2.3000      7.6667
[3,] 20 1.0840      1.0974      7.3158
[4,] 40 0.5266      0.5365      7.1538
[5,] 80 0.2637      0.2653      7.0759

The simulated column and the formula’s are less than 2 % apart in every row (2.2772 against 2.30 with 10 hours), and times_bound falls from 8.5 towards 7 without reaching it.

Check you’ve got it: if the trips were Poisson with λ = 1, how many times the bound would the variance of S² be with a very large n?

About 3 times. The ratio is 1+2λnn−1 1 + \frac{2\lambda n}{n-1} , and with a very large n, nn−1 \frac{n}{n-1} is almost 1, so you are left with 1+2λ=1+2=3 1 + 2\lambda = 1 + 2 = 3 . The smaller λ is, the less S2 S^2 loses against Xˉ \bar X , but it never reaches the bound: the second term is always positive.

Questions you might ask

Why t()? Because sapply places each vector the function returns as a column. With five n values, you would get a 4 × 5 matrix with the n values in the first row. Transposed, each n is a row, which reads better.

Why signif(expo, 3) and not round? Because the variances of λ* are of the order of 10⁻⁴: with round(…, 4) you would get 0.0009 or 0.0001 and lose the digits that matter. signif keeps three significant figures whatever the size.

Why do you get straight lines with a log scale on both axes? If v=c/n v = c/n , then log⁡v=log⁡c−log⁡n \log v = \log c – \log n : a line with slope −1. Every variance falling like 1/n is a parallel line, and one falling like 1/n2 1/n^2 (like the fleet maximum’s) would have twice the slope.

What is ylim = c(0.03, 6) for? The first plot sets the axes from its own data (S²’s). If I do not tell it to go down to 0.03, the mean points and the bound, added later with points and lines, would fall outside the plot.

Comparing a biased estimator with the bound. The Cramér–Rao bound is only a floor for unbiased ones: the MLE 1/Xˉ 1/\bar X (biased) could fall below λ2/n \lambda^2/n with small n without contradicting anything.

Try it yourself

  • Add to the pois table a column with the variance of the median, median(x), and see how far it is from the bound.
  • In the expo table, add the variance of the uncorrected MLE, 1 / mean(x), and compare it with the bound with n = 5. Is it above or below?

Program 3: the duration MLE, with bigger and bigger samples

The duration MLE, λ^=1/Xˉ \hat\lambda = 1/\bar X , is biased with small samples. We want to see in numbers the asymptotic properties of the MLE: that the bias goes away (λn−1 \frac{\lambda}{n-1} ), that it is consistent (the probability of landing close climbs to 1) and that, standardised with its asymptotic variance, it looks more and more like an N(0, 1). At the end, we apply it to the 20 real trips: the estimate and its standard error, taken from the curvature with optim. The tricky part: standardising correctly and knowing which variance to use.

The idea

A function mle(n) returns 5000 MLEs with samples of size n. lapply calls it with n = 5, 20, 100 and 500 and keeps the four simulations in a list. For normality, we standardise with the asymptotic variance λ2/n \lambda^2/n : Z=λ^−λλ2/n Z = \frac{\hat\lambda – \lambda}{\sqrt{\lambda^2/n}} . If property 5 holds, Z should have mean 0, standard deviation 1 and fall outside ±1.96 5 % of the time.

Put into words: “asymptotic” means “when n is very large”. The three properties of the MLE (the bias disappears, it is consistent and it is almost normal) are promises for large samples, not for 5 trips. The program puts each promise to the test with a column: the bias, with the mean of the 5000 MLEs; consistency, with how often they land close to λ; normality, with Z. Standardising means subtracting the center and dividing by the standard deviation. If Z comes out with mean 0 and standard deviation 1, the shape that is left is that of an N(0, 1). With the real trips we don’t know λ: there the variance comes from the curvature of the log-likelihood.

Before coding, think about what you should see with n = 5. With 5 trips, asymptotic theory has not kicked in yet: expect a skewed Z.

The code

# Program 3: the duration MLE (exponential), as n grows
lam <- 1 / 12                                         # mean duration of 12 minutes
mle <- function(n, B = 5000) replicate(B, 1 / mean(rexp(n, lam)))

set.seed(41)
ns <- c(5, 20, 100, 500)
sim_list <- lapply(ns, mle)                           # one simulation per n
data.frame(n = ns,
           mean       = round(sapply(sim_list, mean), 4),
           bias_theo  = round(lam / (ns - 1), 4),     # lambda / (n - 1)
           within_001 = sapply(sim_list, function(l) mean(abs(l - lam) < 0.01)))

# asymptotic normality: standardise with the asymptotic variance lambda^2 / n
z5   <- (sim_list[[1]] - lam) / sqrt(lam^2 / 5)
z100 <- (sim_list[[3]] - lam) / sqrt(lam^2 / 100)
round(c(mean_z5 = mean(z5), sd_z5 = sd(z5), mean_z100 = mean(z100), sd_z100 = sd(z100)), 2)
round(c(out_z5 = mean(abs(z5) > 1.96), out_z100 = mean(abs(z100) > 1.96)), 3)

par(mfrow = c(1, 2))
hist(z5, breaks = seq(-4, 20, by = 0.5), freq = FALSE, xlim = c(-4, 8), main = "n = 5", xlab = "Z")
curve(dnorm(x), add = TRUE, col = "red", lwd = 2)
hist(z100, breaks = seq(-4, 20, by = 0.5), freq = FALSE, xlim = c(-4, 8), main = "n = 100", xlab = "Z")
curve(dnorm(x), add = TRUE, col = "red", lwd = 2)

# the 20 real trips: the estimate and its standard error
duration <- c(0.2, 11.0, 9.0, 18.9, 2.8, 13.0, 27.9, 8.7, 15.5, 8.1,
              5.1, 13.4, 15.8, 5.0, 8.1, 19.6, 0.9, 30.8, 20.9, 3.5)
n <- length(duration)
loglik <- function(l) n * log(l) - l * sum(duration)
o <- optim(1 / mean(duration), loglik, method = "Brent", lower = 0.001, upper = 1,
           control = list(fnscale = -1), hessian = TRUE)
se <- sqrt(-1 / o$hessian[1, 1])                     # standard error = root of -1 / l''
round(c(lambda = o$par, std_err = se,
        from = o$par - 2 * se, to = o$par + 2 * se), 4)

Output

    n   mean bias_theo within_001
1   5 0.1033    0.0208     0.2122
2  20 0.0875    0.0044     0.4006
3 100 0.0843    0.0008     0.7690
4 500 0.0835    0.0002     0.9902
  mean_z5     sd_z5 mean_z100   sd_z100 
     0.54      1.57      0.12      1.05 
  out_z5 out_z100 
   0.127    0.061 
 lambda std_err    from      to 
 0.0840  0.0188  0.0464  0.1215 
The two histograms of program 3Two density histograms of the standardised MLE, Z, between minus 4 and 8, each with the standard normal density in red on top. With n equal to 5, the histogram starts at minus 1.6, has its peak left of 0 and a long right tail running off the plot: it does not fit the bell. With n equal to 100, the histogram fits the red bell.0.000.250.50−4−202468n = 5Z0.000.250.50−4−202468n = 100Z
What the two hist calls with curve(dnorm(x), add = TRUE) draw: with n = 100, the MLE is already almost normal.

How to read it

  • Column mean: with 5 trips, the mean of the MLEs is 0.1033, well above λ = 0.0833. With 20, 0.0875; with 100, 0.0843; with 500, 0.0835. The bias goes away, and it does so as the bias_theo column says: 0.1033−0.0833=0.0200 0.1033 – 0.0833 = 0.0200 , next to the theoretical 0.0208; with 20, 0.0042 against 0.0044.
  • Column within_001: the proportion of times the MLE landed within 0.01 of λ. It climbs from 0.21 to 0.40, 0.77 and 0.99. That is consistency live: with 500 trips, the MLE almost always gets it right to within 0.01.
  • mean_z5 0.54 and sd_z5 1.57: with 5 trips, the standardised Z does not look like an N(0, 1): it is shifted right (the bias) and wider.
  • mean_z100 0.12 and sd_z100 1.05: with 100 trips it is almost an N(0, 1).
  • out_z5 0.127 and out_z100 0.061: with n = 5 it falls outside ±1.96 12.7 % of the time, more than twice a normal’s 5 %. With n = 100, 6.1 %: close.
  • The histograms: in the picture, the n = 5 one rises fast from −1.6 (λ^ \hat\lambda cannot go below 0, so Z cannot go below −5≈−2.2 -\sqrt5 \approx -2.2 ) and has a long right tail running off the plot; the red bell does not fit it. The n = 100 one already settles into the bell.
  • Last line: with the 20 real trips, λ^=0.084 \hat\lambda = 0.084 with standard error 0.0188, and λ^±2 \hat\lambda \pm 2 standard errors runs from 0.0464 to 0.1215. If the MLE is approximately normal, the true λ should lie in that stretch about 95 times out of 100. It is a preview of next topic’s confidence intervals.

The standard error, worked out by hand

The last line of the output comes from optim, which doesn’t show its working. With the exponential it can be done by hand, and that way you see where the 0.0188 comes from:

StepCalculationResultWhy
log-likelihoodℓ(λ)=nlog⁡λ−λ∑xi \ell(\lambda) = n\log\lambda – \lambda\sum x_i the loglik functionit is the logarithm of ∏λe−λxi \prod \lambda e^{-\lambda x_i} : the product becomes a sum
datan=20 n = 20 , ∑xi=238.2 \sum x_i = 238.2 xˉ=11.91 \bar x = 11.91 it is all the formula needs from the data
the peakℓ′(λ)=n/λ−∑xi=0 \ell'(\lambda) = n/\lambda – \sum x_i = 0 λ^=20/238.2=0.084 \hat\lambda = 20/238.2 = 0.084 at the maximum the slope is 0
the curvatureℓ′′(λ^)=−n/λ^2=−238.22/20 \ell''(\hat\lambda) = -n/\hat\lambda^2 = -238.2^2/20 −2836.96since λ^=n/∑xi \hat\lambda = n/\sum x_i , n/λ^2=(∑xi)2/n n/\hat\lambda^2 = (\sum x_i)^2/n , with no decimals dragged along
standard error−1/ℓ′′(λ^)=λ^/n \sqrt{-1/\ell''(\hat\lambda)} = \hat\lambda/\sqrt n 0.084/20=0.0188 0.084/\sqrt{20} = 0.0188 the more curved the peak, the smaller it comes out

Checked in R, with program 3 already run:

c(n = n, sum = sum(duration), mean = mean(duration))
lambda_hat <- n / sum(duration)                    # where l'(lambda) = n / lambda - sum is zero
round(c(l2_hand = -n / lambda_hat^2, l2_optim = o$hessian[1, 1]), 2)
round(c(lambda = lambda_hat, se_hand = lambda_hat / sqrt(n)), 4)

Output:

     n    sum   mean 
 20.00 238.20  11.91 
 l2_hand l2_optim 
-2836.96 -2837.77 
 lambda se_hand 
 0.0840  0.0188 

optim gives −2837.77 and not −2836.96 because it doesn’t differentiate with formulas: it approximates the curvature with very close points and slips in the fourth figure. In the standard error you can’t tell: both give 0.0188.

Check you’ve got it: if all the durations were twice as long, what standard error would you get?

0.0094, half. The sum becomes 476.4, so λ^=20/476.4=0.042 \hat\lambda = 20/476.4 = 0.042 and the standard error is 0.042/20=0.0094 0.042/\sqrt{20} = 0.0094 . Both are divided by 2 at the same time: the standard error is still 1/20 1/\sqrt{20} , 22 % of the estimate. With the exponential, the relative precision only depends on how many trips you look at, not on how long they are.

Questions you might ask

Why do I standardise with λ and not with λ^ \hat\lambda ? Because in the simulation I know λ (I chose it) and I want to see the distribution of the MLE with the exact formula of property 5. With real data I do not know it, and that is why in the last part the standard error comes from λ^ \hat\lambda (from the curvature at the maximum).

Why lapply and not sapply for the simulations? Because each simulation is a vector of 5000 numbers and I want to keep them whole. lapply returns a list with four vectors; then sapply(sim_list, mean) takes one number from each.

Why sim_list[[1]] with double brackets? Double brackets take out the element of the list (the vector); single ones, sim_list[1], would return a list with one element inside, and sim_list[1] - lam would give an error.

Is the rightward push of Z with n = 5 the bias? Partly: the bias of λ^ \hat\lambda is λ/4 \lambda/4 , which standardised gives λ/4λ/5=54=0.56 \frac{\lambda/4}{\lambda/\sqrt5} = \frac{\sqrt5}{4} = 0.56 . That is the mean of Z we get (0.54).

Why does optim start at 1 / mean(duration)? Because that is the MLE. optim finds it again (it is a check), but what we want is the Hessian at that point, and with Brent you have to give a starting point inside the interval.

Writing sqrt(1 / o$hessian). With fnscale = -1, optim maximises, but the Hessian it returns is that of the log-likelihood, which is negative at a maximum: without the minus sign you get NaN.

Try it yourself

  • Change the standardisation of z100 to use the variance of λ∗ \lambda^* instead of the asymptotic one and see whether sd_z100 gets closer to 1.
  • Repeat everything with the trip distance (normal), estimating σ² with S′2 S'^2 (the MLE): standardise with the asymptotic variance 2σ4/n 2\sigma^4/n .

Common mistakes in this practice

  • apply with the margin the wrong way round: 1 goes along rows and 2 along columns. If the summary has as many numbers as simulations, you used the wrong margin.
  • Variance with var() when you want to check the MSE identity: it divides by B − 1, and Var+b2 \text{Var} + b^2 does not match the MSE to the decimal.
  • Generating the sample outside the replicate: if x <- runif(…) is outside, the 10,000 “samples” are the same one and the estimator’s variance comes out 0.
  • Comparing a biased estimator with the bound: the bound is the floor for unbiased ones.
  • Forgetting the sign of the Hessian: with fnscale = -1, the asymptotic variance is -1 / o$hessian.
  • round with very small numbers: variances of the order of 10⁻⁴ round to 0; use signif.

Try it in the R playground

Paste this script into the R playground. It is program 1 boiled down to the essentials, with a fleet you can change:

simulate <- function(theta, n, B = 5000)
  replicate(B, { x <- runif(n, 0, theta); c(mom = 2 * mean(x), max = max(x), cor = (n + 1) / n * max(x)) })
set.seed(5)
sims <- simulate(theta = 5000, n = 20)
dim(sims)
round(apply(sims, 1, function(v) c(mean = mean(v), mse = mean((v - 5000)^2))), 1)
boxplot(t(sims), horizontal = TRUE, main = "Three estimators of a fleet of 5000")
abline(v = 5000, col = "red", lwd = 2)

What to look at:

  1. dim(sims): 3 rows and 5000 columns.
  2. The table has the estimators in columns: apply with a function that returns two numbers puts each result in a column.
  3. In Plots, the boxplot of t(sims) (transposed: one estimator per column, which is what boxplot wants): the maximum’s box sits entirely left of the red line.
  4. In Environment, open sims with View() and look at the first columns: each one is a sample.

Summary

  • Simulating an estimator is repeating the sampling: replicate with the sample inside the block, and a matrix with one estimator per row.
  • apply(sims, 1, f) summarises by estimator; the wrong margin gives as many results as simulations.
  • With the variance divided by B, MSE=Var+b2 \text{MSE} = \text{Var} + b^2 matches to the decimal: it serves as a check of the code.
  • Xˉ \bar X touches the Cramér–Rao bound in the Poisson for any n; S2 S^2 , though unbiased, stays seven or eight times above.
  • The exponential MLE has bias λ/(n−1) \lambda/(n-1) , which vanishes; it is consistent and, standardised with λ2/n \lambda^2/n , approaches an N(0, 1) as n grows.
  • The standard error of an MLE is −1/ℓ′′(θ^) \sqrt{-1/\ell''(\hat\theta)} , and optim(…, hessian = TRUE) gives it without differentiating by hand.

Checklist: have you practised it?

  • Have you run the three programs and checked the outputs?
  • Do you know what a row and what a column are in the replicate matrix?
  • Can you explain why the maximum’s histogram stops at 2400?
  • Do you know why the mean points sit on the bound and the S² ones do not?
  • Have you tried the “Try it yourself” items without looking at the theory?
  • Can you get the standard error of an MLE with optim?

If you said yes to almost all of them, you are ready for the properties of estimators exercises, where I no longer hand you the code. See you there!

Next step: exercisesProperties of estimators — exam-style exercises with the scooter fleet, the best-guessing maximum, the speedometer and Cramér–Rao (and the “more efficient” one that wasn’t)

Did this article help you? Here is how you can support SergioLearns →