Fourth Lab

Today’s goals. Learn about:

  1. Likelihood theory and numerical optimisation
  2. Properties of the MLE (by simulation)
  3. Tests and confidence intervals based on the likelihood

Workflow

  1. Consider examples related to theoretical concepts
  2. Using R to solve some basic questions and to understand important aspects

Let’s start

  1. Download the R code (It is briefly commented)
  2. You will find TODO where I will ask you to code a bit
  3. Part of the code after TODO, depends on successfully filling these lines of code

Likelihood theory: Maximum likelihood estimation

Likelihood inference

The likelihood function

Let \(\mathcal{F}\) be a parametric statistical model for the data \(y\), where \(f(y;\theta)\) is the density or probability function and \(\theta \in \Theta\) is a p-dimensional parameter. By considering \(f(y;\theta)\) as function of \(\theta\) with \(y\) fixed to the observed value, then the likelihood function of \(\theta\) based on \(y\), \(L: \Theta \rightarrow \mathbb{R}^{+}\), is \[L(\theta) = L(\theta; y) \propto f_Y(y; \theta) \,\,, \] where the proportionality is related to a constant \(c(y)>0\) that does not depend on \(\theta\).

On the basis of the data \(y\), \(\theta \in \Theta\) is more likely than \(\theta' \in \Theta\) as an index of the data generating model if \(L(\theta) > L(\theta')\)

Note

  • \(L(\theta)\) is not a density function (on \(\Theta\)).
  • It is convenient to work with \(\ell(\theta) = \log L(\theta)\).
  • If we assume independent observations for \(y=(y_1, \ldots, y_n)\), then \(L(\theta) \propto \prod_{i=1}^{n} f_{Y_i}(y_i; \theta)\) and, up to an additive constant, \(\ell(\theta) = \sum_{i=1}^{n} \log f_{Y_i}(y_i; \theta)\).
  • The value \(\hat \theta\) that maximizes \(L(\theta)\) (or equivalently \(\ell(\theta)\)) is the maximum likelihood estimate.

Numerical optimisation

A Binomial example

Setup

  • Let \(y=(y_{1},\ldots, y_{n})\) be a sample of i.i.d. values from a Bernoulli distribution, \(Y \sim \mbox{Be}(p)\), with \(n = 100\) and \(p = 0.6\). The log-likelihood function is \[\ell(p) = \sum_{i=1}^{n} y_i \log (p) + \Big(n - \sum_{i=1}^{n} y_i\Big) \log (1-p)\] and the MLE is available in closed form, \(\hat p = \bar y\): this allows us to check the output of the numerical optimisers.
  • Logit reparametrisation: \(\psi = {\rm logit}(p) = \log\{p/(1-p)\}\) maps \((0, 1)\) into \(\mathbb{R}\), with inverse \(p(\psi) = \exp(\psi)/\{1+\exp(\psi)\}\). By the invariance of the MLE, \(\hat \psi = {\rm logit}(\hat p)\).
set.seed(13)
n <- 100
p <- 0.6
y <- rbinom(n, 1, p)
mean(y) # MLE of p
[1] 0.63
psi <- function(theta) log(theta/(1-theta))
theta <- function(psi) exp(psi)/(1+exp(psi))

Numerical optimisation

R functions for numerical optimisation

