Point estimation — exam-style exercises with the humidity, the lightning around the station and the pressure (and the var() that cost me half a point)
In the EC2 practice exam we did in class I was asked for the moments estimator of a gamma, I computed it with var() and lost half a point. My shape was 3.58; the right one, 3.77. I had matched the population variance to the sample variance, the one that divides by n − 1, when the method matches moments and the sample’s central moment divides by n. It was a one-line detail, in the first part, and since the parts of an exercise are chained, the mistake dragged into the next two. This article is so that it does not happen to you in the real one.
These are three chained exercises like those in the ME1 EC2 (one context per exercise and parts that need the previous one), with the weather station on the campus roof as the thread, plus a bonus. Before you start, it helps to have the theory, the proofs and the practice of point estimation.
Table of Contents
How to use this article
- Do the exercises with the exam in mind. In the ME1 EC2 you have 4 hours for 50 points, with RStudio and the data open. These three exercises add up to 40 points plus a 2.5-point bonus: give them about 3 hours.
- Paper for what is proved, R for what is computed. The derivations of the estimators, on paper; the estimates and checks, in R, with 2 decimals as the exam asks. Keep the code in a script: at the end you have to upload the
.Rfile with the code for each exercise. - Before differentiating, look at the support. If the interval where the variable lives depends on the parameter, do not differentiate: draw the likelihood.
- Mark with the criteria. Each solution comes with “How it is marked” and a breakdown of the points. It is a guide, mine: not the official criteria.
- Finish with the cheat sheet and “For your script”. The cheat sheet only has results (it is what you can take, handwritten: two sheets, both sides, in the EC2) and “For your script” is the topic’s code, ready for your
.Rfile. If a derivation gets stuck, the proofs have the step by step.
Exercise 1: midday humidity (10 points)
The station records the relative humidity at midday as a proportion between 0 and 1. On winter days, the model that suits it best has density
These are 12 middays:
humidity <- c(0.982, 0.708, 0.873, 0.976, 0.616, 0.610,
0.841, 0.854, 0.837, 0.861, 0.975, 0.934)
- (2 points) Given a simple random sample , obtain the method of moments estimator of θ, .
- (3 points) Obtain the maximum likelihood estimator, , and check that it is a maximum.
- (2 points) Compute the two estimates with the data and compare them.
- (2 points) Check with
optimthe value of from part 3. - (1 point) Give a maximum likelihood estimate of the probability that the midday humidity goes above 90 %.
Exercise 2: lightning around the station (15 points)
In a storm, the lightning strikes the station detects fall at random (uniformly) within a circle of radius θ km around it; θ, the detector’s range, is unknown. Let R be the distance from a strike to the station. These are the distances, in km, of 15 strikes:
strikes <- c(3.61, 7.22, 3.45, 2.87, 8.27, 5.76, 7.71, 8.50,
3.85, 8.57, 8.80, 7.75, 6.59, 8.79, 5.21)
- (2 points) Justify that the density of R is for .
- (2 points) Obtain the method of moments estimator of θ.
- (4 points) Obtain the maximum likelihood estimator of θ, giving the reasoning.
- (2 points) Compute the two estimates with the data and say which one you would use.
- (3 points) In R, simulate 10,000 storms of 15 strikes with θ = 9 and compute the mean of each estimator and the proportion of storms in which the moments one falls below the largest distance observed. Interpret the results.
- (2 points) Give maximum likelihood estimates of the area the detector watches and of the median distance of a strike.
Exercise 3: morning pressure (15 points)
The atmospheric pressure at 8:00 at the station, in hPa, is assumed normal . These are 15 mornings:
pressure <- c(1018.7, 1015.3, 1009.3, 1007.0, 1009.1, 1014.8, 1015.3, 1011.6,
1016.3, 1015.6, 1014.1, 1016.1, 1010.3, 1016.1, 1016.2)
- (4 points) With μ and σ unknown, obtain the maximum likelihood estimators of μ and σ².
- (3 points) Compute the estimates with the data. Does the one for σ² match
var(pressure)? Explain why. - (2 points) Obtain the estimates with
fitdistand interpret theStd. Errorcolumn. - (3 points) A pressure below 1010 hPa signals a low. Give a maximum likelihood estimate of the probability that a morning is below 1010 hPa and of the standard deviation σ. Justify the method.
- (3 points) Now assume μ = 1013 hPa is known. Obtain the MLE of σ² in this case and compute it with the data.
Bonus (2.5 points)
The strong gusts per hour are Poisson(λ) and, with n hours, the MLE is . Prove with the moment generating function that and, if the true λ were 3, compute in R the probability that with 24 hours comes out above 3.5.
Solutions
Exercise 1
Part 1. First, the population mean:
Setting it equal to : , and
Why go through instead of setting θ equal to the mean. The method of moments does not say “θ is the mean”: it says “the mean the model predicts has to equal the mean of the data”. That is why the first step is to work out as a function of θ, and only then set it equal and solve. The shortcut fails the check: with θ = 0.84 the model would predict a mean of , not 0.84.
Do not round before solving. With 0.84 you get ; with the full mean (0.8389…), 5.21. The 2 decimals go only on what you write at the end.
Part 2. . With :
Since the are between 0 and 1, their logs are negative, t < 0 and . Second derivative: for every θ: a maximum, and the only one.
Why the logarithm. Differentiating as it stands forces the product rule with a power whose exponent varies. The logarithm turns the product into a sum and does not move the maximum, because it is increasing: the θ that makes L largest makes largest. Notice too that the 12 data points only come in through one number, : before you open R you already know it is the only thing you need to compute.
Check you’ve got it: if t comes out as −2.25, why does 12/2.25 give 5.33 when R says 5.32?
Nobody is wrong: it is rounding. The unrounded sum of logs is −2.2546, and . Keep the full value in a variable (like theta_ml) and round only when you write it down.
Part 3.
n <- length(humidity)
theta_mm <- mean(humidity) / (1 - mean(humidity)) # moments
theta_ml <- -n / sum(log(humidity)) # maximum likelihood
round(c(mean = mean(humidity), sum_logs = sum(log(humidity)),
moments = theta_mm, ml = theta_ml), 2)
Output:
mean sum_logs moments ml
0.84 -2.25 5.21 5.32
and . They are close, but not the same: the methods give different estimators. A θ of 5 or more says the density piles up near 1: winter middays are humid.
Part 4.
loglik <- function(th) n * log(th) + (th - 1) * sum(log(humidity))
o <- optim(par = theta_mm, fn = loglik, method = "Brent", lower = 0.01, upper = 50,
control = list(fnscale = -1))
round(c(optim = o$par, formula = theta_ml, convergence = o$convergence), 2)
Output:
optim formula convergence
5.32 5.32 0.00
optim, starting at the moments one, reaches 5.32: the same value as the formula. convergence 0: it finished fine.
Why start at the moments estimate and use Brent. optim needs a starting point, and the best one you have is one that is already close: 5.21. With a single parameter, the default method (Nelder-Mead) warns that it is unreliable; Brent is the one for one dimension, but it needs an interval. The lower bound of 0.01 is not a whim: θ has to be positive and does not exist at 0.
Part 5. . By the invariance principle, its MLE is :
round(c(mle = 1 - 0.9^theta_ml, in_the_sample = mean(humidity > 0.9)), 2)
Output:
mle in_the_sample
0.43 0.33
43 % of middays above 90 % humidity. In the sample it was 4 of 12 (33 %): the model’s estimate does not have to match the proportion over 12 days.
In the picture, the log-likelihood from part 4: the top is at 5.32 (solid line) and the moments one (dashed) lands just to its left, where the curve barely drops. That is why they give such similar values.
How it is marked. Part 1: (1), solving (1). Part 2: likelihood and log (1), differentiate and solve (1), second derivative (1). Part 3: the two numbers (1 + 1). Part 4: optim with fnscale = -1 (1) and comment (1). Part 5: invariance (0.5) and number (0.5).
Exercise 2
Part 1. “Uniformly in the circle” means that the probability of falling in a region is proportional to its area. A strike falling less than r km away means falling inside the circle of radius r:
Differentiating: . It is increasing: there is more room far away than close by, so distant strikes are more frequent.
In the picture, the detector’s circle with the 15 strikes at their distance (the angle does not matter: they are spread out so you can see them). The outer ring has much more area than the inner circle of the same thickness: that is why the density grows with r.
Part 2.
Part 3. The support depends on θ: do not differentiate blindly. The likelihood is
(if θ were smaller than some , that strike would be impossible). For , L is proportional to , which is decreasing (its derivative, , is negative). So the maximum is at the smallest allowed θ:
Why you do not set the derivative to 0 here. If you do it blindly, and , which is never 0: there is no point with a horizontal tangent. That does not mean there is no maximum, but that it sits on an edge. The approach is to picture L in your head: it is 0 while θ is smaller than the farthest strike, jumps at 8.80 and from there only goes down. The highest point is the one at the jump.
Check you’ve got it: what is the likelihood at θ = 8.70 with these 15 strikes?
Zero. With a range of 8.70 km, the strikes at 8.80 and 8.79 km could not have been detected: their density is 0 and the whole product vanishes, however well the other 13 fit. That is why the MLE cannot go below the sample maximum.
Part 4.
round(c(moments = 1.5 * mean(strikes), ml = max(strikes)), 2)
Output:
moments ml
9.7 8.8
km and km. This time the moments one lands above the farthest strike (8.80), so it is possible. I would use the maximum likelihood one: it never leaves a data point out and, as we will see in part 5, the moments one sometimes does.
Part 5. To simulate a uniform strike in the circle: , with u uniform(0, 1).
Why the square root and not runif(15, 0, 9). The obvious way to get “15 random strikes up to 9 km” is to draw 15 uniform distances between 0 and 9. But what is uniform is the point in the circle, not the distance: as you saw in part 1, there is more room far away. With uniform distances the mean would be 4.5 km instead of km, and the simulation would be measuring a different model.
set.seed(9)
sim <- replicate(10000, {
r <- 9 * sqrt(runif(15)) # 15 strikes with theta = 9
c(ml = max(r), mm = 1.5 * mean(r))
})
round(c(mean_ml = mean(sim["ml", ]), mean_mm = mean(sim["mm", ]),
mm_impossible = mean(sim["mm", ] < sim["ml", ])), 3)
Output:
mean_ml mean_mm mm_impossible
8.710 9.000 0.345
- The mean of the MLE, 8.71, is below θ = 9: the maximum of 15 strikes can never exceed 9 and hardly ever reaches it. It tends to fall short.
- The mean of the moments one, 9.00, is right on θ: on average it hits.
- But in 34 % of storms the moments one falls below the farthest strike: it says the range is shorter than the distance of a strike the detector has seen. Neither is perfect: one falls short on average and the other is sometimes impossible. Which is “better” is the question for the next topic.
Part 6. The watched area is and the median m satisfies . By invariance, their MLEs are and :
round(c(area = pi * max(strikes)^2, median = max(strikes) / sqrt(2),
sample_median = median(strikes)), 2)
Output:
area median sample_median
243.28 6.22 7.22
About 243 km² watched and a median of 6.22 km: half the strikes fall less than 6.22 km away. The sample median (7.22) is larger: with 15 strikes and an increasing density, the sample has quite a few distant strikes.
How it is marked. Part 1: with areas (1), differentiate (1). Part 2: (1), solve (1). Part 3: likelihood with the condition (2), reasoning that it decreases (1), conclusion (1); differentiating and setting to 0 without reasoning about the support, 0. Part 4: the two numbers (1) and the choice (1). Part 5: correct simulation (1), the three numbers (1), interpretation (1). Part 6: invariance and the two values (1 + 1).
Exercise 3
Part 1. It is proof 5 of the topic. The log-likelihood:
Differentiating with respect to μ: . With respect to σ: , and substituting :
It is a maximum: and, at , at .
The approach with two parameters. Two unknowns, two equations: one partial derivative per parameter, and you solve the system. The order matters: in the equation for μ the disappears when you set it to 0, so μ is solved on its own and then substituted into the one for σ. Differentiating with respect to σ rather than σ² is for convenience: by invariance, the MLE of σ² is the square of the MLE of σ.
Part 2.
n <- length(pressure)
mu_ml <- mean(pressure)
s2_ml <- mean((pressure - mu_ml)^2) # divides by n
round(c(mu = mu_ml, sigma2_ml = s2_ml, var_R = var(pressure),
ratio = s2_ml / var(pressure), fourteen_fifteenths = (n - 1) / n), 4)
Output:
mu sigma2_ml var_R
1013.7200 10.7336 11.5003
ratio fourteen_fifteenths
0.9333 0.9333
hPa and hPa². var(pressure) gives 11.50: it does not match, because var() divides by n − 1 = 14 and the MLE by n = 15. The ratio, 0.9333, is exactly .
Part 3.
suppressMessages(library(fitdistrplus))
pressure <- c(1018.7, 1015.3, 1009.3, 1007.0, 1009.1, 1014.8, 1015.3, 1011.6,
1016.3, 1015.6, 1014.1, 1016.1, 1010.3, 1016.1, 1016.2)
fitdist(pressure, "norm")
Output:
Fitting of the distribution ' norm ' by maximum likelihood
Parameters:
estimate Std. Error
mean 1013.720000 0.8459157
sd 3.276217 0.5981525
fitdist gives and (the root of 10.73). The Std. Error column estimates the standard deviation of each estimator: that of , 0.85 hPa, is ; that of , 0.60 hPa. They tell you how much the estimates would change with another 15 mornings: the mean, less than 1 hPa up or down.
Part 4. , a function of (μ, σ). By the invariance principle, its MLE is obtained by plugging in the MLEs; and the MLE of σ is :
round(c(p_low = pnorm(1010, mu_ml, sqrt(s2_ml)), sigma_ml = sqrt(s2_ml),
in_the_sample = mean(pressure < 1010)), 4)
Output:
p_low sigma_ml in_the_sample
0.1281 3.2762 0.2000
12.8 % of mornings with low-pressure readings and hPa. In the sample, 3 of 15 (20 %).
Using sd(pressure) in pnorm. sd() is the root of the sample variance (divides by n − 1) and is not the MLE of σ; with it you would get 0.1363 instead of 0.1281.
Part 5. With μ = μ₀ = 1013 known, only σ is left. In the derivative with respect to σ there is nothing to substitute:
round(c(sigma2_mu_known = mean((pressure - 1013)^2), sigma2_mu_estimated = s2_ml), 4)
Output:
sigma2_mu_known sigma2_mu_estimated
11.2520 10.7336
11.25 hPa², somewhat larger than 10.73. It always happens: is smallest when (the parabola from descriptive statistics), so with any other center the sum is larger.
What changes when μ is known. There is no system any more: one parameter, one derivative. The typical mistake is to carry over the previous formula with inside; the center is the 1013 you are given, even if the data say something else. And the difference has an exact formula: .
Check you’ve got it: what if the known μ were 1013.72?
You would get 10.73, the same as with μ estimated: the known center would be exactly and the term would be 0.
How it is marked. Part 1: log-likelihood (1), the two derivatives (1 + 1), system and second derivative (1). Part 2: the numbers (2), explaining n against n − 1 (1). Part 3: fitdist (1), interpreting Std. Error (1). Part 4: invariance justified (1), probability (1), σ (1). Part 5: formula (2), number (1).
Bonus
The mgf of a Poisson(λ) is . Since the are independent, that of is the product:
which is the mgf of a Poisson(nλ). So . With n = 24 and λ = 3, , and :
c(p = 1 - ppois(84, 72)) # P(sum >= 85) = 1 - P(sum <= 84)
Output:
p 0.07318557
7.3 %. With a true λ = 3, 24 hours would give an estimate above 3.5 about 7 times in 100. So a day with the estimate above 3.5 is nothing odd even if λ is still 3.
Why 84 in ppois and not 85. The approach is to turn the question about into one about the sum, which is the one with a known distribution. The sum is a whole number, so “greater than 84” means “85 or more”, and since ppois gives , the complement of is . With 1 - ppois(85, 72) you would get 0.06 (you lose the 85) and with 1 - ppois(83, 72), 0.09 (you count the 84, which leaves at exactly 3.5, not above it).
How it is marked. The mgf and the product (1), recognising the Poisson (0.5), going from to the sum (0.5) and the number (0.5).
What’s wrong here?
Three solutions by other people. Before reading the explanation, predict what goes wrong.
Fragment 1. Moments estimator of the rain gamma:
rain <- c(5.0, 8.8, 6.8, 6.1, 0.8, 8.7, 3.7, 10.0, 7.4, 1.6,
7.1, 1.3, 7.5, 6.6, 12.0, 4.0, 7.2, 12.2, 14.8, 6.6)
c(shape = mean(rain)^2 / var(rain), rate = mean(rain) / var(rain))
Output:
shape rate 3.5793461 0.5179951
var() divides by n − 1: it is the sample variance , not the central moment . The shape comes out 3.58 and the rate 0.52, instead of 3.77 and 0.55. It is my half point from the practice exam.
In the method of moments, the sample variance divides by n. With 20 data points the error is 5 %; with 10, 10 %.
Define s2p <- function(x) mean((x - mean(x))^2) once at the top of the script and always use it in moments and in the MLE of σ².
Fragment 2. Checking the humidity MLE with optim:
humidity <- c(0.982, 0.708, 0.873, 0.976, 0.616, 0.610,
0.841, 0.854, 0.837, 0.861, 0.975, 0.934)
loglik <- function(th) 12 * log(th) + (th - 1) * sum(log(humidity))
optim(par = 5, fn = loglik, method = "Brent", lower = 0.01, upper = 50)$par
Output:
[1] 50
Without control = list(fnscale = -1), optim minimises. The log-likelihood goes down the further θ moves from 5.32 on either side, so its minimum inside the interval is at an edge: here, 50 (with a large θ, the term , negative, drags it down). And it warns of nothing: convergence comes out 0, because it has found (correctly) a minimum.
Trusting an optim that returns exactly a limit (lower or upper). It is almost always a forgotten fnscale or an interval that does not contain the maximum.
Fragment 3. MLE of α of the wind Rayleigh:
wind <- c(7.9, 12.2, 11.5, 11.8, 7.0, 11.7, 4.6, 20.3, 9.4, 10.6,
12.9, 3.1, 9.2, 27.3, 12.3, 5.5, 14.2, 14.2, 7.4, 21.1,
14.6, 6.4, 25.4, 8.2, 14.8, 4.1, 7.1, 18.0, 5.6, 16.4,
13.1, 19.7, 12.1, 11.0, 9.1, 20.8, 21.7, 18.6, 1.2, 4.5)
sum(wind)^2 / (2 * length(wind))
Output:
[1] 2959.745
is not . The bracket is in the wrong place: sum(wind)^2 squares the sum (486.6), giving α = 2959.75 instead of 93.14. A Rayleigh with α ≈ 3000 would have its most frequent wind at 54 km/h.
Check the order of magnitude. is the mode of the Rayleigh: it has to be inside the range of the data. km/h is outside.
Practice quiz
Before moving on to the next topic, check you have got it. This quiz is here to consolidate what this article explains: the ME1 exam is not a multiple-choice test (you solve problems by hand and with R), so no mark here counts. There are 10 questions on point estimation: key ideas, typical mistakes and many «what does this R code print?», with the outputs from really running it. In the short answers, a decimal point or a decimal comma both work. Answer without running anything, press Check and read the explanation for each option; you can repeat it as many times as you like.
In the method of moments for a gamma, a classmate uses var(rain) as the sample variance. What is wrong?
- var() divides by n − 1 (the quasi-variance S²) and the method of moments uses the central moment S’², which divides by n
- Nothing: var() is the sample variance
- They should use sd()
- The method of moments uses only the mean, not the variance
Solution
Answer: var() divides by n − 1 (the quasi-variance S²) and the method of moments uses the central moment S’², which divides by n
Define s2p <- function(x) mean((x - mean(x))^2) once at the top of the script and always use it for moments and for the MLE of σ². S’² = (n − 1)/n · S².
To check an MLE, the log-likelihood is maximised with optim(par = 5, fn = loglik, method = "Brent", lower = 0.01, upper = 50) and it returns exactly 50. What happened?
- optim minimises by default:
control = list(fnscale = -1)is missing to make it maximise - The MLE is 50
- The Brent method does not work for one parameter
- You have to start at par = 50
Solution
Answer: optim minimises by default: control = list(fnscale = -1) is missing to make it maximise
Trusting an optim that returns exactly a limit is the mistake. It is almost always a forgotten fnscale or an interval that does not contain the maximum.
The MLE of α for a Rayleigh is Σx²/(2n). A classmate writes sum(wind)^2 / (2 * length(wind)) and gets 2959.75. What is wrong?
- (Σx)² is not Σx²: the bracket is in the wrong place; the right one is
sum(wind^2) / (2 * length(wind)), which gives 93.14 - It should divide by n − 1
- You have to take the root at the end
- Nothing: the wind can be that strong
Solution
Answer: (Σx)² is not Σx²: the bracket is in the wrong place; the right one is sum(wind^2) / (2 * length(wind)), which gives 93.14
Check the order of magnitude: √α̂ is the Rayleigh’s mode and must lie inside the data’s range.
What does it print? (It is S’², the central moment, with 2 decimals.)
x <- c(2, 4, 6, 8) round(mean((x - mean(x))^2), 2)
Solution
Answer: 5
Mean 5; squared deviations 9 + 1 + 1 + 9 = 20; divided by n = 4, S’² = 5. var(x) would give 20/3 = 6.67.
Put in order the steps of the maximum likelihood estimator (support not depending on θ):
- Solve for θ
- Differentiate and set to zero: ℓ'(θ) = 0
- Check that ℓ”(θ) < 0 (it is a maximum)
- Write the likelihood L(θ) = Π f(x_i | θ)
- Take logs: ℓ(θ) = log L(θ)
Solution
Correct order:
- Write the likelihood L(θ) = Π f(x_i | θ)
- Take logs: ℓ(θ) = log L(θ)
- Differentiate and set to zero: ℓ'(θ) = 0
- Solve for θ
- Check that ℓ”(θ) < 0 (it is a maximum)
If the support depends on θ (for example, a uniform on (0, θ)), you do not differentiate: the MLE is an extreme of the sample and you reason about the boundary.
X ~ uniform(0, θ). What is the MLE of θ?
- The sample maximum
- Twice the mean
- The mean
- It is obtained by differentiating ℓ(θ) and setting it to 0
Solution
Answer: The sample maximum
It is the cheat sheet’s rule: if the support depends on θ, the MLE is an extreme of the sample.
The MLE of λ in a Poisson is the sample mean. With the data 3, 5, 2, 6, 4, what is the MLE of P(X = 0) = e^(−λ)? (4 decimals.)
x <- c(3, 5, 2, 6, 4) round(exp(-mean(x)), 4)
Solution
Answer: 0.0183
By the MLE’s invariance: the MLE of τ(λ) is τ(λ̂). λ̂ = 20/5 = 4, so e^(−4) = 0.0183.
Match each concept with its definition:
| Method of moments | |
| Maximum likelihood | |
| MLE invariance | |
| Estimator |
Definitions:
- Choose the θ that makes the observed sample most likely
- The formula with the X_i
- Set E(X^k) equal to the sample's k-th moment and solve
- The MLE of τ(θ) is τ(θ̂)
- The number obtained with the actual data
Solution
- Method of moments → Set E(X^k) equal to the sample’s k-th moment and solve
- Maximum likelihood → Choose the θ that makes the observed sample most likely
- MLE invariance → The MLE of τ(θ) is τ(θ̂)
- Estimator → The formula with the X_i
The number obtained with the data is the estimate. If you are asked for both, give the formula with X_i and then the number.
True or false?
- S’² = (n − 1)/n · S².
- In the method of moments with two parameters, the mean and the quasi-variance S² are matched.
- In a Rayleigh, E(X²) = 2α.
- The sum of n independent Poisson(λ) is Poisson(nλ).
Solution
- T — S’² = (n − 1)/n · S².
- F — In the method of moments with two parameters, the mean and the quasi-variance S² are matched.
- T — In a Rayleigh, E(X²) = 2α.
- T — The sum of n independent Poisson(λ) is Poisson(nλ).
With two parameters you match the mean and the central moment S’² (divided by n), not var().
Data from a Rayleigh: 2, 4 and 4. What is the MLE of α = Σx²/(2n)?
x <- c(2, 4, 4) sum(x^2) / (2 * length(x))
Solution
Answer: 6
Σx² = 4 + 16 + 16 = 36; 2n = 6; α̂ = 36/6 = 6. Check: √6 = 2.45 lies inside the data’s range, as the mode should.
Try it in the R playground
Open the R playground on the site (or RStudio) and paste this script, which solves the whole of exercise 2 and draws the lightning likelihood:
strikes <- c(3.61, 7.22, 3.45, 2.87, 8.27, 5.76, 7.71, 8.50,
3.85, 8.57, 8.80, 7.75, 6.59, 8.79, 5.21)
n <- length(strikes)
L <- function(th) ifelse(th >= max(strikes), 2^n * prod(strikes) / th^(2 * n), 0)
curve(L, 8, 12, n = 1001, xlab = "theta", ylab = "L(theta)")
abline(v = c(max(strikes), 1.5 * mean(strikes)), lty = c(1, 2))
c(ml = max(strikes), moments = 1.5 * mean(strikes))
Things to look at:
- In Plots, the likelihood: 0 up to 8.80, a jump and then a drop. The maximum is the jump.
- The dashed line, the moments one (9.70), is on the falling part: its likelihood is much lower than the maximum’s.
n = 1001incurve: with the default 101 points, the jump is drawn as a ramp.- Copy the simulation from part 5 below it and change the 9 in
9 * sqrt(runif(15))to another range: does the percentage of impossible estimators change?
Cheat sheet: point estimation
The essentials in 30 seconds. Moments: and solve (with two parameters, mean and ). Maximum likelihood: , , , . If the support depends on θ, the MLE is an extreme of the sample. Invariance: MLE of = .
| Distribution | Moments | Maximum likelihood |
|---|---|---|
| Bernoulli(p) | ||
| binom(N, p), N known | ||
| geom(p), failures before success | ||
| Poisson(λ) | ||
| exp(λ) | ||
| normal(μ, σ) | , | , ; with μ₀: |
| gamma(α, β) | , | optim or fitdist; |
| uniform(0, θ) | ||
| uniform(a, b) | , | |
| Rayleigh(α) | ||
| on (0, 1) | ||
| on (0, θ) |
Useful results. . Rayleigh: , , , . Poisson: .
| I want… | Code | Result |
|---|---|---|
mean((x - mean(x))^2) | Variance over n | |
| Maximise one parameter | optimize(f, c(a, b), maximum = TRUE) | $maximum, $objective |
| Maximise several | optim(start, f, x = data, control = list(fnscale = -1)) | $par, $value, $convergence |
One parameter with optim | method = "Brent", lower = a, upper = b | No Nelder-Mead warning |
| Positive parameters | method = "L-BFGS-B", lower = c(0.01, 0.01) | Never tries impossible values |
| MLE with standard errors | fitdist(x, "gamma") (package fitdistrplus) | estimate, Std. Error, loglik |
| Moments with fitdist | fitdist(x, "gamma", method = "mme") | The moments ones |
| Draw a log-likelihood | curve(Vectorize(l)(x), a, b) | The hill |
| Symptom | Likely cause |
|---|---|
optim returns exactly lower or upper | fnscale = -1 missing or the interval does not contain the maximum |
| The likelihood is 0 for every θ | Written with prod() and lots of data: use sum(log()) |
curve draws a straight line or gives a length error | The function does sum(): Vectorize |
| Moments off by 5-10 % | var() instead of |
| Moments estimator below the largest data point | Happens in the uniform and similar: use the MLE |
dgamma with NaN and warnings in optim | Negative parameters: L-BFGS-B with lower |
Before you hand in, ask yourself:
- Have I written the estimator with (formula) and the estimate with the data (number), if both are asked for?
- Have I checked the second derivative or, if the support depends on θ, reasoned about the edge?
- Have I used (over n) where it belongs and not
var()? - Does my
optimhavefnscale = -1and isconvergence0?
For your script
The topic’s code for your exam .R file, with functions tested in this article’s exercises. No statements: only what gets reused.
# ===== Point estimation (ME1, topic 9) =====
s2p <- function(x) mean((x - mean(x))^2) # S'^2 (divides by n)
# --- Moments: closed formulas
mme_poisson <- function(x) mean(x)
mme_exp <- function(x) 1 / mean(x)
mme_gamma <- function(x) c(shape = mean(x)^2 / s2p(x), rate = mean(x) / s2p(x))
mme_unif_ab <- function(x) c(a = mean(x) - sqrt(3 * s2p(x)), b = mean(x) + sqrt(3 * s2p(x)))
mme_rayleigh <- function(x) 2 * mean(x)^2 / pi
# --- Maximum likelihood: closed formulas
mle_bernoulli <- function(x) mean(x)
mle_poisson <- function(x) mean(x)
mle_exp <- function(x) 1 / mean(x)
mle_normal <- function(x) c(mu = mean(x), sigma2 = s2p(x))
mle_unif <- function(x) max(x) # uniform(0, theta)
mle_rayleigh <- function(x) sum(x^2) / (2 * length(x))
drayleigh <- function(x, alpha) x / alpha * exp(-x^2 / (2 * alpha))
# --- Numerical maximum likelihood
# One parameter: the log-likelihood as a function of theta (data inside)
mle_1par <- function(loglik, a, b) optimize(loglik, c(a, b), maximum = TRUE)$maximum
# Several parameters: loglik(par, x) with par a vector; start = moments estimator
mle_optim <- function(loglik, start, x, low = rep(0.01, length(start))) {
o <- optim(start, loglik, x = x, method = "L-BFGS-B", lower = low,
control = list(fnscale = -1))
if (o$convergence != 0) warning("optim has not converged")
o
}
loglik_gamma <- function(par, x) sum(dgamma(x, shape = par[1], rate = par[2], log = TRUE))
loglik_norm <- function(par, x) sum(dnorm(x, mean = par[1], sd = par[2], log = TRUE))
# Example: mle_optim(loglik_gamma, mme_gamma(rain), rain)$par
# --- With fitdistrplus (installed before the exam)
# library(fitdistrplus)
# fitdist(x, "gamma"); fitdist(x, "norm"); fitdist(x, "exp")
# fitdist(x, "gamma", method = "mme") # moments
# --- Draw a one-parameter log-likelihood
draw_loglik <- function(loglik, a, b, mark = NULL) {
curve(Vectorize(loglik)(x), a, b, xlab = "parameter", ylab = "log-likelihood")
if (!is.null(mark)) abline(v = mark, lty = 2)
}
# --- Invariance: plug the MLE into the formula, for example
# P(X > c) in the Rayleigh: exp(-c^2 / (2 * mle_rayleigh(x)))
# P(X < c) in the normal: pnorm(c, mean(x), sqrt(s2p(x)))
What comes next?
With this topic you can get an estimator in two ways. But exercise 2 left a question hanging: the maximum likelihood one fell short on average (8.71 against 9) and the moments one was sometimes impossible. Which is better? The next ME1 topic, properties of estimators, gives the criteria: unbiasedness (right on average), efficiency (the smallest possible variance, with the Cramér-Rao bound) and consistency (getting closer to the parameter as n grows). What you computed here, the distribution of the Rayleigh MLE with its mean and variance, is exactly what you will need.
If you want to review first, you have the theory, the proofs and the practice of this topic, and sampling distributions, where and come from.
Keep goingAll Statistics articlesDid this article help you? Here is how you can support SergioLearns →
Ready for the exam?ME1 EC2 mock exam — 4 hours with R beside you, from the normal to confidence intervals, four versions and a mark out of 50 (and why exercise 1 is worth double)


