Point estimation — theory with the campus weather station, the method of moments and maximum likelihood (and the α I mistook for the mean wind speed)
The first day I downloaded the data from the weather station on the roof, I drew a Rayleigh over the wind histogram setting α equal to the mean. The curve came out squashed to the left, peaking at 3.5 km/h, while the histogram had its hump at 12. I had written alpha <- mean(wind), which gives 12.165, and I had assumed that the parameter of a distribution “is its mean”. In the normal it almost is (μ is the mean); in the Poisson too (λ is the mean); in the Rayleigh it is not: its mean is , and if you want it to be 12.165, α has to be about 94. That day I learnt the question of this topic: with the data in front of you, what value do you give the parameter?
Until now, in every topic, we were given the distribution with its parameters (, …) and we computed probabilities. In real life it is the other way round: you have the data and you do not know the parameter. Today we look at the two classic methods for getting it out of the sample: the method of moments (set the population mean equal to the sample mean) and maximum likelihood (pick the parameter that makes the data you have seen most likely). We carry on from sampling distributions: there and were statistics with their distribution; here they become estimators. The full derivations, step by step, are in the point estimation proofs.
Table of Contents
Before you start. For this topic you need three things you already have: the distributions from earlier topics (Bernoulli, Poisson, gamma, uniform) with their mean and variance; the idea from the previous topic that is a random variable, because it changes with the sample; and knowing how to differentiate a logarithm () with the chain rule. Nothing else. The topic goes in this order: first, three words that need to be kept apart (parameter, estimator, estimate); then the method of moments, which is setting the model’s mean equal to the data’s mean and solving; then the likelihood, which measures how likely it was to see your data with each value of the parameter; and finally, how to find its maximum with logs and derivatives, and what to do when you cannot (the uniform and the gamma). All with the same data: the rooftop station. If you get lost, go back to the 9 rainy days out of 30: with them you can understand the whole topic.
The rooftop station
The example for the whole topic is the weather station on the roof of the Tafira campus. It records many things, and we will use five series (made up, but shaped like the real ones):
- Wind: 40 readings of the mean wind speed (10-minute average), in km/h. The classic model for wind is the Rayleigh, with density for and a parameter .
- Gusts: how many gusts above 40 km/h there were in each of 24 hours. A count: Poisson(λ).
- Rain or not: 30 days in December, 1 if it rained and 0 if not. Bernoulli(p).
- Rain: the litres per square metre (mm) on 20 rainy days. Positive and skewed right: gamma(α, β).
- Delay: how long the station takes to upload each reading to the server, in seconds. The manufacturer says it is “between 0 and a maximum”: uniform(0, θ).
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) # km/h
gusts <- c(2, 6, 4, 4, 9, 4, 4, 1, 3, 3, 1, 4,
1, 1, 3, 2, 2, 3, 4, 3, 1, 4, 6, 2) # per hour
rains <- c(0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1,
0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1) # 30 days
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) # mm
delay <- c(1.34, 1.18, 2.95, 3.36, 3.51, 1.17, 3.42, 3.74,
1.62, 0.91, 0.05, 1.01, 3.35, 0.52, 1.37) # seconds
sapply(list(wind = wind, gusts = gusts, rains = rains,
rain = rain, delay = delay),
function(x) round(c(n = length(x), mean = mean(x)), 2))
Output:
wind gusts rains rain delay n 40.00 24.00 30.0 20.00 15.00 mean 12.16 3.21 0.3 6.91 1.97
Each column is a series: how many data points it has and its mean. Notice two things that will keep coming up: the mean wind speed is 12.165 km/h (R rounds it to 12.16), and the mean of rains is 0.3, the proportion of rainy days (9 out of 30). In all five cases we know the family of the distribution (Rayleigh, Poisson, Bernoulli, gamma, uniform), but not the parameter. That is parametric estimation: the shape is assumed; the number comes from the data.
Parameter, estimator and estimate
Three words that look the same and are not:
- The parameter θ is a fixed number of the population that you do not know: the α of the Rayleigh of the Tafira wind. It does not change if you change sample.
- An estimator is a formula, a function of the sample: “the sum of squares over 2n”. Because it depends on the sample, it is a random variable (what we saw in the previous topic: it has its sampling distribution).
- An estimate is the number that formula gives with your actual data: 93.14.
In the picture: the parameter lives in the population and cannot be seen; the sample goes through the formula (the estimator) and out comes a number (the estimate). With another sample of 40 readings you would get another number, 89 or 101, but the formula would be the same. In the exam they ask for both: “obtain the estimator” wants a formula with capital ; “give an estimate with these data” wants a number.
Loosely, the notes and the exam say “maximum likelihood estimator” both for the formula and for the number. If you are asked for “the MLE of α”, give the formula; if they add “for these data”, give the number too.
One formula, two samples of wind
The difference between estimator and estimate shows up in an experiment you can do with the 40 wind readings. Split them in two: the first 20, as if they were one afternoon, and the last 20, as if they were another. Apply the same formula to both, the maximum likelihood one that comes further down, :
| What you look at | The first 20 | The last 20 | What it is |
|---|---|---|---|
| Formula | the estimator: it does not change | ||
| Sum of squares | 3393.34 | 4058.20 | depends on which 20 readings you got |
| Result | 84.83 | 101.46 | the estimate: it changes with the sample |
| True α | ? | ? | the parameter: the same in both columns, and you cannot see it |
Look at the last row. The α of the Tafira wind is a single number; both afternoons are estimating it at the same time and they give different numbers. Neither is “wrong”: that is what always happens when you estimate from a sample. If you put the 40 readings together, the same formula (now over ) gives 93.14, between the two. That is why an estimator is a random variable: before you take the sample you do not know what number it will give, just as you did not know what mean would come out in the previous topic.
Check you’ve got it: in “the mean wind is 12.165”, what is the parameter, what is the estimator and what is the estimate?
The estimator is , the formula “add up the readings and divide by n”, written in capitals because it works for any sample. The estimate is 12.165, the number that formula gives with these 40 readings (with the first 20 it would give 11.71; with the last 20, 12.62). The parameter would be the true mean of the wind on the roof, , which you do not know. It is not 12.165: with another 40 readings you would get another number, and the true mean would still be the same.
The sample moments
The method of moments rests on something you already know from descriptive statistics: moments. The population moment of order k is ; the sample one, . And the central ones, around the mean:
| Population | Sample |
|---|---|
| , the mean | , the sample mean |
Careful with the last row: the second central moment of the sample divides by n, not by n − 1. We write it (with a prime) so as not to confuse it with the sample variance of the previous topic, the one var() computes. You go from one to the other with
Using var(x) as . var() divides by n − 1. For the method of moments you need (n - 1) / n * var(x) or, directly, mean((x - mean(x))^2). With 20 rain values the difference is 5 %, and in the exam it changes the second decimal.
The method of moments
The idea is very simple: if the data come from an , choose the θ that makes the population mean equal to the sample mean. With two parameters one equation is not enough: you also match the second moment (or the variance). With k parameters, k equations:
The method of moments estimator is the solution of that system. We will write it with a tilde, , to tell it apart from the maximum likelihood one, .
One parameter: gusts and wind
In the Poisson, . Set it equal to the sample mean and you are done: .
In the Rayleigh it takes a bit more work, because the mean is not α: it is (the integral, with a change that turns it into a gamma, is in proof 1). Set them equal and solve:
The picture shows the idea: on the left, what the population says (the mean of a Rayleigh is ); on the right, what the data say (12.165); in the middle, the equals sign. Solving for α is all that is left.
The wind, step by step
The calculation above is three arrows. Slowly, and with the wind numbers:
| Step | What you do | Result | Why |
|---|---|---|---|
| 1 | Count the parameters | one, α | one parameter, one unknown: a single equation is enough, the one for the mean |
| 2 | Write the population mean as a function of α | it comes from the integral in proof 1; it is what the model “says” | |
| 3 | Compute the sample mean | it is what the data say: the sum of the 40 readings over 40 | |
| 4 | Set them equal | the whole method is this equals sign | |
| 5 | Square both sides | to get rid of the root; both sides are positive, so nothing is lost | |
| 6 | Multiply by 2 and divide by π | solving for α is all that is left |
Look at step 2: it is the only one where you need to know something about the distribution. If the model’s mean is the parameter itself (Poisson, Bernoulli), steps 5 and 6 disappear and the estimator is as it is. If it is a function of the parameter, as here, you have to solve for it, and that is where anyone who writes alpha <- mean(wind) goes wrong, as I did on the first day.
Check the result by going the other way: with α = 94.21, the mean of the Rayleigh is , the data’s mean. If undoing the calculation does not give you , you made a mistake when solving.
Two parameters: the rain
The gamma(α, β) has two parameters, so you need two equations. The handy ones are the mean and the variance: and . Setting them equal to and :
Divide the first by the second: . And substitute in the first: .
With the rain numbers, before the code, so you can see where each one comes from:
| Step | Calculation | Result | Why |
|---|---|---|---|
| 1 | 6.91 mm | the first sample moment | |
| 2 | 12.67 | the second central moment: over 20, not over 19 | |
| 3 | 0.55 | dividing the two equations, α goes away and only β is left | |
| 4 | 3.77 | you substitute β into the first equation, |
Why divide? Because both equations have α on top and they only differ in the power of β. When you divide them, α cancels and β is left on its own in one go. It is the trick behind almost every two-parameter method-of-moments system: look for the operation that leaves a single unknown.
Pairing the moments wrongly: setting equal to the sample variance, or equal to . The two good pairs are with (60.42 with the rain) and with (12.67). They give the same estimator, because .
Check you’ve got it: if you use var(rain) instead of S’², what shape and rate do you get?
var(rain) divides by 19 and gives 13.34 instead of 12.67. With that number, the rate would be and the shape , instead of 0.55 and 3.77. The shape already changes in the first decimal. It is not a method-of-moments estimator: the method’s second equation asks for the sample’s central moment, which divides by n.
n <- length(rain)
s2prime <- (n - 1) / n * var(rain) # central moment of order 2: divides by n
lambda_mm <- mean(gusts) # Poisson: E(X) = lambda
alpha_mm <- 2 * mean(wind)^2 / pi # Rayleigh: E(X) = sqrt(alpha * pi / 2)
a_mm <- mean(rain)^2 / s2prime # gamma: shape
b_mm <- mean(rain) / s2prime # gamma: rate
round(c(lambda = lambda_mm, alpha = alpha_mm, s2prime = s2prime,
shape = a_mm, rate = b_mm), 2)
Output:
lambda alpha s2prime shape rate 3.21 94.21 12.67 3.77 0.55
How to read it
lambda 3.21: we estimate that there are, on average, 3.21 strong gusts per hour. It is the mean of the 24 counts.alpha 94.21: the parameter of the wind’s Rayleigh. It is not in units of speed: it is in speed squared (km²/h²). Its root, 9.71 km/h, is the most frequent wind speed (the mode of the Rayleigh is ).s2prime 12.67: the variance of the rain dividing by 20.var(rain)would give 13.34.shape 3.77andrate 0.55: the gamma of the rain by moments. Its mean, mm, is exactly : that is what the method is built for.
The moments estimator is not unique
In the Poisson we also know that . If instead of the mean I match the variance, , I get another method of moments estimator, , which with the gusts gives 3.50 instead of 3.21. Both are “moments” estimators. In practice you choose the simplest (the mean one), and in the next topic we will see the criterion for deciding which is better. For now keep this: the method of moments does not give a single estimator; it depends on which moments you match.
The likelihood function
The second method is Fisher’s (1922) and has a very appealing idea: of all the possible values of the parameter, keep the one that makes the data you have seen most likely.
Before writing any formula, let’s build it with very little data. Keep only the first three days of December: dry, rain, dry (0, 1, 0). If the probability of rain were p, how likely is it to see exactly that?
- The first day is dry: that happens with probability .
- On the second it rains: probability .
- The third, dry again: .
- The days are independent, so the probability of all three together is the product: .
Now we give p some values, like trying out candidates:
| p | What it says | |
|---|---|---|
| 0.1 | with so little rain, rain on one day out of three is odd | |
| 0.3 | quite a bit better | |
| 1/3 | the best of all: it is the proportion of rainy days in this sample | |
| 0.6 | too much rain to see two dry days out of three |
What you have just done is the whole method. The data (0, 1, 0) do not move; what changes is p, and for each p you work out how likely it was to see your data. The p that gives the highest number is the maximum likelihood estimate. Now, the same with the whole month.
Check you’ve got it: with the first five days (0, 1, 0, 0, 0), what function of p comes out and which p makes it largest?
One rainy day and four dry ones, independent: . Trying candidates: with 0.1 you get 0.0656; with 0.2, 0.0819; with 0.3, 0.0720. The maximum is at p = 0.2, which is 1/5, the proportion of rainy days among those five. It is the same pattern as with three days (1/3): the likelihood of a Bernoulli always has its maximum at the sample proportion.
Think of the 30 days in December: 9 rainy and 21 dry. If p (the probability of rain) were 0.1, seeing 9 rainy days would be odd. If it were 0.6, too: you would expect about 18. With p = 0.3, seeing 9 out of 30 is what you would expect. The function that measures “how likely my sample is if the parameter is θ” is the likelihood:
The product comes from the independence of the sample (a simple random sample): the probability, or density, of all of them happening together is the product. Three things to be clear about:
- The data are fixed and θ is the variable. It is the same formula as the joint density, but you look at it as a function of the parameter.
- In the discrete case it is a real probability (that of seeing exactly your sample); in the continuous case it is a product of densities, which is not a probability, but compares just as well.
- It does not add up to 1 and does not have to: it is not a distribution of θ.
With the rain: each day is , and multiplying the 30 the exponents add up: , where 9 is the sum of the data.
L <- function(p) p^9 * (1 - p)^21 # likelihood of the 30 days L(c(0.1, 0.3, 0.6)) # three candidates curve(L, 0, 1, xlab = "p", ylab = "L(p)") # the whole curve
Output:
[1] 1.094190e-10 1.099386e-08 4.432218e-11
How to read it
- The three numbers are the probability of that particular sequence of 30 days (not “9 out of 30” in any order) for p = 0.1, 0.3 and 0.6. They are tiny because any particular sequence of 30 days is always unlikely; what matters is comparing them: with p = 0.3 the sample is about 100 times more likely than with p = 0.1 and about 250 times more than with p = 0.6.
- The picture is what
curvedraws: a hump with its maximum at p = 0.3. That is the maximum likelihood estimate of p with these data. - Look at the vertical axis: it reaches . With 1000 days the numbers would be so small that the computer would round them to 0. That is why we work with the logarithm.
The maximum likelihood estimator
The maximum likelihood estimate is the value that maximises ; the maximum likelihood estimator (MLE) is the formula that gives that value for each sample:
The procedure, in four steps
- Write the likelihood: .
- Take logs: . The product becomes a sum, much easier to differentiate.
- Differentiate and set to 0: . The solution is .
- Check that it is a maximum: .
Why can you maximise the log instead of L? Because the log is increasing: if , then too. It changes the height of the curve, but not where the maximum is.
In the picture, the wind likelihood and its logarithm, one above the other. The top curve is a very tall, narrow spike; the bottom one, a gentle hill. Both peak at the same α: 93.14.
Log and derivative, step by step with the rain
The four steps above fit in four lines, but each one hides a rule. With the likelihood of the 30 days, :
| Step | Result | Why |
|---|---|---|
| Logarithm | the log of a product is the sum of the logs, and the log of a power brings the exponent down in front: | |
| Derivative | the derivative of is ; that of is : the minus comes from the chain rule, because the inside, , has derivative −1 | |
| Set to 0 | at the top of the hill the slope is 0: it neither rises nor falls | |
| Solve | cross-multiply and gather the p terms on one side | |
| Second derivative | both terms are negative for any p, so : it is a maximum |
Three things the table shows that hold for every example in the topic:
- Without the logarithm, you would have to differentiate with the product rule and the chain rule at the same time. It can be done, but you get a long expression that you then have to factorise to set it to 0. With the logarithm, each factor becomes a term and is differentiated on its own.
- The slope tells you where the maximum is. At p = 0.1, : the hill is rising and the maximum is to the right. At p = 0.6, : it is falling, and the maximum is to the left. Only at 0.3 is it zero.
- The logarithm also fixes the numbers. was ; on the other hand, , a number you can handle with no trouble (it is the natural logarithm, R’s
log).
Check you’ve got it: the 24 hours of gusts add up to 77; what is the MLE of λ and what happens to the factorial term when you differentiate?
The Poisson log-likelihood is . The last term has no λ: it is a fixed number, and its derivative is 0. It is in , but it disappears when you differentiate. That leaves ; setting it to 0, , the mean of the gusts. The second derivative, , is negative: it is a maximum.
The station’s three, with the derivative
The full working is in proofs 3 and 4; here, the result and one line of the idea.
- Rain or not (Bernoulli). , with s the number of rainy days. Differentiating, , giving : the proportion of rainy days.
- Gusts (Poisson). . Differentiating, : . The same as by moments.
- Wind (Rayleigh). . Differentiating, :
Different from the moments one, . The two methods do not have to agree.
The Rayleigh, without skipping anything
The wind line is the one that trips people up most, because α appears in two places in the density. Step by step:
| Step | Result | Why |
|---|---|---|
| Log of one density | , and the log undoes the exponential: | |
| Add up the 40 | is the same for all 40 readings, so it appears n times; is common and comes out of the sum | |
| Differentiate with respect to α | has no α: derivative 0. That of is . And has derivative , which with the minus in front gives a plus | |
| Set to 0 and multiply by | is positive: it clears the denominators without changing the solution | |
| Solve | with the data: the sum of the squares of the 40 readings, over 80 | |
| Second derivative | , and at we have : it becomes |
Differentiating with respect to x instead of α. In the likelihood the data are fixed numbers (the 40 readings) and the variable is α. If a shows up when you differentiate, you have differentiated with respect to the data. You can cross out the term from the start (it has no α), but do not confuse it with , which does.
p_ml <- mean(rains) # Bernoulli: s / n lambda_ml <- mean(gusts) # Poisson: the mean alpha_ml <- sum(wind^2) / (2 * length(wind)) # Rayleigh round(c(p = p_ml, lambda = lambda_ml, alpha_ml = alpha_ml, alpha_mm = alpha_mm), 2)
Output:
p lambda alpha_ml alpha_mm
0.30 3.21 93.14 94.21
How to read it
p 0.3: we estimate that in December it rains on 30 % of the days on campus.lambda 3.21: the same as by moments, 3.21 gusts per hour.alpha_ml 93.14againstalpha_mm 94.21: the two methods almost agree for the wind. It does not always happen; with the rain (further down) they split a lot.
Does the Rayleigh fit the wind? Checked as in every topic: density-scale histogram with the curve on top.
drayleigh <- function(x, alpha) x / alpha * exp(-x^2 / (2 * alpha)) # R does not have it
hist(wind, freq = FALSE, breaks = seq(0, 30, by = 3),
main = "Wind on the roof", xlab = "km/h")
curve(drayleigh(x, alpha_ml), add = TRUE, lwd = 2)
In the picture, the histogram of the 40 readings and the Rayleigh with . The curve rises fast, peaks at km/h and falls with a long tail to the right, like the histogram. The tallest bar (12-15 km/h) sits a little above the curve: with 40 data points, each bar wobbles. What matters is the shape: with the right α, the curve goes with the data; with my α = 12.165 from the hook, the peak would be at 3.5 km/h, outside the histogram.
Checking it without differentiating: optimize
In the exam you differentiate by hand. In R you can check it by maximising the log-likelihood directly. For one parameter, optimize:
loglik <- function(a) sum(log(drayleigh(wind, a))) # l(alpha) with the data optimize(loglik, interval = c(10, 500), maximum = TRUE)
Output:
$maximum [1] 93.14425 $objective [1] -127.8304
How to read it
$maximum 93.14: the α where the log-likelihood is largest. It matches the formula to the last decimal: the derivative was right.$objective -127.83: the value of , the height of the hill at the top. It is negative because it is the log of a number below 1; it is not read on its own, it is for comparing.interval = c(10, 500): the interval to search. It has to contain the maximum; if you usec(1, 50), it will return 50, the edge.maximum = TRUE: without it,optimizeminimises.
When you cannot differentiate: the uniform
Sometimes the four-step recipe does not work. The upload delay is a uniform(0, θ): if . The likelihood of 15 delays is
The second part is the key: if θ were smaller than the largest delay observed (3.74 s), that data point would be impossible and L would be 0. And where it is not 0, always goes down: its derivative, , is never zero. So the maximum is at the edge, at the first allowed θ:
In the picture: to the left of 3.74 the likelihood is 0 (a flat line on the floor); exactly at 3.74 it jumps up and from there it falls. The maximum is the jump. By moments, gives : this time it lands above the maximum, but with another sample it could land below, and then it would say the maximum delay is smaller than a delay you have already seen. In the practice we count how often with 10,000 samples.
With numbers it is even clearer. The likelihood of the 15 delays at four values of θ:
| θ | Why | |
|---|---|---|
| 3.50 | 0 | there is a delay of 3.74 s, impossible if the maximum were 3.50 |
| 3.74 | the first θ that allows all the data | |
| 4 | allowed, but each data point falls in a wider interval and is less likely | |
| 5 | wider still, lower still |
With θ = 3.74 the sample is times more likely than with θ = 4. That is why the MLE is the largest data point: stretching θ always makes it worse, and shrinking it below 3.74 makes it impossible.
Differentiating , setting it to 0 and getting stuck at . There is no solution because the maximum is not where the derivative is zero: it is at an edge. When the support depends on the parameter (uniform(0, θ), shifted exponential…), draw L before differentiating.
When you cannot solve it: the gamma with optim
With the rain, the gamma has two parameters. The log-likelihood is
Differentiating with respect to β gives , easy. But the derivative with respect to α brings in , the digamma function, and the equation cannot be solved by hand. It is solved numerically, and that is what optim is for:
loglik2 <- function(par, x) sum(dgamma(x, shape = par[1], rate = par[2], log = TRUE))
mle <- optim(par = c(a_mm, b_mm), fn = loglik2, x = rain,
method = "L-BFGS-B", lower = c(0.01, 0.01),
control = list(fnscale = -1))
mle
Output:
$par
[1] 2.6089050 0.3775559
$value
[1] -54.64027
$counts
function gradient
12 12
$convergence
[1] 0
$message
[1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"
How to read it
$par 2.61 0.38: the MLEs, (shape) and (rate). By moments they were 3.77 and 0.55: here the methods do split. Their mean is the same, mm; what changes is the shape of the curve.$value -54.64: the value of at the maximum.$counts: how many times it evaluated the function and the gradient. A curiosity, not commented on in the exam.$convergence 0: the first thing to look at. 0 means the algorithm finished fine; another number (1, 51, 52) is a warning that the result may not be the maximum.$message: the reason it stopped, in the algorithm’s words.
What matters in the code:
par = c(a_mm, b_mm): the starting values. Starting from the moments ones is a good habit: they are close and the algorithm gets there sooner.fn = loglik2: the function to optimise, with the parameters in a vector (par[1],par[2]) as first argument.x = rain: the data, whichoptimpasses as they are tologlik2.control = list(fnscale = -1): essential.optimminimises; withfnscale = -1it maximises. Without it, it would look for the minimum of the log-likelihood.method = "L-BFGS-B", lower = c(0.01, 0.01): stops the parameters becoming negative (a gamma with shape −1 does not exist anddgammawould returnNaN). The notes use the default method; both get to the same place.
fitdist: the shortcut
The fitdistrplus package does all this in one line, and it is the one used in the exam:
suppressMessages(library(fitdistrplus)) # load the package without its messages
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)
fitdist(rain, "gamma", method = "mle")
Output:
Fitting of the distribution ' gamma ' by maximum likelihood
Parameters:
estimate Std. Error
shape 2.6089268 0.7780414
rate 0.3775861 0.1241446
estimate: the MLEs, the same as withoptim(2.61 and 0.38) except in the third decimal, because each algorithm stops a little earlier or later.Std. Error: an estimate of the standard deviation of each estimator: how much the estimate would change from one sample of 20 days to another. The shape (2.61 with an error of 0.78) is much less well pinned down than the rate. We will use it in confidence intervals.method = "mle"is maximum likelihood (the default);method = "mme"would be the method of moments.
In the picture, the two gammas over the rain histogram:
hist(rain, freq = FALSE, breaks = seq(0, 16, by = 2),
main = "Rain on rainy days", xlab = "mm")
curve(dgamma(x, mle$par[1], mle$par[2]), add = TRUE, lwd = 2) # ML
curve(dgamma(x, a_mm, b_mm), add = TRUE, lwd = 2, lty = 2) # moments
The maximum likelihood one (solid) is wider and gives more probability to days of 1 or 2 mm and to those of 14; the moments one (dashed) is more peaked at 6-8 mm. The histogram, with a strong peak at 6-8 and three days below 2, does not clearly choose between them: with 20 data points, that is normal.
The invariance principle
Once you have , often you are not interested in θ itself but in something that depends on it: the probability of a very windy reading, the mean rainfall, the median… The invariance principle says you do not have to start again:
Invariance principle of the MLE. If is the MLE of θ, then the MLE of any function is .
Two examples from the station:
- Probability that the wind goes above 20 km/h. In the Rayleigh, . Its MLE is .
- Probability that a rainy day goes above 10 mm. Its MLE is
1 - pgamma(10, 2.61, 0.38).
round(c(wind_20 = exp(-20^2 / (2 * alpha_ml)),
rain_10 = 1 - pgamma(10, mle$par[1], mle$par[2]),
wind_mean = sqrt(alpha_ml * pi / 2)), 3)
Output:
wind_20 rain_10 wind_mean
0.117 0.201 12.096
wind_20 0.117: we estimate that 11.7 % of readings are above 20 km/h. In the sample, 6 of 40 (15 %): the Rayleigh smooths out what a sample of 40 exaggerates or misses.rain_10 0.201: 20 % of rainy days go above 10 mm.wind_mean 12.096: the MLE of the mean wind speed, . Almost the sample mean (12.165), but not exactly: it is the mean of the fitted Rayleigh.
Invariance belongs to MLEs. There is no such theorem for the method of moments: the “moments estimate” of would have to be derived again by matching moments.
Moments or maximum likelihood: which one I use
The map sums up how you decide in an exam. And the table, the comparison:
| Method of moments | Maximum likelihood | |
|---|---|---|
| Idea | Match population and sample moments | Choose the parameter that makes the data most likely |
| What you need | (and or the variance with two parameters) | The density or mass, |
| Working | Solve a system | Differentiate the log-likelihood (or optim) |
| Unique? | No: depends on which moments you match | Yes, if the maximum is unique |
| Can give impossible values | Yes (2x̄ below the maximum in the uniform) | No: it never picks a θ that makes a data point impossible |
| Invariance | No | Yes |
| In R | Formulas with mean and (n-1)/n*var | optimize, optim(..., fnscale = -1), fitdist |
| We use it for | Starting values for optim, quick sums | The “good” estimate (it is the one usually asked for) |
What gets proved in this topic
All of it, step by step and checked in R, in the point estimation proofs:
- The mean of the Rayleigh, , and its moments estimator.
- Moments with two parameters: the gamma and the uniform(a, b); and why the moments estimator is not unique.
- MLE of the Bernoulli and the Poisson, with the second derivative.
- MLE of the exponential and the Rayleigh.
- MLE of the normal with μ and σ unknown (the system of two equations) and why the gamma needs
optim. - MLE of the uniform(0, θ) without differentiating.
- Invariance and the distribution of the Rayleigh MLE with the moment generating function.
Common mistakes
Confusing the parameter with the mean. They only coincide in some families (Poisson, Bernoulli, the μ of the normal). In the Rayleigh, the exponential (mean 1/λ) or the gamma (mean α/β), the estimator comes from solving.
Forgetting the logarithm and differentiating the product. It can be done, but the product rule with 30 factors is hell. The logarithm turns into and does not move the maximum.
Not checking the second derivative. It is marked in the exam: without it you do not know whether it is a maximum or a minimum.
optim without control = list(fnscale = -1). It looks for the minimum of the log-likelihood and ends up at an edge, with a meaningless result and convergence 0. In the exercises we see it live.
Confusing rate and scale in the gamma. In R, dgamma(x, shape, rate); if you write dgamma(x, 2.61, 0.38) without names, the third argument is rate. In the notes, gamma(α, β) is shape and rate, just like R.
Try it in the R playground
Open the R playground on the site (or RStudio) and paste this script, which brings together the essentials of the article with the wind data:
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)
n <- length(wind)
alpha_mm <- 2 * mean(wind)^2 / pi # moments
alpha_ml <- sum(wind^2) / (2 * n) # maximum likelihood
loglik <- function(a) sum(log(wind / a) - wind^2 / (2 * a))
curve(sapply(x, loglik), 50, 200, xlab = "alpha", ylab = "log-likelihood")
abline(v = c(alpha_mm, alpha_ml), lty = c(2, 1))
c(moments = alpha_mm, ml = alpha_ml,
optimize = optimize(loglik, c(10, 500), maximum = TRUE)$maximum)
Things to look at:
- In the Environment panel,
alpha_mmandalpha_ml: 94.21 and 93.14. - In Plots, the log-likelihood hill with its top on the solid line. The dashed one (moments) is almost in the same place.
- Why the
sapply:curvepasses the function a vector of x, andloglikis meant for a single α (it does asuminside). Remove thesapplyand you will see a meaningless straight line. - Change the
optimizeinterval toc(10, 50): it returns almost 50, the edge. The interval has to contain the maximum.
Summary
| Concept | What it is | In R |
|---|---|---|
| Estimator | Formula with the sample, | A function of x |
| Estimate | The number with your data | That function’s result |
| Variance dividing by n | (n - 1) / n * var(x) | |
| Moments | Set equal to and solve | mean, s2prime |
| Likelihood | , with θ as the variable | prod(dxxx(x, θ)) |
| MLE | The θ that maximises L (or ) | optimize, optim(fnscale = -1), fitdist |
| Uniform(0, θ) | , without differentiating | max(x) |
| Invariance | MLE of = | Plug into the formula |
| Distribution | Moments | Maximum likelihood |
|---|---|---|
| Bernoulli(p) | ||
| Poisson(λ) | ||
| exp(λ) | ||
| Rayleigh(α) | ||
| normal(μ, σ) | , | , |
| gamma(α, β) | , | With optim or fitdist |
| uniform(0, θ) |
Three ideas to take away:
- Estimating is giving the parameter a value from the data. The estimator is a formula (a random variable); the estimate, a number.
- Moments match; maximum likelihood maximises. Sometimes they agree (Poisson, normal) and sometimes not (Rayleigh, gamma, uniform). Maximum likelihood is the one asked for almost always, and it has invariance.
- First the log, then the derivative, then the second derivative. And if it cannot be solved or the support depends on the parameter,
optimor a picture of L.
Now it is time to do it on the computer: in the point estimation practice in R you estimate the station’s five series by both methods, draw likelihoods and fit the rain with optim and fitdist. And to check you have got it, the point estimation exercises go from easy to hard as chained exam-style exercises, with commented solutions.
Did this article help you? Here is how you can support SergioLearns →