In the Binomial example, the MLE is available in closed form and we obtain numerical values just by plugging the data into the formula. However, remember that the MLE for a parameter may not have an analytic solution. Many times we do not have a closed form for MLE estimates and we may need numerical optimisation. R provides various functions for performing numerical methods:

  • nlm(): minimizes a function using a Newton-type algorithm. It needs a starting value and does not allow constraints on the parameters. It is usually fast and reliable. It returns the ML estimate \(\hat{\theta}\) (estimate), the minimum \(-\ell(\hat{\theta})\) of the negative log-likelihood (minimum) and the hessian (hessian), if hessian = TRUE.

  • optim(): minimizes a function using Nelder-Mead, quasi-Newton and conjugate gradients algorithms. It includes an option for box-constrained optimization, and it requires a starting value. It returns the ML estimate \(\hat{\theta}\) (par), the minimum of the negative log-likelihood \(-\ell(\hat{\theta})\) (value) and the hessian (hessian), if hessian = TRUE. You also can maximize the function by using fnscale = -1 in control argument.

  • nlminb(): often is more stable, robust and reliable than optim (in particular with “nasty” functions). It performs only minimization and does not yield numerical derivatives as output. It returns the ML estimate \(\hat{\theta}\) (par) and the minimum of the negative log-likelihood \(-\ell(\hat{\theta})\) (objective).

  • optimize(): by using a combination of golden section search and successive parabolic interpolation, searches in an interval for a minimum or a maximum (if maximum=TRUE) of a function. It returns \(\hat{\theta}\) (maximum if maximum=TRUE, otherwise minimum) and the value of the function there (objective). Drawback: suited only for one-dimensional parameter.

Numerical optimisation

Binomial example

Here, we are simply using the Binomial example to show how (some of) these functions work.

Note: In the following, we consider and implement the negative log-likelihood function, since some numerical optimisers that we will see are only able to perform minimisation of functions.

In addition, we implement the score and the observed information (used for comparison with the optimiser output)

nllik_bin <- function(theta, data){
  -sum(data) * log(theta) - (length(data) - sum(data)) * log(1-theta)
}
nllik_bin_rep <- function(param, data) nllik_bin(theta(param), data)
score <- function(theta, data){
  sum(data)/theta - (length(data) - sum(data))/(1 - theta)
}

obs_info <- function(theta, data){
   sum(data)/theta^2 + (length(data) - sum(data))/(1 - theta)^2
}

Numerical optimisation

Binomial example

To check if the score and the observed information are correctly implemented, we can compute the numerical gradient and hessian of the log-likelihood function, as implemented in the {numDeriv} R package.

Important

Note that in this case, we obtain them for the negative log-likelihood function, implying that we need to change sign to the score function.

library(numDeriv)
grad(nllik_bin, 0.5, data = y)
[1] -52
-score(0.5, data = y)
[1] -52
hessian(nllik_bin, 0.5, data = y)
     [,1]
[1,]  400
obs_info(0.5, data = y)
[1] 400

Numerical optimisation

nlm optimiser

Let’s start with the first optimiser nlm (considering as starting value 0.5, which is quite close to the MLE; however, see the warnings printed in the R console)

bin.nlm_start1 <- nlm(f = nllik_bin, p = 0.5,
                       data = y, hessian = TRUE)
bin.nlm_start1
$minimum
[1] 65.89557

$estimate
[1] 0.6299995

$gradient
[1] 1.421085e-08

$hessian
         [,1]
[1,] 429.0957

$code
[1] 1

$iterations
[1] 5
nllik_bin(bin.nlm_start1$estimate, data = y)
[1] 65.89557
obs_info(bin.nlm_start1$estimate, y)
[1] 429

Numerical optimisation

optim optimiser

The previous optimiser does not allow constraints on the parameters; however, there are some replacements in the algorithm that allow you to reach the result. If you want to optimise a function with constrained parameters, it is better to use an optimiser allowing for box-constrained optimisation, as for instance optim.

bin.optim_start1 <- optim(par = 0.5, fn = nllik_bin, hessian = TRUE,
  data = y, method = "L-BFGS-B", lower = 1e-7, upper = 1-1e-7)
bin.optim_start1
$par
[1] 0.6299996

$value
[1] 65.89557

$counts
function gradient 
       7        7 

$convergence
[1] 0

