Point estimation — R practice with the campus station, moments, optimize, optim and fitdist (and the likelihood that came out zero with 400 readings)
The night before practical 11 I wanted to maximise the wind likelihood with a year of readings and optimize kept returning the edge of the interval, whatever I told it. With the 40 readings from class it worked. With 400, it did not. The problem was one word: I had written the likelihood with prod(), multiplying 400 densities of 0.04 or 0.05, and the result was so small the computer rounded it to 0. If every value of α gives 0, any of them is “the maximum”, and optimize keeps whichever it lands on. With sum(log()) it worked first time. In program 2 you will see it happen.
In the point estimation theory you saw the two methods and in the proofs, where each formula comes from. Here we do it in R, with the data from the rooftop station, in three medium-level programs: the first estimates the five series by moments and checks whether the Poisson fits the gusts; the second draws likelihoods and maximises them with optimize and optim; the third fits the rain gamma with optim and with fitdist and compares the two methods. The data are shaped like real ones: wind with a long tail, one hour with 9 gusts and three rainy days below 2 mm.
Table of Contents
Before you start
It helps to be clear about:
- What a moments estimator is (match to and, with two parameters, the variance to ).
- What the likelihood is and why its logarithm is maximised.
- The formulas from the theory table: Poisson , Rayleigh and , gamma by moments and .
- R’s
d,p,q,rfunctions withlog = TRUEin the densities.
If any of these feels shaky, go over the theory before carrying on.
fitdist is in the fitdistrplus package. In RStudio install it once with install.packages("fitdistrplus"); in the site’s R playground, the first time you run library(fitdistrplus) it has to be installed too (install.packages works there). In the exam you have to bring it installed.
All the programs start with the station 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)
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)
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)
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)
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)
Program 1: moments for the five series
Compute the method of moments estimator for each series, check with a table whether the estimated Poisson reproduces the gust frequencies and see, by simulating, how often the uniform’s moments estimator gives an impossible value.
The idea
Three parts. First, the formulas: a function s2prime() so as not to get it wrong with var(), and one line per parameter. Second, the gusts fit: if , in 24 hours we expect hours with k gusts; we compare that with what we counted. Third, the uniform: we simulate 10,000 samples of 15 delays with θ = 4 and count how many have below the maximum.
In plain words: the method of moments is one question, asked once per series: “if the data came from this model, which value of the parameter would give the same mean I measured?”. For the gusts the model’s mean is λ, so λ is simply the mean of the 24 hours. For the wind the mean is , and you have to solve for α. For the rain there are two parameters and one mean is not enough: that is why the variance comes in too.
Before programming, think about which vector each thing goes in: table() only counts the values that appear. If there were never 0, 7 or 8 gusts, they will not come out as 0: you have to use factor(gusts, levels = 0:9).
The code
s2prime <- function(x) mean((x - mean(x))^2) # central moment of order 2: divides by n
# 1) Method of moments estimators
mm <- c(lambda_gusts = mean(gusts), # Poisson: E(X) = lambda
p_rains = mean(rains), # Bernoulli: E(X) = p
alpha_wind = 2 * mean(wind)^2 / pi, # Rayleigh: E(X) = sqrt(alpha*pi/2)
shape_rain = mean(rain)^2 / s2prime(rain), # gamma: shape
rate_rain = mean(rain) / s2prime(rain), # gamma: rate
theta_delay = 2 * mean(delay)) # uniform(0, theta): E(X) = theta/2
round(mm, 3)
# 2) Does the Poisson fit the gusts? Observed against expected
obs <- table(factor(gusts, levels = 0:9)) # hours with 0, 1, ..., 9 gusts
expd <- 24 * dpois(0:9, mm["lambda_gusts"]) # hours expected if lambda = 3.21
tab <- rbind(observed = as.vector(obs), expected = round(expd, 1))
colnames(tab) <- 0:9 # one column per number of gusts
tab
barplot(rbind(obs, expd), beside = TRUE, names.arg = 0:9,
legend.text = c("observed", "expected"), xlab = "gusts in an hour")
# 3) How often is 2 * mean below the largest data point?
set.seed(4)
impossible <- replicate(10000, {
x <- runif(15, 0, 4) # 15 delays with theta = 4
2 * mean(x) < max(x) # TRUE if the estimator leaves a data point out
})
mean(impossible) # proportion of samples with an impossible estimator
Output
lambda_gusts p_rains alpha_wind shape_rain rate_rain
3.208 0.300 94.212 3.768 0.545
theta_delay
3.933
0 1 2 3 4 5 6 7 8 9
observed 0 5.0 4 5.0 7.0 0.0 2.0 0.0 0.0 1.0
expected 1 3.1 5 5.3 4.3 2.7 1.5 0.7 0.3 0.1
[1] 0.3222
How to read it
- The six estimators. 3.208 gusts per hour; 30 % rainy days; α = 94.212 for the wind; the rain gamma with shape 3.768 and rate 0.545; and a maximum delay of 3.933 s. All by matching the mean (and the variance in the gamma).
- The two rows of the table. The first counts real hours: none with 0 gusts, 5 with 1, 4 with 2… The second, those the Poisson(3.21) predicts in 24 hours: 1 with 0, 3.1 with 1, 5 with 2… Both add up to 24 (the second, almost: the Poisson leaves a little for 10 or more).
- The picture. The pairs of bars from
barplot(beside = TRUE): observed in black and expected in coral. They follow the same shape, peaking at 3-4 with a tail to the right. The hour with 9 gusts is rare for the Poisson (it expects 0.1), but one in 24 can happen. With 24 data points you cannot ask for more: the Poisson is reasonable. 0.3222. In 32 % of samples of 15 delays, the moments estimator of θ falls below the largest delay: it would estimate that the maximum possible is smaller than something you have already seen. That is why, in the uniform, the maximum likelihood one is used.
The six estimators, one by one
The program computes all six at once inside a c(). These are the pieces it uses (with the data from the start loaded):
s2prime <- function(x) mean((x - mean(x))^2)
round(c(sum_gusts = sum(gusts), hours = length(gusts),
mean_wind = mean(wind), mean_rain = mean(rain),
s2p_rain = s2prime(rain), mean_delay = mean(delay),
max_delay = max(delay)), 2)
round(24 * dpois(c(0, 4, 9), 77 / 24), 2) # three cells of the expected row
Output:
sum_gusts hours mean_wind mean_rain s2p_rain mean_delay max_delay
77.00 24.00 12.16 6.91 12.67 1.97 3.74
[1] 0.97 4.28 0.10
With those pieces, each estimator is a short calculation:
| Estimator | Calculation | Result | Why |
|---|---|---|---|
| (gusts) | 3.21 | in the Poisson the mean is λ: there is nothing to solve for | |
| (rain yes or no) | 0.30 | the mean of ones and zeros is the proportion of ones | |
| (wind) | 94.21 | α is solved from : square it and multiply by (the exact mean is 12.165; the output rounds it) | |
| shape (rain) | 3.77 | with two parameters the mean and the variance are matched; divide by , not by var() | |
| rate (rain) | 0.55 | the same in the denominator; the program’s output gives 0.545 with 3 decimals | |
| (delay) | 3.93 | in the uniform(0, θ) the mean is half of θ |
The expected row, cell by cell. With 0 gusts: , which R prints as 1. With 4: . With 9: 0.10.
Check you’ve got it: why does the table expect one hour with 0 gusts when the data had none?
Because the expected row does not look at the data: it looks at the model. With , the Poisson gives hours without gusts a probability of , and in 24 hours that is hours. Something that happens once in 25 may not happen in 24 tries: it contradicts nothing.
Questions you might ask
Why not use var() in the gamma? Because the method matches the population variance to the sample’s central moment, which divides by n. var(rain) divides by 19 and would give a shape of 3.58 instead of 3.77.
Why mm["lambda_gusts"] and not mean(gusts) again? To use the estimator you have just computed, so that if you change the formula above everything below changes too. It is the same number.
What does factor(…, levels = 0:9) do? It tells table() which values can appear even if they do not. Without it, the table would start at 1 (no hour had 0) and would have no 7 or 8, and the bars could not be compared with dpois(0:9, …).
Is the 32 % from our data? No: it is from 10,000 simulated samples with θ = 4 and n = 15. Our sample is one without the problem (3.93 > 3.74). With more data the percentage does not disappear: the moments estimator depends on the mean, and the mean does not know where the largest data point is.
What if you estimated θ with the largest delay, as maximum likelihood does?
Same seed, same 10,000 samples, and now both estimators are kept:
set.seed(4)
sim <- replicate(10000, {
x <- runif(15, 0, 4) # the same samples as in program 1
c(moments = 2 * mean(x), maximum = max(x)) # the two estimators of theta
})
round(rbind(mean = rowMeans(sim), # where they land on average
sd = apply(sim, 1, sd), # how much they move from sample to sample
over_4 = rowMeans(sim > 4)), 2) # how often they overshoot the real theta
round(mean(16 / 15 * sim["maximum", ]), 2) # the maximum, corrected
Output:
moments maximum mean 4.0 3.75 sd 0.6 0.24 over_4 0.5 0.00 [1] 4
The moments one is right on average (4.00), but it moves a lot (0.60): it overshoots 4 half of the time and, when it falls short, sometimes lands below a data point (the program’s 32 %). The maximum can never be impossible, because it is a data point, and it moves a quarter as much as the other one (0.24 against 0.60). In exchange, it never goes above 4: the real θ is always above the largest data point, so on average it stays at 3.75, which is . That systematic error is corrected by multiplying by , and the last line checks it: the mean goes back to 4. With our delays: .
Comparing table(gusts) with dpois(0:9, …) without the factor. The lengths do not match (8 against 10) and R recycles or throws an error, depending on how you join them. Before comparing frequencies, check that both vectors have the same length and the same values.
Try it yourself
- Change
runif(15, 0, 4)torunif(60, 0, 4)and see how the percentage of impossible estimators goes down (or not). - Compute the second moments estimator of the gusts,
s2prime(gusts), and redo the expected table with it. Which one looks more like the observed?
Program 2: the likelihood, drawn and maximised
Draw the likelihood of the rainy days and the wind log-likelihood, find their maxima with optimize and optim, and check what happens if, with 400 readings, you use prod() instead of sum(log()).
The idea
For one parameter, the likelihood is a curve and you can see it: we draw it with curve and mark the maximum. Then we look for it with two functions: optimize, meant for one parameter (you give it an interval), and optim, meant for several (you give it a starting point; with one parameter, better with method = "Brent" and limits). At the end, the mistake from the hook: 400 readings (the 40, ten times) with prod().
In plain words: the likelihood is a question asked the other way round from probability. The data are already fixed and what moves is the parameter. For each value of p, the curve answers “how likely was it to see exactly these 30 days if the probability of rain were p?”. The MLE is the value that best explains what has already happened: the top of the curve.
For the rainy days the curve is and it can be drawn as it is. For the wind there are 40 densities multiplied together, and that is why its logarithm is drawn: the product turns into a sum, the top is in the same place and the numbers do not become tiny.
Before programming, think about what each function receives: curve() passes the function a vector of parameter values all at once. If you do sum() inside, you would be adding up mixing all the parameters. With sapply or Vectorize the function is applied value by value.
The code
drayleigh <- function(x, alpha) x / alpha * exp(-x^2 / (2 * alpha)) # R has no Rayleigh
L_rains <- function(p) p^sum(rains) * (1 - p)^(length(rains) - sum(rains)) # p^9 (1-p)^21
l_wind <- function(a) sum(log(drayleigh(wind, a))) # log-likelihood
par(mfrow = c(1, 2)) # two plots side by side
curve(L_rains, 0, 1, xlab = "p", ylab = "L(p)", main = "Rainy days")
abline(v = mean(rains), lty = 2) # the MLE, p = s/n
curve(Vectorize(l_wind)(x), 40, 250, xlab = "alpha", ylab = "l(alpha)", main = "Wind")
abline(v = sum(wind^2) / 80, lty = 2) # the MLE, sum(x^2)/(2n)
par(mfrow = c(1, 1))
# The maximum, found in two ways
o1 <- optimize(l_wind, interval = c(10, 500), maximum = TRUE)
o2 <- optim(par = 80, fn = l_wind, method = "Brent", lower = 10, upper = 500,
control = list(fnscale = -1))
round(c(formula = sum(wind^2) / 80, optimize = o1$maximum, optim = o2$par,
l_max = o2$value, convergence = o2$convergence), 4)
# 400 readings: product against sum of logs
wind400 <- rep(wind, 10)
c(product = prod(drayleigh(wind400, 93)), sum_logs = sum(log(drayleigh(wind400, 93))))
L400 <- function(a) prod(drayleigh(wind400, a))
optimize(L400, interval = c(10, 500), maximum = TRUE)$maximum # with prod: the edge
optimize(function(a) sum(log(drayleigh(wind400, a))), c(10, 500), maximum = TRUE)$maximum
Output
formula optimize optim l_max convergence
93.1442 93.1442 93.1443 -127.8304 0.0000
product sum_logs
0.000 -1278.305
[1] 499.9999
[1] 93.14425
How to read it
- The left picture is the likelihood of the 30 days: a hump with its maximum on the dashed line, p = 0.3. Its height is tiny (of the order of ) because it is the probability of one particular sequence of 30 days.
- The right one is the wind log-likelihood between α = 40 and 250: it rises fast, peaks at 93.14 (dashed line) and falls slowly. It is asymmetric: an α that is too small makes the 25 km/h readings almost impossible, and that is punished much more than an α that is too large.
formula 93.1442,optimize 93.1442,optim 93.1443: three paths, the same number (the last digit ofoptimis the algorithm’s tolerance). The formula from proof 4 was right.l_max -127.8304: the height of the top, .convergence 0:optimfinished fine.product 0againstsum_logs -1278.3: the product of 400 densities is exactly 0 on the computer (the real number is around , and adoubledoes not go below ). The sum of logs is computed without trouble.499.9999against93.14: withprod, the likelihood is 0 for every α, andoptimizereturns an end of the interval, the 500, as if it were the maximum. Withsum(log()), the right maximum: the same 93.14 as with 40 data points, because repeating the data ten times does not change .
The product, reading by reading
The output only shows the end, product 0. To see how it gets there, accumulate the product with cumprod:
wind400 <- rep(wind, 10) d400 <- drayleigh(wind400, 93) # one density per reading how_many <- c(10, 40, 100, 200, 300, 400) signif(cumprod(d400)[how_many], 3) # the product after 10, 40, 100... readings round(cumsum(log(d400))[how_many] / log(10), 2) # the same, counted in powers of 10 which(cumprod(d400) == 0)[1] # the first reading at which it is already 0
Output:
[1] 1.87e-13 3.05e-56 1.01e-138 2.63e-278 0.00e+00 0.00e+00 [1] -12.73 -55.52 -138.00 -277.58 -415.58 -555.16 [1] 234
| Readings | Product | In powers of 10 | Why |
|---|---|---|---|
| 10 | −12.73 | each density is around 0.04, and multiplying by 0.04 takes away almost 1.4 powers of 10 | |
| 40 | −55.52 | it is : the likelihood of the 40 class readings, still representable | |
| 100 | −138.00 | it keeps falling at the same pace, about 1.39 powers per reading () | |
| 200 | −277.58 | very close to the limit of a double, | |
| 300 | 0 | −415.58 | the real number exists, but the computer can no longer store it |
| 400 | 0 | −555.16 | the of the output; the sum column computes it without trouble |
The last line says where it breaks: at reading 234 the product is already 0, and it never gets out of there (0 times anything is 0). The sum of logs just keeps subtracting about 3.2 units per reading.
Check you’ve got it: why is the sum of logs of the 400 readings exactly ten times that of the 40?
Because wind400 is the same 40 readings repeated ten times, and the log of a product is the sum of the logs. Each reading contributes its ten times, so the total sum is , the number in the output. Multiplying the curve by 10 does not change at which α the top is: that is why 93.14 comes out again.
Questions you might ask
Why Vectorize(l_wind)(x) in curve and not just l_wind? Because curve calls the function only once with 101 values of α. l_wind would do drayleigh(wind, a) with 40 data points and 101 alphas at once: R would pair them by recycling and the sum would make no sense. Vectorize turns it into a function applied to each α separately.
Why does optim need method = "Brent"? optim‘s default method (Nelder-Mead) is meant for several parameters and, with one, warns that it is “unreliable”. Brent searches an interval, like optimize, and that is why it asks for lower and upper.
What use is l_max if it is not read on its own? For comparing. If you fit another distribution to the same data (a gamma, for example), the one with the highest maximum log-likelihood explains the data better. In program 3 we use it to compare moments and maximum likelihood.
And if I draw exp(l_wind) instead of l_wind? You get the likelihood: a narrow spike peaking at the same place, at a height of . With 40 data points you still can; with 400, no.
Writing the likelihood with prod(). With little data it works and you do not notice; with a lot, it gives 0 and the maximum lands on an edge without any warning. Always write the log-likelihood with sum(log(…)) or, better, with sum(dxxx(x, …, log = TRUE)).
Try it yourself
- Change the
optimizeinterval toc(10, 50)and see what it returns. Do the same withoptimandupper = 50. - Also draw the gusts log-likelihood,
function(l) sum(dpois(gusts, l, log = TRUE)), between 1 and 7, and check that the top is at 3.21.
Program 3: the rain with optim and fitdist
Fit the rain gamma by maximum likelihood with optim and with fitdist, compare the result with the moments one (in the parameters, the log-likelihood and the probabilities) and use invariance to estimate the probability of a day above 10 mm.
The idea
The gamma has two parameters and its MLE cannot be solved by hand (proof 5 explains why), so it is searched for numerically. We start optim at the moments estimator, which is close. Then fitdist does the same in one line and also gives the standard errors. To compare the two methods: (1) the log-likelihood of each (the maximum likelihood one has to be larger, by definition), and (2) the empirical distribution function against the two fitted ones.
In plain words: with two parameters the likelihood is no longer a curve, it is a landscape with hills, and it cannot be drawn with curve. optim does what you would do blindfolded on a mountain: from a point, it takes steps towards where the ground rises until no step goes up. That is why the starting point matters. If it starts from the moments estimators, which are already close to the top, it gets there in a few steps.
Before programming, think about the format optim wants: the function receives a vector with the two parameters as first argument and the data after. And always control = list(fnscale = -1) to maximise.
The code
s2p <- mean((rain - mean(rain))^2) # S'^2
a_mm <- mean(rain)^2 / s2p # moments: shape
b_mm <- mean(rain) / s2p # moments: rate
loglik <- function(par, x) sum(dgamma(x, shape = par[1], rate = par[2], log = TRUE))
mle <- optim(par = c(a_mm, b_mm), fn = loglik, x = rain,
method = "L-BFGS-B", lower = c(0.01, 0.01), # positive parameters
control = list(fnscale = -1)) # maximise
a_ml <- mle$par[1]; b_ml <- mle$par[2]
round(rbind(moments = c(shape = a_mm, rate = b_mm, mean = a_mm / b_mm,
l = loglik(c(a_mm, b_mm), rain),
p_over_10 = 1 - pgamma(10, a_mm, b_mm)),
max_likelihood = c(a_ml, b_ml, a_ml / b_ml, mle$value,
1 - pgamma(10, a_ml, b_ml))), 3)
c(convergence = mle$convergence, days_over_10 = mean(rain > 10))
plot(ecdf(rain), main = "Rain: empirical against the two gammas", xlab = "mm")
curve(pgamma(x, a_ml, b_ml), add = TRUE, lwd = 2) # maximum likelihood
curve(pgamma(x, a_mm, b_mm), add = TRUE, lwd = 2, lty = 2) # moments
Output
shape rate mean l p_over_10
moments 3.768 0.545 6.91 -55.492 0.176
max_likelihood 2.609 0.378 6.91 -54.640 0.201
convergence days_over_10
0.00 0.15
And with fitdist, which gives the same in one line:
suppressMessages(library(fitdistrplus))
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)
fit <- fitdist(rain, "gamma") # method = "mle" by default
fit
round(c(loglik = fit$loglik, aic = fit$aic), 3)
fitdist(rain, "gamma", method = "mme")$estimate # the moments one
Output:
Fitting of the distribution ' gamma ' by maximum likelihood
Parameters:
estimate Std. Error
shape 2.6089268 0.7780414
rate 0.3775861 0.1241446
loglik aic
-54.640 113.281
shape rate
3.767733 0.545258
How to read it
- The
momentsrow: shape 3.768 and rate 0.545, mean 6.91 mm, log-likelihood −55.492 and 17.6 % of rainy days above 10 mm. - The
max_likelihoodrow: shape 2.609 and rate 0.378, the same mean (6.91: proof 5 said ), log-likelihood −54.640 and 20.1 % of days above 10 mm. - The log-likelihood: −54.640 is larger than −55.492. It had to be: the MLE is, by definition, the point where is largest. That the difference is small (0.85) says the two gammas explain the data almost equally well.
days_over_10 0.15: in the sample, 3 of 20 days went above 10 mm. The two estimates (17.6 % and 20.1 %) sit a bit above: with 20 days, 3 or 4 above 10 mm is almost the same. With invariance, the 20.1 % is the MLE of .- The picture is the empirical distribution function from
ecdf(the staircase, rising 1/20 at each data point) with the two gammas on top. The maximum likelihood one (solid) goes slightly above the staircase on the left and slightly below on the right: it puts more probability in the tails. The moments one (dashed) rises more steeply in the center. Both stay inside the staircase most of the time. fitdist: estimate 2.609 and 0.378, as withoptim, with their standard errors (0.778 and 0.124).loglik -54.640is the same value asmle$value. Theaicis with k = 2 parameters: ; it is for comparing different distributions (smaller is better) and you will see it in other subjects.method = "mme": the moments ones, 3.768 and 0.545, the same as with the formula.
The top, searched by hand
optim does not show the path, only where it ends. There is a shortcut to see it: proof 5 says that at the gamma’s MLE . So the top lies on the line with mean 6.91: for each shape, the rate is shape / 6.91.
loglik <- function(par, x) sum(dgamma(x, shape = par[1], rate = par[2], log = TRUE))
shape <- c(1.5, 2, 2.609, 3, 3.768, 4.5)
rate <- shape / mean(rain) # the rate that keeps the mean at 6.91
l <- sapply(seq_along(shape), function(i) loglik(c(shape[i], rate[i]), rain))
round(rbind(shape, rate, l), 2)
mle <- optim(par = c(3.768, 0.545), fn = loglik, x = rain, method = "L-BFGS-B",
lower = c(0.01, 0.01), control = list(fnscale = -1))
mle$counts # how many times it evaluated loglik
Output:
[,1] [,2] [,3] [,4] [,5] [,6]
shape 1.50 2.00 2.61 3.00 3.77 4.50
rate 0.22 0.29 0.38 0.43 0.55 0.65
l -56.12 -55.01 -54.64 -54.75 -55.49 -56.63
function gradient
11 11
| Shape | Rate | Why | |
|---|---|---|---|
| 1.50 | 0.22 | −56.12 | gamma too wide: it gives little density to the normal days, of 6 or 7 mm |
| 2.00 | 0.29 | −55.01 | going up |
| 2.61 | 0.38 | −54.64 | the top: the same as mle$value |
| 3.00 | 0.43 | −54.75 | already going down, but only a little: near the top the ground is almost flat |
| 3.77 | 0.55 | −55.49 | the moments point, 0.85 below the top |
| 4.50 | 0.65 | −56.63 | too peaked: the days of 0.8 and 1.3 mm become very unlikely |
optim made that journey on its own, from the 3.77 column to the 2.61 one, in 11 evaluations.
Check you’ve got it: the moments point also lies on the line with mean 6.91. Why?
Because the method of moments matches the mean by construction. Its shape is and its rate ; when you divide them, cancels and is left. That is why the program’s output gives mean 6.91 in both rows. They only differ in the shape: the moments choose it to get the variance right; maximum likelihood, to make the 20 days as likely as possible.
Questions you might ask
Why start optim at the moments values and not at c(1, 1)? Because from a good starting point the algorithm gets there sooner and with less risk of stopping somewhere odd. From c(1, 1) it also gets there, but with more evaluations (try it and look at mle$counts).
Why lower = c(0.01, 0.01)? With the default method, optim may try a negative shape or rate; dgamma returns NaN and warnings appear. With L-BFGS-B and a positive lower limit, it never tries impossible values.
If the mean is the same, how do the two gammas differ? In the shape: with α = 2.6 the gamma is wider and more skewed; with 3.8, more peaked and symmetric. Moments fit the mean and variance; maximum likelihood fits the whole curve at once, data point by data point, and that is why it takes the three days below 2 mm into account.
Why is fitdist separate? Because on this page the R that runs in the browser does not have fitdistrplus; I ran that block with R 4.3 on my computer. In RStudio or the site’s playground, with the package installed, you just paste it after the rest.
Forgetting control = list(fnscale = -1). optim minimises by default: it would look for the minimum of the log-likelihood and end up with the shape at the limit (0.01) and the rate shooting off, with convergence 0, without warning you of anything. If the result makes no sense, the first thing to check is whether you put the fnscale.
Try it yourself
- Also fit an exponential to the rain with
fitdist(rain, "exp")and compare itsloglikwith the gamma’s. Is the second parameter worth it? - Change
optim‘s starting point toc(1, 1)and then toc(20, 5). Does it always get to the same place? How many evaluations does it need?
Common mistakes in this practice
- Using
var()as in the method of moments.var()divides by n − 1. - The likelihood with
prod(). With a lot of data it gives 0 and the maximum lands on an edge without warning. optimwithoutfnscale = -1. It minimises instead of maximising.- Passing
curvea function that doessum(). It has to be vectorised withVectorizeorsapply. - Not looking at
$convergence. If it is not 0, the result may not be the maximum. - Comparing
table()withdpois()withoutfactor(…, levels = …). The values that do not appear are missing.
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 three programs:
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)
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)
drayleigh <- function(x, alpha) x / alpha * exp(-x^2 / (2 * alpha))
l_wind <- function(a) sum(log(drayleigh(wind, a)))
curve(Vectorize(l_wind)(x), 40, 250, xlab = "alpha", ylab = "log-likelihood")
alpha_ml <- optimize(l_wind, c(10, 500), maximum = TRUE)$maximum
loglik <- function(par, x) sum(dgamma(x, par[1], par[2], log = TRUE))
mle <- optim(c(3, 0.5), loglik, x = rain, method = "L-BFGS-B",
lower = c(0.01, 0.01), control = list(fnscale = -1))
c(alpha_wind = alpha_ml, shape = mle$par[1], rate = mle$par[2])
Things to look at:
- In Plots, the hill of the wind log-likelihood, with its top near 93.
- In Environment,
mleis a list: open it with a click and you will seepar,value,counts,convergenceandmessage. - Remove
control = list(fnscale = -1)and run it again: the shape goes to the limit, 0.01, and the rate to an absurd number, around . - Type
?optimin the console: in the help, look forfnscaleand read what it does.
Summary
- The method of moments is formulas with
meanands2prime; it also serves asoptim‘s starting point. - A fit is checked against the data: observed against expected frequencies (discrete), histogram with the density or
ecdfwith the distribution function (continuous). - A one-parameter likelihood is drawn with
curve(Vectorize(f)(x), …)and maximised withoptimize(…, maximum = TRUE). - With several parameters,
optim(par, fn, …, control = list(fnscale = -1)); always check$convergence. fitdist(x, "gamma")gives the MLE, its standard errors and the log-likelihood; withmethod = "mme", the moments ones.- The log-likelihood is written with
sum(log())orlog = TRUE, never withprod().
Checklist: have you practised it?
- Have you run the three programs and checked the outputs?
- Could you explain why the MLE always has a log-likelihood greater than or equal to the moments one?
- Do you know when to use
optimizeand whenoptim? - Could you say what
$valueand$convergencemean? - Have you seen with your own eyes what happens with
prod()and 400 data points? - Have you tried the “Try it yourself” sections without looking at the theory?
If you answered yes to almost everything, you are ready for the point estimation exercises, where I no longer give you the code. See you there!
Next step: exercisesPoint estimation — exam-style exercises with the humidity, the lightning around the station and the pressure (and the var() that cost me half a point)Did this article help you? Here is how you can support SergioLearns →