$message
[1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"

$hessian
         [,1]
[1,] 429.0048
bin.optim_start2 <- optim(par = 0.001, fn = nllik_bin,
  data = y, method = "L-BFGS-B", lower = 1e-7, upper =1-1e-7)
bin.optim_start2
$par
[1] 0.6299996

$value
[1] 65.89557

$counts
function gradient 
      12       12 

$convergence
[1] 0

$message
[1] "CONVERGENCE: REL_REDUCTION_OF_F <= FACTR*EPSMCH"
optimHess(bin.optim_start2$par, nllik_bin, data = y)
         [,1]
[1,] 429.0048

Numerical optimisation

Note

  • The optim() function provides a lot of numerical methods (Nelder-Mead, quasi-Newton, conjugate-gradient methods and simulated annealing). As a drawback, the user has to set up carefully the initial guesses and the method, since the final solution may be quite sensitive to these choices…To compute the observed information, the function optimHess() computes numerical derivatives of generic functions.

  • As an alternative, we could consider again the reparametrisation introduced above. Generally, for numerical purposes, it is convenient to reparameterize the model in such a way that the new parameter space is unbounded. Then, we explore this by using nlm()

Numerical optimisation

bin.nlm_start1_rep <- nlm(f = nllik_bin_rep , p = 0,
                          data = y, hessian = TRUE)
bin.nlm_start1_rep
$minimum
[1] 65.89557

$estimate
[1] 0.5322163

$gradient
[1] 2.842171e-08

$hessian
        [,1]
[1,] 23.3094

$code
[1] 1

$iterations
[1] 4
nllik_bin_rep (bin.nlm_start1_rep$estimate, data = y)
[1] 65.89557
c(bin.nlm_start1_rep$estimate, psi(bin.nlm_start1$estimate), psi(mean(y)))
[1] 0.5322163 0.5322147 0.5322168
hessian(nllik_bin_rep, bin.nlm_start1_rep$estimate, data = y)
      [,1]
[1,] 23.31

Likelihood theory: group activity

Waiting times between orders

The model

  • Waiting times (minutes) between consecutive orders, \(Y_i \stackrel{iid}\sim\) Exponential with mean \(\theta\): \(f(y; \theta) = \frac{1}{\theta} e^{-y/\theta}, \ y > 0\) (R uses the rate: rexp(n, rate = 1/theta))
  • Log-likelihood, up to an additive constant: \(\ell(\theta) = -n \log \theta - S/\theta\), with \(S = \sum_{i=1}^n y_i\)
  • Data: \(n = 8\) waiting times (see below); PART 1, 2 and 3 of the R script are completed in teams

Individual predictions (write your answer before touching R)

  • P1. Is the log-likelihood of \(\theta\) symmetric around its maximum?
  • P2. Will the Wald interval (est \(\pm\) 1.96 SE) and the likelihood-ratio interval be the same? If not, which one reaches higher values?
  • P3. For the RATE \(\lambda = 1/\theta\), is the MLE \(1/\bar y\) unbiased?
y <- c(2.1, 9.4, 0.8, 5.6, 14.2, 3.3, 7.9, 1.7)   # minutes between orders
n <- length(y); S <- sum(y)

Likelihood, score and information

PART 1: The log-likelihood

1a. Plot the log-likelihood minus its maximum, over \(\theta \in (2, 20)\)

  • Log-likelihood, up to an additive constant (as in the slides): \(\ell(\theta) = -n \log \theta - S/\theta\)
  • Mark the MLE (find it from the plot, then check in 1b)
ll_exp <- function(theta, n, S) -n * log(theta) - S / theta
th  <- seq(2, 20, length.out = 400)
lln <- sapply(th, ll_exp, n = n, S = S)
plot(th, lln - max(lln), type = "l", lwd = 2, xlab = expression(theta),
     ylab = expression(l(theta) - max(l)))
## add a vertical line at the MLE (find it from the plot, then check in 1b)
TODO
Solution
ll_exp <- function(theta, n, S) -n * log(theta) - S / theta
th  <- seq(2, 20, length.out = 400)
lln <- sapply(th, ll_exp, n = n, S = S)
plot(th, lln - max(lln), type = "l", lwd = 2, xlab = expression(theta),
     ylab = expression(l(theta) - max(l)))
## add a vertical line at the MLE (find it from the plot, then check in 1b)
abline(v = mean(y), col = 2, lty = 2)

PART 1: MLE and likelihood ratio

1b. MLE: numerical maximisation vs the closed form

  • optimize() with maximum = TRUE maximises the log-likelihood directly
opt <- optimize(ll_exp, interval = c(0.1, 100), n = n, S = S, maximum = TRUE)
opt$maximum
TODO          # closed form (the sample mean)
Solution
opt <- optimize(ll_exp, interval = c(0.1, 100), n = n, S = S, maximum = TRUE)
opt$maximum
[1] 5.62498
mean(y)       # closed form (the sample mean)
[1] 5.625

1c. How much more supported is \(\theta = 5\) than \(\theta = 10\)?

TODO          # exp(ll_exp(5, n, S) - ll_exp(10, n, S))
Solution
exp(ll_exp(5, n, S) - ll_exp(10, n, S))
[1] 2.843903

Q1

How many times is \(\theta = 5\) more supported than \(\theta = 10\)? Is it a lot?

PART 1: Same \(n\), same sum

1d. Another sample with the SAME \(n\) and the SAME sum, different values

  • Compute ll_exp for the two samples at \(\theta = 3, 5, 8\). What do you notice?
y2 <- c(5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 10.0)
c(length(y2), sum(y2))
[1]  8 45

Q2

What does 1d tell you about the data needed to build the likelihood? Link it to sufficient statistics (factorization in the slides).

PART 1: Score and observed information

1e. Derive \(U(\theta)\) and \(J(\theta)\) by hand from ll_exp and code them

  • Differentiate once and twice with respect to \(\theta\); \(J(\theta)\) is MINUS the second derivative
  • 1f. At the MLE: the score and the standard error
U <- function(theta, n, S) TODO
J <- function(theta, n, S) TODO       # J = - second derivative

th_hat <- mean(y)
U(th_hat, n, S)
se_obs <- TODO                  # 1 / sqrt(J(th_hat, n, S))
c(se_obs, th_hat / sqrt(n))
Solution
U <- function(theta, n, S) -n / theta + S / theta^2
J <- function(theta, n, S) -n / theta^2 + 2 * S / theta^3   # J = - second derivative

th_hat <- mean(y)
U(th_hat, n, S)
[1] -2.220446e-16
se_obs <- 1 / sqrt(J(th_hat, n, S))
c(se_obs, th_hat / sqrt(n))
[1] 1.988738 1.988738

Q3

Why is the score 0 at the MLE? Is the log-likelihood symmetric (P1)?

Properties of the MLE (simulation)

PART 2: Score and information at the true value

Simulation setup

  • True \(\theta = 5\), samples of size \(n = 8\), \(R = 10000\) replications (each row of Y is one sample)
  • 2a. Evaluate the score and the observed information at the true value, in each sample
set.seed(2026)
R <- 10000; theta_t <- 5
Y <- matrix(rexp(n * R, rate = 1 / theta_t), nrow = R)    # each row = one sample
Ssim <- rowSums(Y)

U_t <- U(theta_t, n, Ssim)
J_t <- J(theta_t, n, Ssim)
c(mean(U_t), var(U_t))        # expected score; variance of the score
[1] -0.001857266  0.317924057
c(mean(J_t), n / theta_t^2)   # mean observed information vs n/theta^2
[1] 0.3192571 0.3200000

Q4

What is \(E(U)\) at the true value? What is \({\rm var}(U)\)? Which identity of the slides is this? Same question for mean(J_t).

PART 2: Cramér-Rao lower bound

2b. Two UNBIASED estimators of \(\theta\)

  • The MLE (sample mean) and \(n \cdot \min(y_i)\)
  • Compare their means and variances with the Cramér-Rao bound \(\mathcal{I}(\theta)^{-1} = \theta^2/n\)
est_mle <- rowMeans(Y)
est_min <- n * apply(Y, 1, min)
rbind(mean = c(mean(est_mle), mean(est_min)),
      var  = c(var(est_mle),  var(est_min)))
TODO                          # compute the Cramer-Rao bound theta^2 / n
Solution
est_mle <- rowMeans(Y)
est_min <- n * apply(Y, 1, min)
rbind(mean = c(mean(est_mle), mean(est_min)),
      var  = c(var(est_mle),  var(est_min)))
         [,1]      [,2]
mean 4.994196  4.974248
var  3.104727 24.787080
theta_t^2 / n                 # Cramer-Rao bound theta^2 / n
[1] 3.125

Q5

Which of the two unbiased estimators has smaller variance? Does the MLE reach the Cramér-Rao bound? Does the other estimator violate it?

PART 2: Invariance of the MLE

2c. Estimate the RATE \(\lambda = 1/\theta\)

  • By plugging in: \(\hat \lambda = 1/\bar y\). Is it unbiased? (true \(\lambda = 0.2\))
mean(1 / est_mle)
[1] 0.2288856
mean((n - 1) / Ssim)          # another estimator of lambda: what is it doing?
[1] 0.2002749

Q6

Is \(1/\bar y\) unbiased for \(\lambda\)? Why can the MLE of a function (plug-in rule) be biased even if the MLE of \(\theta\) is not?

PART 2: Sampling distribution of the MLE

Q7

What changes when \(n\) grows? Which property of the MLE is this?

par(mfrow = c(1, 3))
for (nn in c(5, 50, 500)) {
  m <- replicate(5000, mean(rexp(nn, rate = 1 / theta_t)))
  hist(m, prob = TRUE, breaks = 40, main = paste("n =", nn), xlab = "MLE of theta")
  curve(dnorm(x, theta_t, theta_t / sqrt(nn)), add = TRUE, col = 2, lwd = 2)
}
par(mfrow = c(1, 1))

Tests and confidence intervals

PART 3: Four 95% confidence intervals

3a. Back to the observed data: \(n = 8\), \(\hat \theta = \bar y\)

  • Wald: \(\hat \theta \pm 1.96 \, \hat \theta/\sqrt{n}\); Wald on the log scale: Wald interval for \(\log \theta\), then exp()
  • LRT: \(\{\theta: W(\theta) \leq \chi^2_{1; 0.95}\}\), with \(W(\theta) = 2\{\ell(\hat \theta) - \ell(\theta)\}\)
  • Exact: \(2S/\theta \sim \chi^2_{2n}\)
q95 <- qchisq(0.95, 1)
W   <- function(theta) 2 * (ll_exp(th_hat, n, S) - ll_exp(theta, n, S))   # LRT statistic

ci_wald  <- th_hat + c(-1, 1) * 1.96 * th_hat / sqrt(n)
ci_wlog  <- TODO               # Wald on log(theta), then exp(): th_hat * exp(c(-1, 1) * 1.96 / sqrt(n))
ci_lrt   <- c(uniroot(function(t) W(t) - q95, c(0.5, th_hat))$root,
              uniroot(function(t) W(t) - q95, c(th_hat, 100))$root)
ci_exact <- 2 * S / qchisq(c(0.975, 0.025), df = 2 * n)    # exact result
rbind(wald = ci_wald, wald_log = ci_wlog, lrt = ci_lrt, exact = ci_exact)
Solution
q95 <- qchisq(0.95, 1)
W   <- function(theta) 2 * (ll_exp(th_hat, n, S) - ll_exp(theta, n, S))   # LRT statistic

ci_wald  <- th_hat + c(-1, 1) * 1.96 * th_hat / sqrt(n)
ci_wlog  <- th_hat * exp(c(-1, 1) * 1.96 / sqrt(n))       # Wald on log(theta), then exp()
ci_lrt   <- c(uniroot(function(t) W(t) - q95, c(0.5, th_hat))$root,
              uniroot(function(t) W(t) - q95, c(th_hat, 100))$root)
ci_exact <- 2 * S / qchisq(c(0.975, 0.025), df = 2 * n)    # exact result
rbind(wald = ci_wald, wald_log = ci_wlog, lrt = ci_lrt, exact = ci_exact)
             [,1]      [,2]
wald     1.727074  9.522926
wald_log 2.813013 11.247947
lrt      3.021877 12.308969
exact    3.120087 13.029006

PART 3: The LRT and Wald intervals on the log-likelihood

Q8

Which interval is symmetric? Which are not? Does it match P1-P2?

plot(th, lln - max(lln), type = "l", lwd = 2, xlab = expression(theta),
     ylab = expression(l(theta) - max(l)))
abline(h = -q95 / 2, col = 2)
abline(v = ci_lrt, col = 2, lty = 2)
abline(v = ci_wald, col = 4, lty = 2)

PART 3: Three tests

3b. \(H_0: \theta = 10\) (minutes) vs \(H_1: \theta \neq 10\)

  • LRT: \(W(\theta_0)\); Wald: \((\hat \theta - \theta_0)^2 J(\hat \theta)\); Score: \(U(\theta_0)^2/\mathcal{I}(\theta_0)\), with \(\mathcal{I}(\theta) = n/\theta^2\)
  • Under \(H_0\), the three statistics are approximately \(\chi^2_1\)
theta0 <- 10
W_lrt   <- W(theta0)
W_wald  <- n * (th_hat - theta0)^2 / th_hat^2        # (th_hat - theta0)^2 * J(th_hat)
W_score <- U(theta0, n, S)^2 / (n / theta0^2)        # U(theta0)^2 / I(theta0), with I = n / theta^2
stat <- c(LRT = W_lrt, Wald = W_wald, Score = W_score)
rbind(stat = stat, p_value = pchisq(stat, df = 1, lower.tail = FALSE))
              LRT       Wald     Score
stat    2.2058263 4.83950617 1.5312500
p_value 0.1374902 0.02781486 0.2159249

Q9

Do the three tests lead to the same decision at level 5%? Which interval agrees with the Wald test, which with the LRT? (Is \(\theta_0 = 10\) inside each interval?)

PART 3: Coverage in repeated sampling

3c. \(n = 8\), true \(\theta = 5\), \(10^5\) samples

  • A CI covers \(\theta_t\) exactly when the corresponding test does NOT reject it
set.seed(1)
Rr <- 1e5
Sx <- rgamma(Rr, shape = n, scale = theta_t)         # sum of n exponentials
hx <- Sx / n                                         # MLEs
cov_wald  <- abs(hx - theta_t) <= 1.96 * hx / sqrt(n)
cov_wlog  <- TODO       # abs(log(hx) - log(theta_t)) <= 1.96 / sqrt(n)
cov_lrt   <- 2 * n * (log(theta_t / hx) + hx / theta_t - 1) <= q95    # LRT statistic at theta_t <= q95
cov_exact <- (2 * Sx / theta_t >= qchisq(0.025, 2 * n)) & (2 * Sx / theta_t <= qchisq(0.975, 2 * n))
c(wald = mean(cov_wald), wald_log = mean(cov_wlog), lrt = mean(cov_lrt), exact = mean(cov_exact))
Solution
set.seed(1)
Rr <- 1e5
Sx <- rgamma(Rr, shape = n, scale = theta_t)         # sum of n exponentials
hx <- Sx / n                                         # MLEs
cov_wald  <- abs(hx - theta_t) <= 1.96 * hx / sqrt(n)
cov_wlog  <- abs(log(hx) - log(theta_t)) <= 1.96 / sqrt(n)
cov_lrt   <- 2 * n * (log(theta_t / hx) + hx / theta_t - 1) <= q95    # LRT statistic at theta_t <= q95
cov_exact <- (2 * Sx / theta_t >= qchisq(0.025, 2 * n)) & (2 * Sx / theta_t <= qchisq(0.975, 2 * n))
c(wald = mean(cov_wald), wald_log = mean(cov_wlog), lrt = mean(cov_lrt), exact = mean(cov_exact))
    wald wald_log      lrt    exact 
 0.89481  0.93915  0.94768  0.94985 

Q10

Which interval is closest to 95%? Why does the Wald interval undercover? Repeat with \(n = 30\) and \(n = 100\): what happens?

PART 3: Questions and discussion

Q11

The LRT interval for the rate \(\lambda = 1/\theta\) is just \(1/\)(its interval for \(\theta\)); this is NOT true for the Wald interval. What property of the LRT is this? Why do the LRT and Wald-on-log nearly coincide here?

Discussion (reporter of each team)

  • Which of your three predictions was wrong, and what did it teach you?
  • If you had only one interval to report for \(n = 8\), which one and why?