Generalized linear mixed models
Binary responses and counts can vary with observed covariates while also reflecting differences between clusters. Observations from the same cluster may resemble one another because they share a response tendency that the covariates do not explain. A regression analysis must then account for both the possible values of each response and the association within clusters. A generalized linear mixed model (GLMM) expresses the covariate relationship at given cluster effects, while the distribution of those effects describes variation between clusters. The chapter uses the simulated GLMM80 data throughout and compares three ways of handling the integral over the random effects: quadrature, the Laplace approximation and penalized quasi-likelihood.
9.1 Logistic and Poisson models with random intercepts and slopes
The simulated GLMM80 data have 80 independent clusters, each with eight responses ordered by covariate value. In cluster $i$, let $y_i$ collect the responses in that order. The matrices $X_i$ and $Z_i$ give the design rows for the fixed coefficients $\beta$ and the vector of shared normal random effects $b_i$ with mean zero. The vector $o_i$ contains the known offsets, each added with coefficient one. At observation $j$, write the design rows as $x_{ij}^{\top}$ and $z_{ij}^{\top}$. The linear predictor is
For a logistic response, $Y_{ij}$ is Bernoulli with conditional success probability $p_{ij}=1/(1+e^{-\eta_{ij}})$, so $\eta_{ij}=\log\lbrace p_{ij}/(1-p_{ij})\rbrace $ is the conditional log odds. In the random-intercept model, $\beta_0$ is the log odds at covariate zero, offset zero and random intercept zero. The mean-zero deviation $b_{i0}$ shifts that log odds, making $\beta_0+b_{i0}$ the cluster-specific intercept. Take $\beta=(\beta_0,\beta_1)^\top=(-0.4,0.8)^\top$. The first observation has fixed design row $(1,-1)$, random intercept design row $(1)$, and offset zero. Its linear predictor is $-0.4+0.8(-1)+b_{10}=-1.2+b_{10}$.
With the random intercept and offset fixed, a one-unit covariate increase adds $\beta_1$ to the log odds and multiplies the odds by $\exp(\beta_1)$. A random slope adds a second column to $Z_i$. With row $(1,x)$ at covariate value $x$, the cluster-specific log-odds slope is $\beta_1+b_{i1}$ and its conditional odds ratio is $\exp(\beta_1+b_{i1})$. Here $\beta_1$ is the mean of the cluster slopes on the log-odds scale. A positive slope deviation lowers the linear predictor at $x=-1$ and raises it at $x=1$. Averaging probabilities over the random-effect distribution generally gives a different marginal relationship; setting the deviations to zero does not perform that averaging.
For a Poisson response, $Y_{ij}$ is a count whose conditional mean and variance both equal $\mu_{ij}=\exp(\eta_{ij})$. In the random-intercept model, $\beta_0$ is the log expected count at covariate zero, offset zero and random intercept zero. At the same exposure and random intercept, a one-unit covariate increase multiplies the expected count by $\exp(\beta_1)$. If the offset is the log of an observed exposure, the expected count is that exposure times $\exp(\beta_0+\beta_1x+b_{i0})$. The latter expression is the conditional rate per exposure unit, and $b_{i0}$ shifts its logarithm. Thus the coefficient compares conditional rates when exposure differs.
For each observed design, assume $b_i\sim N_q(0,G)$. In the logistic model with a random intercept and slope, $G_{11}$ measures between-cluster variation in the log-odds intercept, $G_{22}$ variation in the log-odds change per unit of the covariate, and $G_{21}$ their covariance. Their units are squared log odds, squared log odds per squared covariate unit, and squared log odds per covariate unit, respectively. A positive covariance associates higher intercepts with larger slopes. In the Poisson random-intercept model, $G_{11}$ is the variance of the log-mean intercept, or of the log-rate intercept when an exposure offset is present. These variances describe differences between clusters; the conditional response variances remain $p_{ij}(1-p_{ij})$ and $\mu_{ij}$ in the two models.
In both models, assume independence across clusters and conditional independence of responses within a cluster given its shared effects and design. For repeated responses from a person, the person is the cluster. The Bernoulli or Poisson distribution specifies the remaining response variation at given effects. From the book directory, load the functions for the grouped design and the numerical calculations.
1
2
3
4
5
6
7
.libPaths(c(".R-library", .libPaths()))
for (file in c("result", "stability", "families", "logit", "differentiation",
"line_search",
"quasi_newton", "newton", "glm", "transforms", "simulation", "em", "factor", "sem",
"lmm", "dogleg", "lmm_fast", "lmm_profile", "integration")) {
source(paste0("code/lib/", file, ".R"))
}
Grouping and generating the data
The constructor glmm_data() groups responses, design rows and offsets by cluster and checks which response values the family permits. Here family = "binomial" accepts individual Bernoulli observations coded 0 or 1; this constructor has no trials argument for grouped binomial counts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
glmm_data <- function(y, X, Z, id, family = "binomial", offset = rep(0, length(y))) {
stopifnot(family %in% c("binomial", "poisson", "normal"),
length(offset) == length(y), all(is.finite(offset)))
if (family == "binomial") stopifnot(all(y %in% 0:1))
if (family == "poisson") stopifnot(all(y >= 0), all(y == floor(y)))
d <- lmm_design(y, X, Z, id)
d$family <- family
d$offset <- offset
# Number the clusters by first appearance.
appearance <- unique(as.character(id))
d$blocks <- d$blocks[match(appearance, vapply(d$blocks, `[[`, "", "id"))]
d$group_index <- match(as.character(id), appearance)
# Retain each observation's exposure offset when the design is split by group.
d$blocks <- lapply(d$blocks, function(b) { b$offset <- offset[b$rows]; b })
d
}
Clusters are numbered by first appearance. The saved row indices in b$rows recover the offsets in the same order as the observations, even when rows from different clusters are interleaved. The constructor calls lmm_design() to group the corresponding rows of the responses and both designs.
The following generator draws shared effects for each cluster and then conditionally independent binary responses or counts at the specified covariate rows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
glmm_generate <- function(m = 80L, n = 8L, beta = c(-.4, .8),
G = matrix(.49), family = "binomial", observation_sd = 0) {
x <- seq(-1, 1, length.out = n)
Z <- if (nrow(G) == 1L) matrix(1, n, 1) else cbind(1, x)
# Each row is one draw with covariance G.
b <- matrix(rnorm(m * nrow(G)), m) %*% chol(G)
extra <- if (observation_sd > 0) matrix(rnorm(m * n, 0,
observation_sd), m) else matrix(0, m, n)
eta <- matrix(rep(beta[1] + beta[2] * x, each = m), m) + b %*% t(Z) + extra
Y <- if (family == "binomial") matrix(as.numeric(runif(m * n) < plogis(eta)), m) else
matrix(rpois(m * n, exp(eta)), m)
# Stack observations group by group to keep their IDs aligned.
observed <- data.frame(id = rep(seq_len(m), each = n), x = rep(x, m),
y = as.vector(t(Y)))
list(observed = observed, truth = list(beta = beta, G = G, b = b,
observation_sd = observation_sd, extra = extra), family = family,
random_slope = nrow(G) == 2L)
}
In glmm_generate(), each row of b is one draw for a cluster. Multiplication by the transposed random effect design applies that draw to all eight linear predictors. A random intercept shifts them equally. The random slope contribution also depends on the covariate, through the second column of the design. Given these linear predictors, separate uniform draws generate the binary responses, or separate Poisson draws generate the counts.
The generator stores the generating coefficients and covariance together with the realized random effects in truth, separate from the observed identifiers, covariates, and responses. To construct the integrand for the data available to an analyst, glmm_as_data() rebuilds the design from those observations and the model’s random slope specification.
1
2
3
4
5
6
glmm_as_data <- function(input) {
observed <- input$observed
X <- cbind(intercept = 1, x = observed$x)
Z <- if (!input$random_slope) matrix(1, nrow(X), 1) else X
glmm_data(observed$y, X, Z, observed$id, input$family)
}
Seed 901 generates binary responses with random intercept variance 0.49. The design for seed 902 also has a random slope with variance 0.16 and covariance 0.08 with the random intercept. Seed 903 generates counts from the Poisson mixed model with a log link function, fixed intercept 0.2 and slope 0.5. Each design has 80 clusters observed eight times. A cluster has one random effect in the first and third designs and two in the second.
1
2
3
4
5
6
7
8
9
10
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(901)
binary_input <- glmm_generate()
set.seed(902)
slope_input <- glmm_generate(G = matrix(c(.49, .08, .08, .16), 2))
set.seed(903)
count_input <- glmm_generate(beta = c(.2, .5), family = "poisson")
binary <- glmm_as_data(binary_input)
slope <- glmm_as_data(slope_input)
count <- glmm_as_data(count_input)
Summing the responses gives the number of successes or events in each simulated dataset.
1
2
3
4
5
print(data.frame(example_model = c("random-intercept logistic regression",
"random-intercept and slope logistic regression",
"random-intercept Poisson regression"), clusters = 80,
responses = 640, number_of_random_effects = c(1, 2, 1),
response_sum = c(sum(binary$y), sum(slope$y), sum(count$y))))
1
2
3
4
example_model clusters responses number_of_random_effects response_sum
1 random-intercept logistic regression 80 640 1 293
2 random-intercept and slope logistic regression 80 640 2 289
3 random-intercept Poisson regression 80 640 1 1284
The cluster counts, response counts and numbers of random effects in this summary come from the design. Only the last column sums observations. It gives 293 and 289 successes in the two binary datasets and 1284 events in the count data.
Conditional log probabilities and the cluster integrand
To derive the conditional log probabilities and their derivatives, first consider a Bernoulli observation. Suppress the indices and write $p$ for its conditional success probability. A success contributes $p$ and a failure contributes $1-p$. Taking the logarithm of $p^y(1-p)^{1-y}$ and substituting the logistic probability gives the conditional log probability $a$. Differentiating with respect to $\eta$ gives the observed response minus its conditional mean. Since $dp/d\eta=p(1-p)$, a second differentiation gives
\[a=y\eta-\log(1+e^\eta),\qquad \frac{\partial a}{\partial\eta}=y-p,\qquad -\frac{\partial^2 a}{\partial\eta^2}=p(1-p).\]For a Poisson count with $\log\mu=\eta$, taking the log of $e^{-\mu}\mu^y/y!$ gives
\[a=y\eta-e^\eta-\log(y!),\qquad \frac{\partial a}{\partial\eta}=y-\mu,\qquad -\frac{\partial^2 a}{\partial\eta^2}=\mu.\]The factorial contributes to the probability of the observed count and drops out of both derivatives. At a fixed rate, adding $\log 2$ for twice the exposure gives $e^{\eta+\log 2}=2e^\eta$. The following function evaluates these conditional log probabilities, means and derivatives, with a unit-variance normal case for later checks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
glmm_response <- function(y, eta, family) {
if (family == "binomial") {
mu <- plogis(eta)
# Evaluate 1 - p as the opposite logistic tail for extreme linear predictor values.
w <- mu * plogis(-eta)
return(list(log_density = -y * log1pexp(-eta) - (1 - y) * log1pexp(eta),
mu = mu, residual = y - mu, weight = w, third = w * (1 - 2 * mu)))
}
if (family == "poisson") {
mu <- exp(eta)
return(list(log_density = y * eta - mu - lgamma(y + 1),
mu = mu, residual = y - mu, weight = mu, third = mu))
}
list(log_density = dnorm(y, eta, 1, log = TRUE), mu = eta,
residual = y - eta, weight = eta * 0 + 1, third = eta * 0)
}
In glmm_response(), residual is the observed response minus its conditional mean at the specified random effects, which is the first derivative for either family. The field weight is the negative second derivative, and third is the derivative of that weight, hence $-\partial^3 a/\partial\eta^3$, not the third derivative of $a$ itself. These identities use the logit and log links specified here. The response weight is a conditional variance and is distinct from a quadrature weight. For the logistic model, log1pexp() (Section 1.1) gives $\log(1+e^t)$, and plogis(-eta) computes the failure probability directly when the success probability is close to one. For a count, lgamma(y + 1) supplies $\log(y!)$. For a normal response, the function uses unit conditional variance. The returned log_density is a log probability mass for binary responses and counts, and a log density for normal responses. The stable formulas reduce cancellation but do not make exponentiation finite for every input.
With the design fixed, the eight observations are conditionally independent given their shared $b_i$. Write $a_{ij}(b_i)$ for their individual log probabilities at that value. To find the probability of the observed response vector, multiply its eight conditional probabilities before averaging over the distribution of $b_i$.
Choose a lower triangular Cholesky factor $L$ with $G=LL^\top$. Write $b_i=Lz_i$, where the standardized random vector $z_i$ has the $q$-dimensional standard normal density $\phi_q$. An integration point $z$ is a possible value of $z_i$, whereas the design row $z_{ij}^{\top}$ is fixed by the observation. For fixed designs, offsets, $\beta$, and $G$, the contribution of cluster $i$ to the marginal likelihood is the probability that its response vector $Y_i$ takes the observed value $y_i$.
\[\begin{aligned} P(Y_i=y_i)&=\int_{\mathbb R^q}\left[\prod_{j=1}^{8}e^{a_{ij}(Lz)}\right]\phi_q(z)\,dz =\int_{\mathbb R^q}e^{h_i(z)}\,dz,\\ h_i(z)&=\sum_{j=1}^{8}a_{ij}(Lz)+\log\phi_q(z). \end{aligned}\]Set $A=Z_iL$. Changing $z$ by a vector $d$ changes the eight linear predictors by $Ad$. In the gradient, the chain rule multiplies each residual by its row of $A$. Differentiating again weights the outer product of each row with itself by the corresponding conditional response variance. Let $\mu_i$ collect the conditional means at $z$, let $W_i$ be the diagonal matrix of the eight weights, and let $I_q$ denote the identity matrix. Differentiating $\log\phi_q(z)$ supplies the final terms in the gradient and negative Hessian below. For these canonical response models at finite linear predictors, $-\nabla^2 h_i(z)=I_q+A^\top W_iA$ is positive definite because $W_i$ has nonnegative diagonal entries. Thus the log joint density is strictly concave in $z$, including for an all-zero or all-one binary cluster.
\[\nabla h_i(z)=A^\top(y_i-\mu_i)-z,\qquad -\nabla^2 h_i(z)=A^\top W_i A+I_q.\]Evaluating $h_i(0)$ gives the joint log density of the observed responses and the standardized effects at $z=0$. Taking the logarithm after integration gives the log probability of the observed responses. These log probabilities add across the 80 independent clusters.
The object returned by glmm_data() stores the observations and design, while glmm_integrand() also receives the candidate coefficients beta and lower Cholesky factor L. For cluster $i$, these inputs correspond to the model as follows.
| Input | Model quantity |
|---|---|
block$y, block$X, block$Z | $y_i$, $X_i$ and $Z_i$ in their common observation order |
block$offset | Known offset vector $o_i$ |
family | The conditional response distribution stored in the parent data object |
beta | Fixed coefficient vector $\beta$ |
L | Factor of the random-effect covariance $G=LL^\top$ |
Argument z of the returned functions | Standardized random effects, giving $b_i=Lz$ |
These values of beta and L remain fixed while the returned functions vary z; a new parameter trial requires a new integrand. The function below provides the conditional log probability, log joint density and derivatives for this one cluster.
1
2
3
4
5
6
7
8
9
10
11
12
glmm_integrand <- function(block, beta, L, family) {
A <- block$Z %*% L
fixed <- drop(block$X %*% beta) + block$offset
terms <- function(z) glmm_response(block$y, fixed + drop(A %*% z), family)
response <- function(z) sum(terms(z)$log_density)
h <- function(z) response(z) + sum(dnorm(z, log = TRUE))
# The standard normal log density contributes -z to the gradient and -I to the Hessian.
gr <- function(z) drop(crossprod(A, terms(z)$residual)) - z
he <- function(z) {
H <- crossprod(A, terms(z)$weight * A)
-(H + t(H)) / 2 - diag(ncol(A))
}
The standard normal density for z enters through dnorm() in h, rather than through an extra field in the data object. In glmm_integrand(), fixed contains the fixed parts of the linear predictors, including the offsets, for one cluster. The function response() adds the log probabilities at a specified $z$, and h() adds the normal log density. The function he() returns the Hessian, so its negative is the positive definite matrix that determines the width of the local quadratic approximation. Subsequent uses of curvature in the mode calculation refer to this negative Hessian.
The next component evaluates changes from a reference point. Its difference helper is defined after the first numerical examples; those examples use the probability and derivative functions above.
1
2
3
4
5
6
7
8
9
centered <- function(anchor) {
eta <- fixed + drop(A %*% anchor)
function(z) {
# Convert a change in the standardized effects to changes in the linear predictors.
delta <- z - anchor
sum(glmm_log_density_change(block$y, eta, drop(A %*% delta), family)) -
sum(anchor * delta) - sum(delta^2) / 2
}
}
The final component evaluates several integration points together, using one point per input row. These additional components will support the quadrature calculations in Section 9.3.
1
2
3
4
5
6
7
8
9
10
11
at_nodes <- function(nodes, joint = TRUE) {
# Each column holds all observations at one integration point.
eta <- fixed + A %*% t(nodes)
value <- colSums(matrix(glmm_response(block$y, eta, family)$log_density,
length(block$y)))
if (joint) value <- value + rowSums(matrix(dnorm(nodes, log = TRUE), nrow(nodes)))
value
}
list(response = response, h = h, gr = gr, he = he, centered = centered,
at_nodes = at_nodes, dimension = ncol(A))
}
Evaluating the integrand at specified values
For the first binary cluster, set $L=0.7$, the random intercept standard deviation, and evaluate its responses at $z=0$.
1
2
3
4
5
6
7
u_true <- c(-.4, .8, log(.7))
first <- glmm_integrand(binary$blocks[[1]], u_true[1:2], matrix(.7), "binomial")
block <- binary$blocks[[1]]
eta0 <- drop(block$X %*% c(-.4, .8)) + block$offset
at_zero <- glmm_response(block$y, eta0, "binomial")
print(data.frame(observation = block$rows, x = block$X[, 2], offset = block$offset,
y = block$y, probability = at_zero$mu, log_mass = at_zero$log_density))
1
2
3
4
5
6
7
8
9
observation x offset y probability log_mass
1 1 -1.0000000 0 0 0.2314752 -0.2632825
2 2 -0.7142857 0 0 0.2745958 -0.3210263
3 3 -0.4285714 0 0 0.3223797 -0.3891682
4 4 -0.1428571 0 0 0.3741894 -0.4687075
5 5 0.1428571 0 1 0.4290534 -0.8461739
6 6 0.4285714 0 1 0.4857182 -0.7221267
7 7 0.7142857 0 1 0.5427525 -0.6111019
8 8 1.0000000 0 0 0.5986877 -0.9130153
The eight success probabilities range from 0.231 to 0.599. In the first row, the linear predictor is $-1.2$ and the response is zero. Its log probability is therefore $\log(1-0.2314752)$, which gives $-0.2632825$ to the precision shown. Summing the conditional log probabilities of the eight observed responses gives the first quantity below.
1
2
3
4
print(c(conditional_log_probability_at_zero = first$response(0),
normal_log_density_at_zero = dnorm(0,log=TRUE),
joint_log_density_at_zero = first$h(0), log_integrand_derivative_at_zero = first$gr(0),
negative_log_integrand_second_derivative_at_zero = -first$he(0)[1]))
1
2
3
4
5
6
conditional_log_probability_at_zero normal_log_density_at_zero
-4.5346022 -0.9189385
joint_log_density_at_zero log_integrand_derivative_at_zero
-5.4535407 -0.1811963
negative_log_integrand_second_derivative_at_zero
1.8883238
The conditional log probability of the pattern is $-4.53460$. Adding the normal log density $-0.91894$ gives $h_i(0)=-5.45354$. The derivative with respect to the standardized intercept is $0.7\sum_j(y_{ij}-p_{ij})=-0.18120$. Its sign means that a small increase from zero reduces the joint log density. The negative second derivative is $0.49\sum_j p_{ij}(1-p_{ij})+1=1.88832$, including one unit of curvature from the standard normal density. The probability of the responses depends on the area under the integrand.
The offset and the random intercept both enter the linear predictor additively, but the exposure is observed. With the other terms of the linear predictor summing to 0.2, the following calculation changes only the exposure.
1
2
3
exposure <- c(1,2)
print(data.frame(exposure,offset=log(exposure),
expected_count=glmm_response(c(1,1),.2+log(exposure),"poisson")$mu))
1
2
3
exposure offset expected_count
1 1 0.0000000 1.221403
2 2 0.6931472 2.442806
Increasing the exposure from one to two raises the expected count from 1.22140 to 2.44281 at the same rate.
To see what averaging over an unobserved intercept does, consider two binary observations whose linear predictors have the common fixed part $-0.4$. Both have conditional success probability $p$ at the same intercept. Their joint success probability given that intercept is $p^2$. The 31 Gauss-Hermite quadrature points and weights from normal_rule() approximate this average over an intercept with standard deviation 0.7. Squaring the average of $p$ instead gives the probability of two successes for observations with independent draws of the intercept.
1
2
3
4
5
6
7
8
9
# With identical linear predictors, the difference between the two joint probabilities
# is the variance of the conditional success probability over random intercepts.
# Scale the standard normal points by the random intercept standard deviation.
rule_pair <- normal_rule(31)
p_pair <- plogis(-.4+.7*rule_pair$nodes)
p_marginal <- sum(rule_pair$weights*p_pair)
print(c(two_successes_shared=sum(rule_pair$weights*p_pair^2),
two_successes_independent=p_marginal^2,
variance=sum(rule_pair$weights*(p_pair-p_marginal)^2)))
1
2
two_successes_shared two_successes_independent variance
0.19243836 0.16881469 0.02362366
Sharing the intercept raises the joint success probability from 0.168815 to 0.192438. The difference, 0.023624, is $E(p^2)-[E(p)]^2$, the variance of the conditional success probability across intercepts.
If $L=0$, every standardized draw gives the same linear predictor. This gives a direct check with the original eight responses.
1
2
3
no_effect <- glmm_integrand(block, c(-.4, .8), matrix(0), "binomial")
print(c(GLM_log_probability = sum(at_zero$log_density),
integrated_at_zero_variance = no_effect$response(0)))
1
2
GLM_log_probability integrated_at_zero_variance
-4.534602 -4.534602
At zero variance, no_effect$response(0) gives the constant conditional log probability. The standard normal density integrates to one, so the marginal log probability equals the ordinary logistic regression value of $-4.534602$.
Changes between integration points
The first cluster calculations used the integrand at a single point, and the paired-response example averaged probabilities across points. The remaining integrand components make repeated evaluations and small changes between points more reliable.
To compare two nearby points in that integral, let $\delta$ be the change in one observation’s linear predictor from its value $\eta$ at the starting point. For the logistic response, the ratio $(1+e^{\eta+\delta})/(1+e^\eta)$ equals $1+p(e^\delta-1)$. Thus the change in log probability is $y\delta-\log[1+p(e^\delta-1)]$. For $\vert \delta\vert <0.5$, glmm_log_density_change() evaluates the second term with expm1() and log1p(), which preserve small changes that subtraction of nearly equal values can lose. The Poisson calculation uses $e^\eta(e^\delta-1)$ for the change in the conditional mean.
1
2
3
4
5
6
7
8
9
10
glmm_log_density_change <- function(y, eta, delta, family) {
if (family == "normal") return(-delta * (eta - y) - delta^2 / 2)
if (family == "poisson") return(y * delta - expm1(delta) * exp(eta))
# Binomial: the change of log(1 + exp(eta)); a small change is computed without
# subtracting close logarithms.
small <- abs(delta) < .5
difference <- ifelse(small, log1p(plogis(eta) * expm1(delta)),
log1pexp(eta + delta) - log1pexp(eta))
y * delta - difference
}
With a reference point $z_0$ and displacement $d=z-z_0$, the changes in the linear predictors are the entries of $Ad$. The function returned by centered() sums their log probability changes and adds $-z_0^\top d-d^\top d/2$, the change in the normal log density. The result is $h_i(z)-h_i(z_0)$. The argument named anchor supplies this reference point. Subtracting a function value here does not mean centering observations by their sample mean.
For several integration points, at_nodes() takes one point per input row. Multiplying by the transposed points gives a matrix of linear predictor values with eight rows, one per observation, and one column per point. Each column sum then covers one response vector. For the joint density, add the standard normal log density once per point. When the weights already integrate over the standard normal distribution, use joint = FALSE. Exponentiating its returned values then gives the conditional probabilities to average.
The lme4 package fits logistic and Poisson mixed models with random intercepts and slopes.
9.2 Observation-level random effects and overdispersion
Even at the same exposure and covariate value, two observations can have different underlying Poisson rates. How much variation does that add to their counts? For observation $j$ in cluster $i$, write $f_{ij}=x_{ij}^\top\beta+o_{ij}$ for the fixed part of its log mean, including the known offset. Suppose a normal term $u_{ij}$ with mean zero and variance $v$ adds to this fixed part. Its variance is on the log-mean scale; count variability must be obtained from the resulting response distribution. Given $u_{ij}$, the count $Y_{ij}$ is Poisson with mean and variance both equal to $\lambda_{ij}=\exp(f_{ij}+u_{ij})$. The normal moment $E(e^{tu_{ij}})=e^{t^2v/2}$ at $t=1$ gives the marginal mean $\mu_{ij}=E(\lambda_{ij})=\exp(f_{ij}+v/2)$. At $t=2$, it gives $E(\lambda_{ij}^2)=\mu_{ij}^2e^v$. By the law of total variance,
\[\begin{aligned} \operatorname{Var}(Y_{ij}) &=E\{\operatorname{Var}(Y_{ij}\mid u_{ij})\} +\operatorname{Var}\{E(Y_{ij}\mid u_{ij})\}\\ &=\mu_{ij}+\mu_{ij}^2(e^v-1). \end{aligned}\]The first term is the average conditional Poisson variance. The second measures variation in the conditional means. When $v>0$, the marginal variance exceeds the marginal mean at the given covariate value. This is overdispersion relative to the Poisson distribution.
The variance of one count depends on how much its log mean varies. For two counts in the same cluster, their covariance depends on which part of that variation they share. Write $u_{ij}=b_{i0}+e_{ij}$, where the shared random intercept $b_{i0}$ has variance $\sigma_b^2$ and the observation-level random effect $e_{ij}$ has variance $\sigma_e^2$. These effects have normal distributions with mean zero. The observation-level effects are independent across observations and independent of the shared intercept, so $v=\sigma_b^2+\sigma_e^2$. For distinct observations $j$ and $k$, the counts are independent given the effects. Their expected product therefore equals $E(\lambda_{ij}\lambda_{ik})$. The product of their conditional means contains $e^{2b_{i0}}$ because the same intercept occurs twice. The two observation-level terms each occur once and their expectations multiply. Consequently,
\[\begin{aligned} E(\lambda_{ij}\lambda_{ik}) &=e^{f_{ij}+f_{ik}}e^{2\sigma_b^2}e^{\sigma_e^2} =\mu_{ij}\mu_{ik}e^{\sigma_b^2},\\ \operatorname{Cov}(Y_{ij},Y_{ik}) &=\mu_{ij}\mu_{ik}\bigl(e^{\sigma_b^2}-1\bigr). \end{aligned}\]At fixed marginal means, only the shared variance determines how large this covariance is. At fixed conditional regression coefficients and offsets, increasing the observation-level variance also raises both marginal means. It then increases an existing positive covariance. If the shared variance is zero, the covariance is zero at every observation-level variance.
In the simulated GLMM80 count data, each cluster has eight observations whose linear predictors have fixed parts $0.2+0.5x$ and a shared random intercept with standard deviation 0.7. A second dataset uses the same covariate rows and an independent normal effect with standard deviation 0.4 for each observation. With seed 904, glmm_generate() draws new effects and counts for all 80 clusters.
1
2
set.seed(904)
extra_input <- glmm_generate(beta = c(.2, .5), family = "poisson", observation_sd = .4)
The first cluster in this second dataset has counts $(2,2,4,3,2,3,5,9)$. The first count of two occurs at $x=-1$, so the fixed part of its linear predictor is $0.2+0.5(-1)=-0.3$. To evaluate the probability of the whole vector, poisson_olre_integral() takes the observed counts, the fixed parts of their linear predictors and the two standard deviations. The olre part of its name abbreviates observation-level random effects. The call uses 61 standard normal quadrature points for each one-dimensional integral. This function evaluates a probability at supplied standard deviations; it does not estimate the observation-level variance.
Why can the function use one-dimensional integrals when the cluster has nine random effects? At a given outer point, the shared intercept $b$ has one value for all eight counts. Each count still has its own independent observation-level effect to average over. Let $p_j(y_j\mid b,e)$ be its conditional Poisson probability at the observed count $y_j$. Writing $E_e$ for the average over one observation-level effect and $E_b$ for the average over the shared intercept, the cluster contributes
\[E_b\!\left[\prod_{j=1}^8 E_e\{p_j(y_j\mid b,e)\}\right].\]1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
poisson_olre_integral <- function(y, fixed, cluster_sd, observation_sd, nodes = 31L) {
base <- normal_rule(nodes)
outer_terms <- vapply(seq_along(base$nodes), function(k) {
# Rows are counts and columns are observation-level quadrature points.
eta <- fixed + cluster_sd * base$nodes[k] +
matrix(rep(observation_sd * base$nodes, each = length(y)), length(y))
inner_terms <- glmm_response(y, eta, "poisson")$log_density
# Average over a separate effect for each count, then add their log probabilities.
sum(apply(sweep(inner_terms, 2, log(base$weights), "+"), 1, logsumexp))
}, 0.0)
# Average the resulting product over the shared intercept.
logsumexp(log(base$weights) + outer_terms)
}
print(c(ordinary_count_total = sum(count$y),
extra_effect_count_total = sum(extra_input$observed$y),
first_extra_cluster_log_integral = poisson_olre_integral(extra_input$observed$y[1:8],
.2 + .5 * count$blocks[[1]]$X[,2], .7, .4, 61)))
1
2
ordinary_count_total extra_effect_count_total first_extra_cluster_log_integral
1284.00000 1128.00000 -17.18276
The first two entries sum the counts over all 640 observations. The original draw with seed 903 gave 1284 events and the second gave 1128. The intercepts and counts were redrawn, so the difference between totals includes sampling variation. The last entry, $-17.18276$, approximates the log probability of the eight counts beginning with $(2,2,4)$.
In eta, row $j$ varies the effect for count $j$ over the inner points. For each row, the inner logsumexp() calculates the log of a weighted sum of Poisson probabilities, one for each possible value of that observation’s effect on the grid. Adding the eight resulting log probabilities multiplies the separately averaged probabilities on their original scale. This product still depends on $b$. The final logsumexp() gives the log of its weighted average over the outer points. A single high intercept raises the conditional means of both counts in a pair, whereas a high observation-level effect raises only its own.
With fixed part 0.2 of the linear predictor for both counts in a pair, the simulation uses seed 100902 to generate 100,000 independent pairs and check the covariance formula. Within a pair, the same draw from shared enters both log means, while the independent draws from extra1 and extra2 enter one each. For these parameters, the marginal mean is $\mu=\exp[0.2+(0.49+0.16)/2]$. The count variance is $\mu+\mu^2(e^{0.65}-1)$ because both effects vary the rate. In the covariance, $\mu^2(e^{0.49}-1)$, only the shared variance appears in the exponent.
1
2
3
4
5
6
7
8
9
10
11
12
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(100902)
M <- 100000L
# The two counts in each pair use the same draw of the intercept.
shared <- rnorm(M, 0, .7)
extra1 <- rnorm(M, 0, .4)
extra2 <- rnorm(M, 0, .4)
y1 <- rpois(M, exp(.2 + shared + extra1))
y2 <- rpois(M, exp(.2 + shared + extra2))
mean_theory <- exp(.2 + (.7^2 + .4^2) / 2)
variance_theory <- mean_theory + mean_theory^2 * expm1(.7^2 + .4^2)
covariance_theory <- mean_theory^2 * expm1(.7^2)
The empirical mean and variance use the first count in each pair. The covariance uses the product of the two counts’ deviations from their respective sample means. For each moment, influence records one centered contribution per pair. Its column standard deviation divided by $\sqrt{100{,}000}$ estimates the Monte Carlo standard error of the corresponding sample moment. For the variance and covariance, this is a first-order approximation to the Monte Carlo standard error, using estimated means; it is not an exact finite-sample standard error.
1
2
3
4
5
6
7
8
9
# Center one contribution per independent pair for each Monte Carlo standard error.
influence <- cbind(mean = y1 - mean(y1),
variance = (y1 - mean(y1))^2 - mean((y1 - mean(y1))^2),
covariance = (y1 - mean(y1)) * (y2 - mean(y2)) -
mean((y1 - mean(y1)) * (y2 - mean(y2))))
moment_table <- data.frame(moment = c("mean","variance","covariance"),
theory = c(mean_theory, variance_theory, covariance_theory),
empirical = c(mean(y1), var(y1), cov(y1,y2)), MCSE = apply(influence, 2, sd) / sqrt(M))
print(moment_table, row.names = FALSE)
1
2
3
4
moment theory empirical MCSE
mean 1.690459 1.688190 0.00660293
variance 4.306755 4.359868 0.06425519
covariance 1.806939 1.866154 0.04007222
The predicted mean, variance and covariance are 1.69046, 4.30676 and 1.80694. The simulated values were 1.68819, 4.35987 and 1.86615, with Monte Carlo standard errors of 0.00660, 0.06426 and 0.04007. All three discrepancies are within two Monte Carlo standard errors. The largest on this scale is the covariance discrepancy, about 1.48. If all 0.65 units of log mean variance came from independent observation-level effects, the count variance at this fixed part of the linear predictor would still be 4.30676, but the two counts would have zero covariance.
For a single Bernoulli observation, mixing over a success probability has a different consequence. Let $\pi$ be the probability of success given the random effects and $p=E(\pi)$ its marginal value. Total variance now gives $E[\pi(1-\pi)]+\operatorname{Var}(\pi)=p(1-p)$ because the two terms involving $E(\pi^2)$ cancel. An observation-level normal effect can change $p$. Once $p$ is specified, the variance of a single binary response is fixed, so its marginal distribution cannot identify a separate Bernoulli dispersion parameter. This statement concerns a single binary response at a specified marginal probability. Correlation among repeated binary observations and extra variation in grouped binomial counts are separate questions. The lme4 package fits Poisson mixed models with shared and observation-level random effects.
9.3 Evaluating the marginal likelihood with Gauss-Hermite and adaptive quadrature
What probability does the random-intercept logistic regression model assign to the first cluster’s four failures, three successes and final failure? With fixed coefficients $(-0.4,0.8)$ and an intercept deviation of zero, the conditional log probability of that pattern was $-4.53460$. A fixed Gauss-Hermite quadrature (GHQ) rule uses this value at its central point and evaluates the same eight responses at other possible intercepts. Write $u_k$ and $v_k$ for the standard normal points and their probability weights, which sum to one. If the random intercept has standard deviation $\sigma_b$, the intercept deviation at point $k$ is $\sigma_b u_k$. Let $s_i(b)$ be the sum of the conditional log probabilities for cluster $i$ at random effect $b$. The approximation to the log marginal probability of its observed vector is
\[\ell_i^{\mathrm{fixed}}=\log\sum_{k=1}^{K}v_k\exp\{s_i(\sigma_b u_k)\}.\]With 31 points, the calculation for the first cluster uses 31 products of eight probabilities. Its record contains one log probability and a node count of 31. The other 79 clusters use the same possible intercepts, but their observed responses change those products. The negative marginal log likelihood is obtained by adding the cluster log probabilities and reversing the sign. With two random effects, the same reasoning uses a Cartesian product of normal points and maps each standardized point $u_k$ to $Lu_k$, where $LL^\top$ is the covariance of the random effects.
Two clusters with the same design can favor different intercepts. A string of successes favors higher intercepts than a string of failures. Adaptive Gauss-Hermite quadrature (AGQ) places points where the observed response pattern and the normal density together give a large integrand. From the book directory, with the grouped data and integration functions loaded, the following file supplies the covariance transformations, numerical differentiation routines and scalar likelihood used in the calculations.
1
source("code/lib/glmm.R")
The evaluator glmm_integrate() calculates one marginal probability per cluster in the standardized effects $z$, with $b=Lz$. It accepts fixed quadrature, adaptive quadrature or the Laplace approximation, along with an optional mode-search starting vector for each cluster.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
glmm_integrate <- function(data, beta, L, method = "AGQ",
nodes = if (data$q < 3L) 11L else 7L,
starts = NULL, control = list()) {
q <- data$q
stopifnot(method %in% c("GHQ", "AGQ", "Laplace"), length(beta) == data$p,
identical(dim(L), c(q, q)), all(is.finite(c(beta, L))))
if (is.null(starts)) starts <- matrix(0, data$groups, q)
stopifnot(identical(dim(starts), c(data$groups, q)))
fixed_rule <- if (method == "GHQ") product_rule(nodes, q) else NULL
integrals <- lapply(seq_along(data$blocks), function(i) {
f <- glmm_integrand(data$blocks[[i]], beta, L, data$family)
if (all(L == 0)) {
value <- f$response(rep(0, q))
return(list(log_integral = value, valid = is.finite(value), evaluations = 1L,
reason = if (is.finite(value)) "exact_zero_variance" else
"nonfinite_cluster_loglik"))
}
The starting vector for each cluster is zero unless supplied by the caller. With fewer than three effects, the default is 11 adaptive points per effect. With three or more, it is seven. The fixed rule needs just one call to product_rule() for all clusters. If every entry of $L$ is zero, the conditional probability is constant in $z$ and equals the integral. With $K$ points on each of $q$ axes, the product rule has $K^q$ points per cluster. These rules use standard normal probability weights; formulas for Hermite weights under a different normalization require the corresponding rescaling.
For nonzero $L$, write $h_i(z)=s_i(Lz)+\log\phi_q(z)$, where $\phi_q$ is the standard normal density in $q$ dimensions. The conditional mode $\hat z_i$ maximizes $h_i$. Subtracting its value at the starting point changes neither its gradient nor its curvature. The call to conditional_mode() passes that centered function and the derivatives in $z$. At the returned mode, let $H_i=-\nabla^2 h_i(\hat z_i)$ and let the upper triangular Cholesky factor $R_i$ satisfy $R_i^\top R_i=H_i$. The adaptive grid evaluates $z_{ik}=\hat z_i+R_i^{-1}u_k$. A direction with greater curvature thus receives a narrower spread of points. The same mode and curvature also serve the one-point Laplace calculation. The conditional distribution is that of the random effects given the observed responses, with the model parameters fixed. This implementation adapts to its mode and negative Hessian; adaptive rules based on posterior means and variances are another construction.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
start <- starts[i, ]
if (method != "GHQ") {
mode <- conditional_mode(f$centered(start), f$gr, f$he, start, control)
if (!mode$valid) return(list(log_integral = NA_real_, valid = FALSE,
reason = mode$reason, inner = mode))
start <- mode$mode
}
if (method == "Laplace") {
answer <- laplace_approx(f$h, f$gr, f$he, start, control, inner = mode)
answer$mode_search <- mode
return(answer)
}
rule <- if (method == "GHQ") fixed_rule else {
# In one or more dimensions the same fitted curvature defines the adaptive rule.
r <- product_rule(nodes, q, mode$mode, curvature = mode$curvature)
r$inner <- mode
r
}
if (!isTRUE(rule$valid)) return(list(log_integral = NA_real_, valid = FALSE,
reason = rule$reason, rule = rule, evaluations = 0L))
For the first cluster, at_nodes() adds eight conditional log probabilities in each column of its matrix of linear predictor values. With fixed nodes, joint = FALSE gives $s_1(Lu_k)$ and rule$log_weights supplies $\log v_k$. With adaptive nodes, joint = TRUE includes $\log\phi_q(z_{1k})$ in each value of $h_1$. The corrected log weight is $\log v_k-\log\phi_q(u_k)-\log\vert \det R_1\vert $. The subtraction removes the normal integration density at the original point, and the determinant accounts for the change of volume. The two rules can now use the same logsumexp() calculation. Subtracting the maximum makes the largest exponential equal to one, and adding the maximum back gives the cluster log probability.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# The fixed weights include the normal density. The adaptive values include it.
values <- f$at_nodes(rule$nodes, joint = method != "GHQ")
weighted <- rule$log_weights + values
total <- if (anyNA(weighted) || any(weighted == Inf)) NA_real_ else
logsumexp(weighted)
list(log_integral = total, valid = is.finite(total), rule = rule,
evaluations = rule$count, reason = if (is.finite(total)) "evaluated" else
"nonfinite_cluster_loglik",
mode_search = if (method != "GHQ") mode else NULL)
})
valid <- all(vapply(integrals, `[[`, TRUE, "valid"))
contributions <- vapply(integrals, `[[`, 0.0, "log_integral")
list(value = if (valid) -sum(contributions) else Inf, valid = valid,
loglik_contributions = contributions, clusters = integrals,
method = method, nodes_per_axis = if (method == "Laplace") 1L else nodes,
number_of_random_effects = q, beta = beta, G = tcrossprod(L),
failed_clusters = which(!vapply(integrals, `[[`, TRUE, "valid")))
}
For the original fixed coefficients and intercept standard deviation 0.7, glmm_integrate(binary, c(-.4, .8), matrix(.7), "GHQ", 31) returns all 80 log probabilities. Its first cluster record contains log_integral for the response pattern and evaluations equal to 31. For adaptive quadrature, this count excludes the work of finding the mode. The combined return gives one log marginal probability per cluster and an infinite negative log likelihood if any cluster is invalid. This evaluator works entirely in $z$. Estimating the random-effect covariance as a parameter also calls for posterior moments on the original scale of the intercept and slope. The field valid checks whether the contribution can be evaluated under the implemented checks; Section 9.5 shows that it can remain true after an inner iteration limit.
Fitting with posterior weights on adaptive grids
How do the cluster integrals determine the regression coefficients and the random-effect covariance? The function glmm_fit() fits the binary and Poisson models here with zero offsets. Write $D$ for the covariance of the random effects $b_i$ with mean zero, $n$ for the number of clusters and $p$ for the number of fixed coefficients. At each trial, the fit needs both the probability of the observed responses and the relative support those responses give to different values of $b_i$. The group index assigns each row of the design matrix to the cluster whose integral contains it. Here $D=G$ in the notation of Section 9.1. It is the covariance on the random effects’ original scale, not the relative covariance $G/\sigma^2$ used in Chapter 8. Selecting "Laplace" or one adaptive point delegates to glmm_laplace_fit().
The implementation first places a grid for each cluster and computes posterior weights on it. An initial expectation-maximization (EM) phase updates the covariance and takes a coefficient step with those weights fixed, periodically refreshing the grid. If needed, BFGS then optimizes on a grid that remains fixed during each run. A final grid placement reevaluates the returned parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
glmm_fit <- function(data, method = "AGQ",
nodes = if (data$q < 3L) 11L else 7L, start = NULL,
control = list()) {
stopifnot(method %in% c("GHQ", "AGQ", "Laplace"),
data$family %in% c("binomial", "poisson"),
all(data$offset == 0))
# A single adaptive node gives the Laplace approximation.
if (method == "Laplace" || (method == "AGQ" &&
nodes == 1L)) return(glmm_laplace_fit(data, start, control = control))
settings <- modifyList(list(em_iters = 30L, refresh_every = 10L, qn_rounds = 15L,
qn_iters = 10L, qn_iters_step = 10L, relative_change_offset = 1e-4, relative_parameter_tolerance = 1e-5, qn_rel_tol = 1e-8,
beta_scale = .1, D_scale = .01, max_coef = 12), control)
y <- data$y
X <- data$X
g <- data$group_index
n <- data$groups
q <- data$q
p <- data$p
# A diagnostic can record the raw contributions and their sum at the current stage.
cluster_ids <- vapply(data$blocks, `[[`, "", "id")
report_clusters <- function(stage, values, total, ids = cluster_ids) {
if (is.function(settings$cluster_diagnostic) && any(!is.finite(values)))
settings$cluster_diagnostic(stage, setNames(values, ids), total)
invisible(NULL)
}
linkinv <- if (data$family == "binomial") binomial()$linkinv else poisson()$linkinv
log_density <- function(eta) {
mu <- linkinv(eta)
if (data$family != "binomial") y * log(mu) - mu - lgamma(y + 1) else
dbinom(y, 1L, mu, TRUE)
}
Xty <- drop(crossprod(X, y))
The first part of the function sets the controls and selects the conditional response log probability. If control$cluster_diagnostic is a function, report_clusters() calls it when contributions are nonfinite, passing the calculation stage, a vector named by cluster identifier and its total. This optional function records diagnostic information rather than replacing a failed contribution.
The function glmm_fit() begins with a common grid of $K$ standard normal points. It divides each product probability weight $v_k$ by the standard normal density at $u_k$ to obtain w[k] for integration with respect to volume. Within adapt(), the grid will be transformed separately for each cluster into points $b_{ik}$. The fixed rule uses center zero and precision $D^{-1}$, which gives the spread of the normal prior. For adaptive placement, the criterion for cluster $i$ is the negative conditional response log probability plus $b_i^\top D^{-1}b_i/2$. Its minimum gives the mode because the posterior normalizing constant is the same for every $b_i$ in that cluster. Within an optimization run these transformed points in the original random effects remain fixed. Even the "GHQ" fitting option can replace that grid between runs as $D$ changes; it is therefore distinct from using fixed standardized points throughout in glmm_integrate().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
rule <- normal_rule(nodes)
index <- as.matrix(expand.grid(rep(list(seq_len(nodes)), q)))
z <- matrix(rule$nodes[index], ncol = q)
K <- nrow(z)
log_w <- rowSums(matrix(log(rule$weights[index]), ncol = q)) -
rowSums(matrix(dnorm(z, log = TRUE), ncol = q))
w <- exp(log_w)
log_w_matrix <- matrix(rep(log_w, each = n), n, K)
# The adaptive grid uses the conditional mode and curvature in each cluster.
# The fixed grid uses the prior covariance.
adapt <- function(beta, D, modes) {
D_inv <- solve(D)
fixed <- drop(X %*% beta)
b <- vector("list", n)
log_det_terms <- numeric(n)
hessians <- vector("list", n)
for (i in seq_len(n)) {
blk <- data$blocks[[i]]
if (method == "GHQ") {
H <- D_inv
modes[i, ] <- 0
} else {
For the adaptive rule, fn() evaluates the negative log posterior density up to a constant. Its gradient adds the prior term $D^{-1}b_i$ to the gradient of the negative conditional response log probability with respect to $b_i$. BFGS searches from the cluster’s preceding mode, or from zero on the first placement. Every observation contributes to this density. A nonfinite sum is rejected. The returned center and curvature determine the adaptive rule; the optimizer’s stopping reason is recorded separately from whether that rule can be evaluated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
f_i <- fixed[blk$rows]
Zty_i <- drop(crossprod(blk$Z, blk$y))
fn <- function(bi) {
eta <- f_i + drop(blk$Z %*% bi)
mu <- linkinv(eta)
ld <- if (data$family != "binomial") blk$y * log(mu) - mu - lgamma(blk$y + 1) else
dbinom(blk$y, 1L, mu, TRUE)
total <- sum(ld)
if (is.function(settings$cluster_diagnostic))
report_clusters("conditional mode", sum(ld), total, blk$id)
if (!is.finite(total)) return(Inf)
prior <- c(.5 * crossprod(bi, D_inv) %*% bi); prior - total
}
gr <- function(bi) {
mu <- linkinv(f_i + drop(blk$Z %*% bi))
drop(-Zty_i + crossprod(blk$Z, mu) + D_inv %*% bi)
}
conditional <- bfgs(fn, gr, modes[i, ])
if (identical(conditional$reason, "nonfinite_initial_value"))
stop(sprintf("Nonfinite initial negative log posterior density for cluster %s",
blk$id))
modes[i, ] <- conditional$par
H <- glmm_cd_jacobian(modes[i, ], gr)
}
The helper glmm_cd_jacobian() takes the current vector of random effects and the gradient function. It returns a symmetric matrix of central differences that approximates the Hessian of the negative log joint density at the returned point. Each coordinate is perturbed by $0.001\max(1,\vert b_{il}\vert )$ in each direction. The next block uses this curvature to transform the integration points and retain the quantities needed for posterior moments.
1
2
3
4
5
6
7
8
9
10
11
12
# Map the standard points into the original random effects for this cluster.
U <- chol(H)
log_det_terms[i] <- -determinant.matrix(U, logarithm = TRUE)$modulus; hessians[[i]] <- H
b[[i]] <- t(solve(U, t(z)) + modes[i, ])
}
Zb <- array(0, c(length(y), K))
for (i in seq_len(n)) Zb[data$blocks[[i]]$rows, ] <- data$blocks[[i]]$Z %*% t(b[[i]])
b <- do.call(rbind, b)
b2 <- if (q > 1) t(apply(b, 1, function(row) outer(row, row))) else b * b
list(b = b, b2 = b2, Zb = Zb, log_det_terms = log_det_terms, modes = modes,
hessians = hessians)
}
If $U_i$ is the upper Cholesky factor of that curvature, solve(U, t(z)) gives the displacements from the mode. For each cluster the function stores its transformed points, the log Jacobian $-\log\vert \det U_i\vert $, and the resulting random-effect contribution to every observation’s linear predictor at every point. The row of b2 for a point contains the products of its coordinates, including their squares.
At point $b_{ik}$, let $d_{ik}$ be the conditional response probability for the cluster multiplied by its normal random-effect density at $b_{ik}$. For a finite cluster log integral, the normalized quadrature weight $p_{ik}$ and the approximate posterior second moment give the covariance update
\[p_{ik}=\frac{d_{ik}w_k}{\sum_{r=1}^{K}d_{ir}w_r},\qquad D_{\mathrm{new}}=\frac1n\sum_{i=1}^{n}\sum_{k=1}^{K} p_{ik} b_{ik}b_{ik}^{\top}.\]These weights approximate expectations under the continuous posterior distribution of $b_i$ given its responses. The log Jacobian is constant across nodes for a given cluster. It enters the cluster log marginal probability and cancels in the normalization of $p_{ik}$.
The fixed coefficients use the same posterior weights. If $\mu_{ik}(\beta)$ is the vector of conditional response means for cluster $i$ at node $k$, the gradient of the expected negative conditional log likelihood, with the weights fixed, is
\[g(\beta)=\sum_i X_i^\top\!\left[\sum_k p_{ik}\mu_{ik}(\beta)-y_i\right].\]1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
posterior <- function(beta, D, state) {
lpb <- rowsum(log_density(drop(X %*% beta) + state$Zb), g, reorder = FALSE)
lpb <- lpb + matrix(glmm_normal_log_density(state$b, D), n, K, byrow = TRUE)
# The Jacobian enters the log probability and cancels in the normalized weights.
log_marg <- glmm_row_logsumexp(log_w_matrix + lpb)
contributions <- log_marg + state$log_det_terms
if (any(!is.finite(contributions))) {
report_clusters("marginal likelihood", contributions, sum(contributions))
stop("Nonfinite marginal log likelihood for cluster(s): ",
paste(cluster_ids[!is.finite(contributions)], collapse = ", "))
}
list(post_w = exp(lpb - log_marg), log_marg = contributions)
}
posterior_mean <- function(post_w, B) vapply(seq_len(ncol(B)),
function(k) colSums(t(post_w) * matrix(B[, k], K, n) * w), numeric(n))
expected_nll_beta_gradient <- function(beta, post_w, state) {
mu <- linkinv(drop(X %*% beta) + state$Zb)
# Expected score for coefficient l: the sum over clusters of the posterior mean of
# sum_j x_jl mu_j.
expected <- function(l) sum((rowsum(X[, l] * mu, g, reorder = FALSE) * post_w) %*% w,
na.rm = TRUE)
-Xty + vapply(seq_len(p), expected, 0.0)
}
The entry lpb[i,k] stores $\log d_{ik}$, the log of the conditional response probability multiplied by the random-effect density. The helper glmm_normal_log_density() supplies one zero-mean normal log density per row of the node matrix state$b, using covariance D. Its diagonal shortcut ignores off-diagonal entries whose absolute values are all below the square root of machine precision. The helper glmm_row_logsumexp() then applies the logarithmic summation to each cluster row of weighted log terms and returns one log integral per cluster before the Jacobian adjustment. The Jacobian-adjusted log probabilities are stored in post$log_marg.
The function posterior() includes w in the denominator but stores post$post_w[i,k] before multiplication by the individual weight. The products post$post_w[i,k] * w[k] sum to one for that cluster. In posterior_mean(post$post_w, state$b2), the first column averages the squared intercept coordinate over nodes within each cluster. The mean of that column across clusters gives the new intercept variance. This averages posterior second moments about the model’s fixed random-effect mean of zero. post$post_w alone is not a vector of posterior probabilities. Only after multiplication by the quadrature weights does it give the normalized weights used for these approximate conditional moments.
For coefficient $l$, expected_nll_beta_gradient() weights the conditional means by design column $l$, adds them within their clusters and averages over the grid. Subtracting the corresponding element of Xty completes the derivative.
For the BFGS criterion, the parameters include the distinct entries of the upper Cholesky factor of $D$, with its diagonal entries on the log scale. Let $S$ be the sum of the clusters’ posterior second moment matrices. Differentiating the negative normal log density in $D$ and averaging over the posterior gives $\tfrac12(nD^{-1}-D^{-1}SD^{-1})$ after summing over clusters. The next functions combine this covariance derivative with the fixed-coefficient derivative on the current quadrature grid.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
unpack <- function(theta) list(beta = theta[seq_len(p)],
D = glmm_par_to_D(theta[-seq_len(p)]))
nll <- function(theta, state, contributions = FALSE) {
a <- unpack(theta)
log_marg <- posterior(a$beta, a$D, state)$log_marg
if (contributions) return(-log_marg)
# All clusters must have finite evaluated contributions.
total <- sum(log_marg)
report_clusters("BFGS", log_marg, total)
return(-total)
}
nll_gradient <- function(theta, state) {
a <- unpack(theta)
post <- posterior(a$beta, a$D, state)
# Each missing cluster has missing posterior moments in every coordinate.
# The normal-density term below still counts all n clusters.
S <- matrix(colSums(posterior_mean(post$post_w, state$b2), na.rm = TRUE), q, q)
D_inv <- solve(a$D)
M <- n * D_inv - D_inv %*% S %*% D_inv
U <- chol(a$D)
G <- U %*% M
diag(G) <- diag(G) * diag(U)
c(expected_nll_beta_gradient(a$beta, post$post_w, state), G[upper.tri(G, diag = TRUE)])
}
At a trial parameter vector, nll_gradient() recalculates the posterior weights on the current grid. For a complete set of finite contributions, the weighted derivatives give the gradient of the negative log likelihood on that grid.
For $D=U^\top U$, differentiating the two occurrences of $U$ gives U %*% M, where M is twice the derivative with respect to $D$ given above. For the derivative in $\log U_{ll}$, the chain rule supplies the additional factor $U_{ll}$. For two random effects the stored covariance parameters are $(\log U_{11},U_{12},\log U_{22})$, where $D=U^\top U$. The function glmm_D_to_par() packs these entries by columns of the upper triangle. Its inverse, glmm_par_to_D(), reconstructs $U$, exponentiates its diagonal and returns $D$. The local unpack() separates the fixed coefficients from these covariance coordinates. In this derivative calculation the local variable G is a gradient matrix, whereas the returned fit field G is a covariance. For three or more effects the upper-triangle ordering here also differs from the lower-triangle ordering of logchol_factor(); vectors must not be passed between the two representations without conversion.
By default, the starting fixed coefficients are the ordinary generalized linear model (GLM) estimates multiplied by $\sqrt{1.346}$, and $D$ starts at the identity. The initial EM iterations place the nodes at these parameters and again at the start of evaluations 10, 20 and 30 if reached. Between placements, posterior() updates the densities and weights for the current parameters. The stopping comparison uses the fixed coefficients and the distinct entries of $D$ on their original scales. The covariance update uses approximate conditional second moments, while the coefficient update takes only one adjusted Newton step.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
if (is.null(start)) {
reduced <- fit_glm(make_glm(X, y, data$family), method = "irls")
beta <- reduced$par * sqrt(1.346)
D <- diag(q)
} else {
beta <- start[seq_len(p)]
D <- glmm_par_to_D(start[-seq_len(p)])
}
modes <- matrix(0, n, q)
converged <- FALSE
reason <- "iteration_limit"
loglik <- numeric(0)
params <- list()
too_large <- function(beta) any(abs(beta[-1L]) > settings$max_coef)
check_coefficients <- function(beta) if (too_large(beta))
stop("A large coefficient value has been detected during the optimization")
em_updates <- 0L
if (settings$em_iters > 0) {
state <- adapt(beta, D, modes)
modes <- state$modes
for (it in seq_len(settings$em_iters)) {
if (it %in% seq(0, settings$em_iters, settings$refresh_every)) {
state <- adapt(beta, D, modes)
modes <- state$modes
}
params[[it]] <- c(beta, D[lower.tri(D, diag = TRUE)])
post <- posterior(beta, D, state)
# The posterior calculation has checked every cluster contribution.
loglik[it] <- sum(post$log_marg)
report_clusters("EM", post$log_marg, loglik[it])
After a coefficient update, too_large() tests all fixed coefficients except the first against max_coef, whose default is 12 in absolute value. The caller check_coefficients() stops with an error if this guard is triggered. It is a bound on coefficient magnitude in the supplied covariate units, not a convergence test.
From the fifth evaluation onward, the code compares successive likelihoods before making another update. Let $\theta_t$ contain these coefficients and covariance entries at evaluation $t$, and let $\ell_t$ be the monitored log likelihood. If $\ell_t>\ell_{t-1}$, either of the following inequalities stops this initial phase. The control relative_change_offset supplies the denominator offset $10^{-4}$, relative_parameter_tolerance supplies the parameter-change threshold $10^{-5}$, and qn_rel_tol supplies the likelihood-gain tolerance.
If neither stopping condition is met, the next update averages the posterior second moments for $D$ and takes one adjusted Newton step for the fixed coefficients, with the current posterior weights fixed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
if (it > 4 && loglik[it - 1] < loglik[it]) {
previous <- params[[it - 1]]
change <- max(abs(params[[it]] - previous) / (abs(previous) + settings$relative_change_offset))
small_gain <- loglik[it] - loglik[it - 1] <
settings$qn_rel_tol * (abs(loglik[it - 1]) + settings$qn_rel_tol)
if (change < settings$relative_parameter_tolerance || small_gain) {
converged <- TRUE; reason <- "converged_during_EM"; break }
}
# M step: the posterior second moments give D; one Newton step, with the nearest
# positive definite curvature, updates beta.
second <- matrix(colMeans(posterior_mean(post$post_w, state$b2), na.rm = TRUE), q, q)
D <- .5 * (second + t(second))
beta_gradient <- function(b) expected_nll_beta_gradient(b, post$post_w, state)
H <- glmm_nearest_pd(glmm_fd_jacobian(beta, beta_gradient))
beta <- beta - drop(solve(H, beta_gradient(beta)))
em_updates <- em_updates + 1L; check_coefficients(beta)
}
}
In this update, colMeans() averages the cluster second moments and the next line symmetrizes $D$. With the current posterior weights fixed, glmm_fd_jacobian() takes the coefficient vector and the function beta_gradient() and uses forward differences of $g(\beta)$ to approximate its derivative matrix. The difference matrix is symmetrized, then glmm_nearest_pd() adjusts it before the Newton solve. Solving the resulting linear system gives one Newton step, $\beta_{\mathrm{new}}=\beta-H^{-1}g(\beta)$, where $H$ is the adjusted matrix. The fitted conditional means change during this step while the weights used to average them remain fixed. The helper is named glmm_nearest_pd(), but here it is used to adjust eigenvalues before solving the Newton system. No matrix-distance criterion or certificate of the nearest positive definite solution is returned. The name alone should not be read as establishing that property.
An EM stop skips BFGS. If all 30 EM updates are made without a stop, optimization continues in the fixed coefficients and log-Cholesky coordinates. The numerical parameter scaling values for BFGS are 0.1 for the fixed effects and 0.01 for the covariance coordinates. The first BFGS run allows 10 iterations with relative tolerance $10^{-8}$. Each further run allows 10 more iterations than the preceding one, up to 15 runs in all. The nodes, integration weights and log Jacobians are set before each run. Within that run, differentiation treats the placement as fixed while the coefficients and the covariance in the joint density change. A successful return from BFGS ends the outer loop.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
theta <- c(beta, glmm_D_to_par(D))
runs <- list()
if (!converged && settings$qn_rounds > 0) {
par_scale <- rep(c(settings$beta_scale, settings$D_scale), c(p, length(theta) - p))
maxit <- settings$qn_iters
for (outer in seq_len(settings$qn_rounds)) {
# Rebuild the grid once for this run, before evaluating trial parameters.
state <- adapt(beta, D, modes)
run <- bfgs(function(t) nll(t, state), function(t) nll_gradient(t, state), theta,
list(maxit = maxit, rel_tol = settings$qn_rel_tol, par_scale = par_scale))
if (identical(run$reason, "nonfinite_initial_value"))
stop("Nonfinite initial negative log likelihood in BFGS")
runs[[outer]] <- run
theta <- run$par
a <- unpack(theta)
beta <- a$beta
D <- a$D
modes <- state$modes
check_coefficients(beta)
if (run$converged) {
converged <- TRUE
reason <- "converged_during_BFGS"
break
}
maxit <- maxit + settings$qn_iters_step
}
}
The final placement uses the returned parameters. Each cluster must supply a finite log probability before the contributions are summed. If this condition fails, the calculation reports the affected clusters. The final grid is newly placed, and the reported likelihood and score are evaluated with the returned coefficients on this grid. The coefficients and covariance are not optimized again after this final placement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
theta <- c(beta, glmm_D_to_par(D))
state <- adapt(beta, D, modes)
contributions <- -nll(theta, state, TRUE)
total <- sum(contributions)
report_clusters("final", contributions, total)
list(value = -total, beta = beta, G = D, theta = theta,
loglik_contributions = contributions, converged = converged, reason = reason,
optimizer = list(em_updates = em_updates, em_loglik = loglik,
score = -nll_gradient(theta, state), bfgs_reason = vapply(runs,`[[`,"","reason"),
bfgs_runs = length(runs), bfgs_iterations = vapply(runs, `[[`, 0L, "iterations"),
iterations = em_updates + sum(vapply(runs, `[[`, 0L, "iterations")),
evaluations = Reduce(`+`, lapply(runs, `[[`, "evaluations"),
c(objective = 0L, gradient = 0L, hessian = 0L)),
converged = converged, reason = reason),
modes = state$modes, method = method, nodes_per_axis = nodes,
constraints = list(mean = rep(0, q), covariance = "positive definite"))
}
Fits to the simulated binary data
For the binary data with a random intercept and slope, the integral is two-dimensional. The call with seven adaptive points on each axis uses 49 point pairs in each cluster. To check the approximation at the fitted coefficients and covariance, slope_common() uses the standardized evaluator. R returns an upper Cholesky factor from chol(), so t(chol(fit$G)) supplies the lower triangular Cholesky factor $L$ for which $LL^\top$ equals the fitted covariance. The two finer grids evaluate the same fitted parameters. Each row of either grid specifies an intercept and a slope for all eight observations of one cluster.
1
2
3
4
5
6
7
8
slope_agq <- glmm_fit(slope, "AGQ", 7)
slope_common <- function(fit, nodes = 15L) glmm_integrate(slope, fit$beta, t(chol(fit$G)),
"AGQ", nodes)$value
print(c(slope_agq$beta, intercept_SD = sqrt(slope_agq$G[1,1]),
slope_SD = sqrt(slope_agq$G[2,2]),
covariance = slope_agq$G[1,2], own7_nll = slope_agq$value,
common15_nll = slope_common(slope_agq), refinement15_21 = slope_common(slope_agq,
21)-slope_common(slope_agq)))
1
2
3
4
intercept x intercept_SD slope_SD covariance own7_nll
-2.371431e-01 6.086700e-01 8.386422e-01 5.307963e-01 -2.797628e-02 4.198781e+02
common15_nll refinement15_21
4.198781e+02 -4.960725e-10
The fitted fixed intercept is $-0.23714$ and the fixed slope is $0.60867$. The intercept and slope standard deviations are $0.83864$ and $0.53080$, and their covariance is $-0.02798$. At these estimates, the negative marginal log likelihood prints as $419.8781$ using either seven or 15 points per axis. Subtracting the 15-point value from the 21-point value gives $-4.96\times10^{-10}$. This small change measures how closely the two finer grids integrate the observed responses at this fit.
For the binary random-intercept data, one integration axis suffices. The two fits below use the same 640 observations with 31 fixed points and seven adaptive points. The assertion checks that the adaptive fit returns one finite log probability for each of the 80 clusters. To compare the fits on one scale, common_scalar() evaluates each returned parameter vector with a fresh 61-point adaptive rule. The own_nll column uses each fit’s own rule.
1
2
3
4
5
6
7
8
9
10
fixed_fit <- glmm_fit(binary, "GHQ", 31)
adaptive_fit <- glmm_fit(binary, "AGQ", 7)
stopifnot(length(adaptive_fit$loglik_contributions) == binary$groups,
all(is.finite(adaptive_fit$loglik_contributions)))
common_scalar <- function(fit, nodes = 61L) glmm_integrate(binary, fit$beta,
t(chol(fit$G)), "AGQ", nodes)$value
print(rbind(GHQ31 = c(fixed_fit$beta, SD = sqrt(fixed_fit$G[1]),
own_nll = fixed_fit$value, common61_nll = common_scalar(fixed_fit)),
AGQ7 = c(adaptive_fit$beta, SD = sqrt(adaptive_fit$G[1]),
own_nll = adaptive_fit$value, common61_nll = common_scalar(adaptive_fit))))
1
2
3
intercept x SD own_nll common61_nll
GHQ31 -0.1911973 0.7212418 0.6057660 422.0517 422.0517
AGQ7 -0.1911970 0.7212408 0.6057595 422.0517 422.0517
The fixed rule gives intercept $-0.1911973$, slope $0.7212418$ and intercept standard deviation $0.6057660$. The adaptive rule gives $-0.1911970$, $0.7212408$ and $0.6057595$. The first entry of fixed_fit$loglik_contributions is $-4.891201$. It is the log probability of the eight responses after averaging over 31 intercepts. At the adaptive estimates, adaptive_fit$loglik_contributions gives $-4.891198$ for this cluster. In each case, the negative sum over all 80 clusters is the value reported for the fit. Both fits give $422.0517$ to the printed precision under their own rule and under the common adaptive rule. How steep is the log likelihood at these estimates?
The score vector measures how the log likelihood changes with the fixed intercept, the fixed slope and the log random-intercept standard deviation, in that order. To compare these derivatives, glmm_scalar() uses 61 fixed standard normal points for both parameter vectors. In standardized coordinates, varying the log standard deviation changes the random intercept represented by each fixed point. Its gr component gives the gradient of the negative log likelihood, so the minus sign at each call gives the derivative of the log likelihood. The last column totals the iteration counters returned by the BFGS runs.
1
2
3
4
5
6
7
scalar_reference <- new.env(parent=environment())
sys.source("code/lib/glmm.R",scalar_reference)
common_nll_gradient <- scalar_reference$glmm_scalar(binary,61L,"GHQ")$gr
print(rbind(GHQ31=c(score=-common_nll_gradient(fixed_fit$theta),
BFGS=sum(fixed_fit$optimizer$bfgs_iterations)),
AGQ7=c(score=-common_nll_gradient(adaptive_fit$theta),
BFGS=sum(adaptive_fit$optimizer$bfgs_iterations))))
1
2
3
score1 score2 score3 BFGS
GHQ31 0.0005131636 -0.001975742 -0.1206253 1
AGQ7 0.0005065706 -0.001973607 -0.1204220 1
Each fit completed 30 EM updates. Both recorded a BFGS counter of one. This counter starts at one, so its reported value alone cannot tell how many parameter moves were accepted. The derivatives with respect to the log standard deviation under the common fixed rule are $-0.12063$ at the fixed-rule fit and $-0.12042$ at the adaptive fit. With the fixed coefficients unchanged, a small increase in log standard deviation would decrease the common fixed-rule log likelihood at either fit. The adaptive-quadrature values of the negative marginal log likelihood agree to four decimal places even though the fixed-rule derivatives at both estimates are nonzero. The adaptive nodes of the supplied glmm_fit(), its normal log density, its finite-difference derivative calculations and its positive definite matrix adjustment are adapted from the GLMMadaptive package (code/NOTICE.md), which fits generalized linear mixed models by adaptive Gauss-Hermite quadrature.
9.4 Laplace approximation to the marginal likelihood
How much of a cluster’s marginal probability can be recovered from the height and curvature of its integrand at a single point? For cluster $i$, let $b_i$ be the vector of $q$ random effects on their original scale, with positive definite covariance $\Sigma$. Write $h_i(b_i)$ for the sum of the conditional response log probabilities and the full $N_q(0,\Sigma)$ log density. At the mode $\hat b_i$ of the random effects given the observed responses, the gradient of $h_i$ vanishes. Let $H_i$ be the negative Hessian of $h_i$ there and suppose it is positive definite. This $h_i$ is expressed in $b_i$, whereas Section 9.3 expressed the joint density in standardized $z_i$. The covariance $\Sigma$ here is the same model quantity denoted $G$ or $D$ above. Near the mode, the quadratic expansion and its integral give
\[\begin{aligned} h_i(b_i)&\approx h_i(\hat b_i) -\tfrac12(b_i-\hat b_i)^\top H_i(b_i-\hat b_i),\\ \log\int_{\mathbb R^q} e^{h_i(b_i)}\,db_i &\approx h_i(\hat b_i)+\tfrac q2\log(2\pi)-\tfrac12\log|H_i|. \end{aligned}\]The exponential of the quadratic term integrates to $(2\pi)^{q/2}\vert H_i\vert ^{-1/2}$. For the same height, increasing the curvature in one direction with the other curvatures fixed reduces the approximate probability. This is the Laplace approximation. The evaluator glmm_nll_laplace() passes the fixed coefficients and lower Cholesky factor to the standardized integration routine. For $b_i=Lz_i$, the log density in $z_i$ gains $\log\vert \det L\vert $ and the negative Hessian at the mode becomes $L^\top H_iL$. These changes cancel in the log integral, so laplace_approx() can use the standardized mode and curvature.
1
2
3
4
glmm_nll_laplace <- function(u, data, starts = NULL, control = list()) {
glmm_integrate(data, head(u, data$p), logchol_factor(tail(u, -data$p)),
"Laplace", 1L, starts, control)
}
Fitting by the Laplace approximation
For fitting, glmm_laplace_fit() searches for the conditional modes in the original units of the random effects. It handles binary and Poisson responses with zero offsets and one or two random effects per cluster. Its outer parameter vector $\theta$ contains the fixed coefficients, the log standard deviations and, for two random effects, an unrestricted parameter $c$. The transformation $\rho=c/\sqrt{1+c^2}$ gives the correlation. Multiplying the correlation matrix on both sides by the diagonal matrix of standard deviations gives $\Sigma$.
For two random effects this starting vector is not the log-Cholesky vector accepted by the multi-point glmm_fit() branch. A common vector must be converted before switching methods. Positive standard deviations and correlations strictly between $-1$ and $1$ imply a positive definite covariance in exact arithmetic; extreme transformed inputs still require numerical checks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
glmm_laplace_fit <- function(data, start = NULL, control = list(), inner_control = list()) {
stopifnot(data$family %in% c("binomial", "poisson"), data$q <= 2L,
all(data$offset == 0))
p <- data$p
q <- data$q
m <- data$groups
k <- p + q + q * (q - 1) / 2
covariance <- function(theta) {
sd <- exp(theta[p + seq_len(q)])
R <- diag(q)
dR <- list()
if (q == 2) {
c <- theta[p + 3]
# Map the unrestricted coordinate into a correlation.
R[1, 2] <- R[2, 1] <- c / sqrt(1 + c^2)
dR <- list(matrix(c(0, 1, 1, 0), 2) * (1 + c^2)^(-1.5))
}
Sigma <- outer(sd, sd) * R
dSigma <- c(lapply(seq_len(q), function(j) {
E <- matrix(0, q, q)
E[j, j] <- 1
E %*% Sigma + Sigma %*% E
}), lapply(dR, function(d) outer(sd, sd) * d))
list(Sigma = Sigma, inverse = solve(Sigma), derivatives = dSigma)
}
The covariance helper also computes one derivative matrix $\partial\Sigma/\partial\theta_l$ for each covariance coordinate. At a given $\theta$, the next block evaluates the negative joint log density $-\sum_i h_i(b_i)$, including the full normal density of the random effects.
1
2
3
4
5
6
7
8
9
10
11
12
13
blocks <- data$blocks
response <- function(b, eta) glmm_response(b$y, eta, data$family)
joint <- function(u, beta, cv) {
U <- matrix(u, m, q, byrow = TRUE)
value <- 0
for (i in seq_len(m)) {
b <- blocks[[i]]
# Include the response log probabilities and the normal quadratic term.
t <- response(b, drop(b$X %*% beta + b$Z %*% U[i, ]))
value <- value - sum(t$log_density) + .5 * sum(U[i, ] * drop(cv$inverse %*% U[i, ]))
}
value + m * (.5 * determinant(cv$Sigma)$modulus[1] + q / 2 * log(2 * pi))
}
The vector u stacks the random effects of all $m$ clusters, one cluster at a time. At a given $\theta$, joint() computes $-\sum_i h_i(b_i)$. Each loop iteration subtracts the response log probabilities and adds the normal quadratic term $b_i^\top\Sigma^{-1}b_i/2$. The line after the loop adds the remaining normal density terms for all $m$ clusters. In particular, the log determinant of $\Sigma$ changes as the outer optimizer changes the standard deviations.
Each cluster contributes a separate gradient and Hessian block. Let $\mu_i$ contain its conditional response means and let $W_i$ be diagonal with the corresponding conditional variances. In the gradient, $-Z_i^\top(y_i-\mu_i)$ comes from the responses and $\Sigma^{-1}b_i$ comes from the normal density. The Hessian block is $Z_i^\top W_i Z_i+\Sigma^{-1}$. The random effects of another cluster do not enter this derivative, so the off-diagonal blocks of the full Hessian $H$ are zero.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
joint_gradient <- function(u, beta, cv) {
U <- matrix(u, m, q, byrow = TRUE)
as.vector(vapply(seq_len(m), function(i) {
b <- blocks[[i]]
t <- response(b, drop(b$X %*% beta + b$Z %*% U[i, ]))
-drop(crossprod(b$Z, t$residual)) + drop(cv$inverse %*% U[i, ])
}, numeric(q)))
}
joint_hessian <- function(u, beta, cv) {
U <- matrix(u, m, q, byrow = TRUE)
H <- matrix(0, m * q, m * q)
for (i in seq_len(m)) {
b <- blocks[[i]]
t <- response(b, drop(b$X %*% beta + b$Z %*% U[i, ]))
# These indices select the random effects for just this cluster.
index <- (i - 1) * q + seq_len(q)
H[index, index] <- crossprod(b$Z, t$weight * b$Z) + cv$inverse
}
H
}
For each trial $\theta$, the inner Newton algorithm minimizes the negative joint log density over all $mq$ random effects together. At the conditional modes, the negative Laplace log likelihood adds half the log determinant of $H$ to the negative joint log density and subtracts $mq\log(2\pi)/2$. Summing the individual cluster corrections gives the same answer. This formula requires the inner searches to reach stationary points.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
best <- list(u = rep(0, m * q), value = Inf)
inner <- function(theta) {
beta <- theta[seq_len(p)]
cv <- tryCatch(covariance(theta), error = function(e) NULL)
if (is.null(cv)) return(NULL)
fit <- tryCatch(inner_newton(function(u) joint(u, beta, cv),
function(u) joint_gradient(u, beta, cv),
function(u) joint_hessian(u, beta, cv), best$u, inner_control), error = function(e) NULL)
if (is.null(fit) || !is.finite(fit$value)) return(NULL)
list(u = fit$par, beta = beta, cv = cv)
}
laplace <- function(a) {
H <- joint_hessian(a$u, a$beta, a$cv)
# Half the log determinant is the sum of the log Cholesky diagonals.
joint(a$u, a$beta, a$cv) + sum(log(diag(chol(H)))) - m * q / 2 * log(2 * pi)
}
fn <- function(theta) {
a <- inner(theta)
if (is.null(a)) return(NaN)
value <- laplace(a)
# Reuse modes from the lowest finite negative Laplace log likelihood.
if (is.finite(value) && value < best$value) best <<- list(u = a$u, value = value)
value
}
The first inner search starts at zero. Subsequent searches use the modes associated with the lowest finite negative Laplace log likelihood found so far. In laplace(), the Cholesky diagonals give the determinant term because $H=R^\top R$ implies $\tfrac12\log\vert H\vert =\sum_l\log R_{ll}$.
The outer derivative must follow the modes as $\theta$ changes. The joint log density is stationary in the random effects at a mode, but its curvature can still change as the mode moves. For one cluster, write $f=-h_i$ and $F=f+\tfrac12\log\vert f_{bb}\vert $, omitting the constant. Differentiating $f_b(\hat b_i,\theta)=0$ gives $\partial\hat b_i/\partial\theta=-H_i^{-1}f_{b\theta}$. The total gradient of $F$ in the outer parameters is therefore $F_\theta-f_{\theta b}H_i^{-1}F_b$, evaluated at the mode.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
gr <- function(theta) {
a <- inner(theta)
if (is.null(a)) stop("inner Newton optimization failed during gradient calculation")
U <- matrix(a$u, m, q, byrow = TRUE)
S <- a$cv$inverse
dS <- a$cv$derivatives
total <- numeric(k)
for (i in seq_len(m)) {
b <- blocks[[i]]
ui <- U[i, ]
t <- response(b, drop(b$X %*% a$beta + b$Z %*% ui))
third <- t$third
Hinv <- solve(crossprod(b$Z, t$weight * b$Z) + S)
# Diagonal of Z H^{-1} Z transpose in this cluster.
lev <- rowSums((b$Z %*% Hinv) * b$Z)
grad_u <- -drop(crossprod(b$Z,
t$residual)) + drop(S %*% ui) + .5 * drop(crossprod(b$Z, third * lev))
grad_beta <- -drop(crossprod(b$X, t$residual)) + .5 * drop(crossprod(b$X,
third * lev))
cross_beta <- crossprod(b$X, t$weight * b$Z)
For each cluster, Hinv is the inverse Hessian block and lev contains the diagonal of $Z_iH_i^{-1}Z_i^\top$. Multiplying those diagonal entries by third, the derivative of the response variance with respect to its linear predictor, gives the contribution of the log determinant to the derivative with respect to the linear predictor, multiplied by one half.
The remaining gradient calculation applies the mode-change correction to the covariance coordinates as well as the fixed coefficients.
1
2
3
4
5
6
7
8
9
10
11
12
grad_cov <- vapply(dS, function(D) {
A <- S %*% D %*% S
.5 * sum(S * D) - .5 * sum(ui * drop(A %*% ui)) - .5 * sum(Hinv * A)
}, 0.0)
cross_cov <- do.call(rbind, lapply(dS, function(D) -drop(S %*% D %*% S %*% ui)))
# Account for the change in the conditional mode.
correction <- drop(Hinv %*% grad_u)
total <- total + c(grad_beta - drop(cross_beta %*% correction),
grad_cov - drop(cross_cov %*% correction))
}
total
}
In the code, grad_u is $F_b$ and correction is $H_i^{-1}F_b$. The two mixed derivative matrices apply this correction to the fixed coefficients and the covariance coordinates. In the latter calculation, S denotes $\Sigma^{-1}$ and each D is a derivative of $\Sigma$. dS stores derivatives of $\Sigma$, despite S denoting its inverse. The derivative of the inverse is supplied by the separate product $-S(\partial\Sigma/\partial\theta_l)S$.
BFGS minimizes the negative Laplace log likelihood using this total derivative. The zero starting vector gives zero fixed coefficients, unit random-effect standard deviations and zero correlation when a slope is random. After BFGS stops, the function recomputes the conditional modes and the Laplace criterion at the returned coefficients and covariance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
theta <- if (is.null(start)) rep(0, k) else start
fn(theta)
gr(theta)
optimizer <- bfgs(fn, gr, theta, control)
final <- inner(optimizer$par)
if (is.null(final)) stop("Conditional-mode evaluation failed at the returned parameters")
final_value <- laplace(final)
cv <- final$cv
list(value = final_value, beta = optimizer$par[seq_len(p)], G = cv$Sigma,
theta = optimizer$par,
converged = optimizer$converged, reason = optimizer$reason,
optimizer = c(optimizer[c("iterations", "evaluations", "converged", "reason")]),
modes = matrix(final$u, m, q, byrow = TRUE), method = "Laplace", nodes_per_axis = 1L,
constraints = list(mean = rep(0, q), covariance = "positive definite"))
}
BFGS tests whether the decrease exceeds $r(\vert v_{\mathrm{old}}\vert +r)$, where $v_{\mathrm{old}}$ is the preceding negative Laplace log likelihood and the default relative tolerance $r=\sqrt{\epsilon}$ uses machine precision $\epsilon$. If the decrease is too small, the routine can restart with the identity inverse Hessian approximation before it stops. The iteration limit is 100. The returned fit gives the fixed coefficients and covariance on their model scales along with the optimizer’s stopping reason and counter. The control argument of glmm_laplace_fit() sets the outer BFGS controls, while inner_control sets the inner Newton controls.
Comparing Laplace and adaptive quadrature
With one node, adaptive quadrature reduces to the Laplace approximation, and the binary random-intercept model provides a check on the determinant and its sign. The fixed vector u_true contains intercept $-0.4$, slope $0.8$ and log standard deviation $\log(0.7)$. Consider adaptive Gauss-Hermite quadrature with one point at these parameters. The standard normal rule assigns weight one to zero. Translating and scaling places that point at the conditional mode. The density correction divides by the standard normal density at zero, and the Jacobian multiplies by $\vert H_i\vert ^{-1/2}$ on the scale used for the mode search. With the same mode and curvature, the single weighted value is $e^{h_i(\hat b_i)}(2\pi)^{q/2}\vert H_i\vert ^{-1/2}$, exactly the exponential of the Laplace expression.
The first two calls below estimate parameters separately for the random-intercept data and the random-intercept and slope data. The next two calls use the same u_true and the same binary data to evaluate the one-node adaptive and Laplace approximations. Like glmm_nll_laplace(), glmm_nll_agq() separates the fixed coefficients from the lower log-Cholesky coordinates in u, constructs the factor with logchol_factor() and returns the full glmm_integrate() record. Its node argument selects the adaptive rule, and value contains the combined negative log likelihood.
1
2
3
4
glmm_nll_agq <- function(u, data, nodes = if (data$q < 3L) 11L else 7L, starts = NULL, control = list()) {
glmm_integrate(data, head(u, data$p), logchol_factor(tail(u, -data$p)),
"AGQ", nodes, starts, control)
}
Without a node count, it uses 11 adaptive nodes per dimension for one or two random effects and seven for more. The first number printed subtracts these negative log likelihoods. The other entries use fitted parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
laplace_fit <- glmm_fit(binary, "Laplace")
slope_laplace <- glmm_fit(slope, "Laplace")
one_node <- glmm_nll_agq(u_true, binary, 1)
local_quadratic <- glmm_nll_laplace(u_true, binary)
print(c(one_node_gap = one_node$value - local_quadratic$value,
scalar_Laplace_own = laplace_fit$value,
scalar_Laplace_common61 = common_scalar(laplace_fit),
intercept_model_difference_in_negative_loglik = common_scalar(laplace_fit) -
common_scalar(adaptive_fit),
slope_Laplace_own = slope_laplace$value,
slope_Laplace_common15 = slope_common(slope_laplace),
slope_model_difference_in_negative_loglik = slope_common(slope_laplace) -
slope_common(slope_agq)))
1
2
3
4
5
6
7
8
one_node_gap scalar_Laplace_own
0.00000000 422.37549765
scalar_Laplace_common61 intercept_model_difference_in_negative_loglik
422.06682612 0.01516077
slope_Laplace_own slope_Laplace_common15
420.84849863 420.02425827
slope_model_difference_in_negative_loglik
0.14618155
The difference at u_true is zero to the precision shown. In laplace_fit$optimizer, the reason field is converged and iterations is 8. The corresponding fields in slope_laplace$optimizer give converged and 13. These counters come from BFGS, which estimated the outer parameters for each model. The equality of one-point AGQ and Laplace checks their algebraic equivalence at common modes and Hessians; it does not show that either equals the exact marginal likelihood.
For the random-intercept model, the first comparison fixes the Laplace estimates. Evaluating them by Laplace gives a negative log likelihood of 422.3755. Evaluating them by adaptive quadrature with 61 points gives 422.0668, a decrease of about 0.30867 due to the integration rule. The second comparison fixes the 61-point rule and changes the estimates. Its value at the Laplace estimates minus its value at the seven-node adaptive estimates is 0.01516.
The same two comparisons apply to the model with a random slope. At its Laplace estimates, the Laplace value is 420.8485 and the adaptive value using 15 points on each axis is 420.0243. Their difference is about 0.82424. With that 15-point rule applied to both fitted parameter vectors, the difference is 0.14618. In both models, a positive difference on the common rule means that rule assigns the observed responses a higher likelihood at the adaptive estimates.
Finer quadrature also uses values away from the mode, which can change where the approximate likelihood is maximized. In the model with a random slope, for example, the fitted slope standard deviation is about 0.366 under Laplace and 0.531 with seven adaptive points per axis. The 0.14618 difference measures the consequence of that entire change in fitted parameters on the common 15-point rule. In the random-intercept model, the fitted intercept standard deviation changes from 0.578 to 0.606 and the common-rule difference is 0.01516. For these data, moving from the Laplace estimates to the adaptive estimates improves the common criterion more in the model with a random slope.
The difference between integration rules can also be examined for each response pattern. For the random-intercept model, the parameters are fixed at the seven-node adaptive estimates. Both calls below use the same fixed coefficients and standard deviation and locate the conditional modes at those values. For each cluster, subtract its 61-node adaptive log integral from its Laplace log integral. These are log probabilities, so a negative discrepancy means a smaller probability under Laplace. All clusters have the same eight covariate values. If $f_j$ is the fixed part of the linear predictor for observation $j$ and $s_i=\sum_j y_{ij}$ is the number of successes, the conditional response log probability at random intercept $b$ is
\[\sum_j y_{ij}f_j+b\,s_i-\sum_j\log\{1+\exp(f_j+b)\}.\]For two patterns with equal totals, only the first term can differ. It adds a constant to either log integral and cancels when the two rules are compared. This explains why the table groups clusters by $s_i$.
1
2
3
4
5
6
7
8
9
laplace_clusters <- glmm_integrate(binary, adaptive_fit$beta, t(chol(adaptive_fit$G)),
"Laplace")
accurate_clusters <- glmm_integrate(binary, adaptive_fit$beta, t(chol(adaptive_fit$G)),
"AGQ", 61)
cluster_table <- data.frame(successes = vapply(binary$blocks, function(b) sum(b$y), 0.0),
log_integral_error = laplace_clusters$loglik_contributions -
accurate_clusters$loglik_contributions)
print(aggregate(log_integral_error ~ successes, cluster_table,
function(x) c(clusters = length(x), mean = mean(x), min = min(x), max = max(x))))
1
2
3
4
5
6
7
8
9
10
successes log_integral_error.clusters log_integral_error.mean log_integral_error.min log_integral_error.max
1 0 3.000000000 -0.003072290 -0.003072290 -0.003072290
2 1 3.000000000 -0.003679888 -0.003679888 -0.003679888
3 2 12.000000000 -0.004123201 -0.004123201 -0.004123201
4 3 25.000000000 -0.004410404 -0.004410404 -0.004410404
5 4 11.000000000 -0.004552040 -0.004552040 -0.004552040
6 5 15.000000000 -0.004554933 -0.004554933 -0.004554933
7 6 6.000000000 -0.004419236 -0.004419236 -0.004419236
8 7 4.000000000 -0.004138365 -0.004138365 -0.004138365
9 8 1.000000000 -0.003701833 -0.003701833 -0.003701833
The 25 clusters with three successes include the first cluster. Each has a Laplace log probability about 0.00441 below the reference. Across all 80 clusters, the discrepancies range from about $-0.00455$ to $-0.00307$. The largest absolute discrepancies occur with four or five successes and the smallest with none. Within each row, the minimum and maximum agree to the displayed precision, as the shared-intercept calculation predicts. The glmmTMB package fits generalized linear mixed models using the Laplace approximation.
9.5 Nested optimization, starting at previous conditional modes, and derivatives of the outer objective function
When the fixed intercept increases, a cluster can partly offset that increase by shifting its conditional random intercept down. How does that movement enter the derivative of the marginal log likelihood? For one cluster, write $h(z,\theta)$ for the log joint density of its observed responses and standardized random effects $z$ at model parameters $\theta$. The inner optimization finds the conditional mode $\hat z(\theta)$ at each value tried by the outer optimizer.
Suppose the mode is finite and $z$ can vary freely in every direction in a neighborhood of it, as it can in $\mathbb R^q$ here. Assume that $h$ is twice continuously differentiable in $(z,\theta)$ nearby and that $h_{zz}$ at the mode is nonsingular. These are conditions on the conditional random-effect calculation, not a shorthand for whether an outer variance estimate is zero. The first derivative with respect to $z$ is zero all along the solution. Differentiating that condition with respect to one outer coordinate $\theta_j$ gives
\[h_z(\hat z(\theta),\theta)=0,\qquad h_{zz}\frac{d\hat z}{d\theta_j}+h_{z\theta_j}=0,\qquad \frac{d\hat z}{d\theta_j}=-h_{zz}^{-1}h_{z\theta_j}.\]Both derivatives on the right are evaluated at the mode. The mixed derivative measures how much the inner gradient changes if $\theta_j$ moves while $z$ remains fixed. The change in the mode restores stationarity.
The Laplace calculation uses both the height and the width of the integrand. In the total derivative of its log height, the term $h_z^\top d\hat z/d\theta_j$ vanishes. For several random effects, the Gaussian integral contributes $-\tfrac12\log\det[-h_{zz}(\hat z,\theta)]$. Stationarity places no such restriction on the derivative of this log determinant. For a scalar random intercept, let $H=-h_{zz}(\hat z,\theta)>0$. The log integral includes $-\tfrac12\log H$ because its width is proportional to $H^{-1/2}$. Its derivative therefore depends on how curvature changes along the solution. For a smooth log joint density with the required third derivatives, write $\tilde\ell$ for the Laplace approximation to this cluster’s log integral. Then
\[\frac{d\tilde\ell}{d\theta_j} =h_{\theta_j}(\hat z,\theta)-\frac{1}{2H}\frac{dH}{d\theta_j}, \qquad \frac{dH}{d\theta_j} =-h_{zz\theta_j}-h_{zzz}\frac{d\hat z}{d\theta_j}.\]In glmm_scalar(), each cluster has one standardized intercept. Write $s$ for the random-intercept standard deviation. The last coordinate of u is $\log s$. A unit change in $z_i$ changes every linear predictor in cluster $i$ by $s$. Different clusters have no mixed second derivatives with respect to their intercepts, so one Newton solve can update the full vector using a diagonal Hessian.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
glmm_scalar <- function(data, nodes = 11L, method = "AGQ", reuse_previous_modes = FALSE,
inner_control = list()) {
stopifnot(data$q == 1L, all(data$Z == 1), method %in% c("GHQ", "AGQ", "Laplace"))
index <- data$group_index
m <- data$groups
aggregate_rows <- function(a) rowsum(as.matrix(a), index, reorder = FALSE)
base <- normal_rule(if (method == "Laplace") 1L else nodes)
previous <- rep(0, m)
last_u <- NULL
last <- NULL
inner_failures <- 0L
failure_reasons <- character()
evaluate <- function(u) {
if (identical(u, last_u)) return(last)
p <- data$p
beta <- head(u, p)
s <- exp(u[p + 1L])
fixed <- drop(data$X %*% beta) + data$offset
terms <- function(z) glmm_response(data$y, fixed + s * z[index], data$family)
h <- function(z) sum(terms(z)$log_density) + sum(dnorm(z, log = TRUE))
# The standard normal prior contributes -z to the inner gradient.
gr <- function(z) s * drop(aggregate_rows(terms(z)$residual)) - z
he <- function(z) -diag(1 + s^2 * drop(aggregate_rows(terms(z)$weight)), m)
inner <- NULL
H <- rep(1, m)
center <- rep(0, m)
dcenter <- dH <- matrix(0, m, p + 1L)
if (method != "GHQ") {
anchor <- if (reuse_previous_modes) previous else rep(0, m)
centered <- function(anchor) {
eta <- fixed + s * anchor[index]
function(z) {
delta <- z - anchor
sum(glmm_log_density_change(data$y, eta, s * delta[index], data$family)) -
sum(anchor * delta) - sum(delta^2) / 2
}
}
approximation <- laplace_approx(centered(anchor), gr, he, anchor, inner_control)
attempts <- list(approximation$inner)
inner <- approximation$inner
if (!approximation$valid) {
inner_failures <<- inner_failures + 1L
failure_reasons <<- c(failure_reasons, inner$reason)
return(list(value = Inf, gradient = rep(NA_real_, p + 1L),
valid = FALSE, inner = inner, reason = inner$reason))
}
approximation$log_integral <- approximation$log_integral + h(anchor)
inner$total_iterations <- sum(vapply(attempts, function(a) a$fit$iterations, 0L))
center <- inner$mode
H <- diag(inner$curvature)
For cluster $i$, the inner gradient in gr() multiplies the sum of response residuals by $s$ and subtracts $z_i$ for the normal prior. The function named centered subtracts the joint log density at the reference point supplied as anchor. Newton’s method minimizes its negative, avoiding subtraction of nearly equal totals.
At the modes, the next block differentiates their locations and curvatures with respect to the fixed coefficients and log standard deviation. For a binary response with conditional probability $p$, the weight is $p(1-p)$ and its derivative with respect to the linear predictor is $p(1-p)(1-2p)$. The total change in the linear predictor includes the movement of the cluster’s conditional mode.
1
2
3
4
5
6
7
8
9
10
t <- terms(center)
W <- drop(aggregate_rows(t$weight))
# One row of mixed derivatives per cluster.
cross <- cbind(-s * aggregate_rows(t$weight * data$X),
s * drop(aggregate_rows(t$residual)) - s^2 * center * W)
dcenter <- cross / H
deta <- cbind(data$X, s * center[index]) + s * dcenter[index, , drop = FALSE]
dH <- s^2 * aggregate_rows(t$third * deta)
dH[, p + 1L] <- dH[, p + 1L] + 2 * s^2 * W
}
Each row of cross contains the mixed derivatives for one cluster. Dividing by that cluster’s positive curvature gives dcenter, with one column per fixed coefficient and one for the log standard deviation. The last column of dH also differentiates the explicit factor $s^2$ in the curvature. These derivatives follow the stationary solution and its negative Hessian. Using the same formulas at a point returned after an unfinished mode search does not make them derivatives of that finite-iteration search procedure.
For a base quadrature point $a$, the adaptive point is $\hat z+a/\sqrt H$. Even when the center moves little, a change in curvature moves the points away from or toward it. At each adaptive point, the derivative of the log term includes the derivative of the conditional log probability of the responses, the derivative of the standard normal log density and the derivative of the log Jacobian. For ordinary quadrature, the points and their weights are fixed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
logterms <- matrix(0, m, length(base$nodes))
derivatives <- array(0, c(m, p + 1L, length(base$nodes)))
for (k in seq_along(base$nodes)) {
a <- base$nodes[k]
z <- center + a / sqrt(H)
# Differentiate the center and the inverse square root of curvature.
dz <- dcenter - .5 * a * dH / H^1.5
t <- terms(z)
logterms[, k] <- drop(aggregate_rows(t$log_density)) + log(base$weights[k])
deta <- cbind(data$X, s * z[index]) + s * dz[index, , drop = FALSE]
derivatives[, , k] <- aggregate_rows(t$residual * deta)
if (method != "GHQ") {
logterms[, k] <- logterms[, k] + dnorm(z, log = TRUE) - dnorm(a,
log = TRUE) - .5 * log(H)
# Derivatives of the normal log density and the log Jacobian.
derivatives[, , k] <- derivatives[, , k] - z * dz - .5 * dH / H
}
}
The row of dz includes changes in both the adaptive center and its scale. Within each cluster, the derivative of the approximated log integral is a weighted average over the quadrature points. A point’s weight in this average is its exponentiated log term divided by the sum over points. Subtracting the largest log term before exponentiation gives the same normalized weights and avoids overflow for finite log terms.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
maximum <- vapply(seq_len(nrow(logterms)), function(i) max(logterms[i, ]), 0)
mass <- exp(logterms - maximum)
posterior <- sweep(mass, 1, rowSums(mass), "/")
contribution <- maximum + log(rowSums(mass))
failed <- which(!is.finite(contribution))
if (length(failed))
return(list(value = Inf, gradient = rep(NA_real_, p + 1L), valid = FALSE,
reason = "nonfinite_cluster_loglik", failed_clusters = failed,
loglik_contributions = contribution, inner = inner))
# Change sign for the negative marginal log likelihood.
gradient <- rep(0, p + 1L)
for (k in seq_along(base$nodes)) gradient <- gradient -
colSums(matrix(derivatives[, , k], m, p + 1L) * posterior[, k])
last_u <<- u
last <<- list(value = -sum(contribution), gradient = gradient, valid = TRUE,
loglik_contributions = contribution, inner = inner, beta = beta, G = matrix(s^2),
method = method, nodes_per_axis = length(base$nodes), number_of_random_effects = 1L,
laplace_sum_gap = if (method == "Laplace") -sum(contribution) +
approximation$log_integral else NA_real_)
if (reuse_previous_modes && !is.null(inner)) previous <<- center
last
}
list(fn = function(u) evaluate(u)$value, gr = function(u) evaluate(u)$gradient,
evaluate = evaluate, diagnostics = function() list(inner_failures = inner_failures,
failure_reasons = failure_reasons))
}
The minus sign in gradient converts the summed log likelihood derivatives to the gradient of the negative marginal log likelihood. If the optimizer asks for the value and then the gradient at identical parameters, both come from the same evaluation. The stored result is reused only when the parameter vector is identical. With reuse_previous_modes = TRUE, a successful evaluation supplies the next starting modes; this is different from the lowest-objective starting record used by glmm_laplace_fit().
A call to the scalar evaluator’s evaluate() computes the contribution of every cluster at one specified parameter vector. If a cluster log integral is nonfinite, the return has value = Inf, an unavailable gradient and valid = FALSE. The reason field reads "nonfinite_cluster_loglik", failed_clusters identifies the affected clusters, and loglik_contributions shows the individual values. A failure during the inner mode calculation takes a different route through the function and returns the inner reason directly. The adaptive fitting procedure also requires a finite contribution from every cluster before reporting the full-data log likelihood. The scalar evaluator does not separately require every gradient component to be finite before setting valid = TRUE. Its inner_failures counter counts rejected inner approximations, not every unfinished Newton search. The adaptive fitting procedure from Section 9.3 uses BFGS to place its nodes and has its own stopping rule.
Consider the first eight responses of binary, the first cluster in data/source/ch09/GLMM80-binary.rds. At the generating values u_true, the fixed intercept is $-0.4$, the slope is $0.8$ and $s=0.7$. Increasing the fixed intercept raises all eight fitted probabilities at a fixed random intercept, so the conditional mode shifts down. The following calculation separates the height and curvature contributions to the derivative of the Laplace log integral.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
one_cluster <- glmm_data(binary$y[1:8], binary$X[1:8, ], matrix(1, 8, 1), rep(1, 8))
one_laplace <- glmm_scalar(one_cluster, method = "Laplace")
implicit <- one_laplace$evaluate(u_true)
z_mode <- implicit$inner$mode
probability <- plogis(drop(one_cluster$X %*% u_true[1:2]) + .7 * z_mode)
w <- probability * (1 - probability)
H <- 1 + .7^2 * sum(w)
z_beta0 <- -.7 * sum(w) / H
H_beta0 <- .7^2 * sum(w * (1 - 2 * probability)) * (1 + .7 * z_beta0)
print(c(laplace_log_integral_derivative_wrt_intercept = -implicit$gradient[1],
laplace_derivative_by_finite_differences = -num_grad(one_laplace$fn,
u_true)$gradient[1],
profile_log_integrand_derivative = sum(one_cluster$y - probability),
subtracted_curvature_term = H_beta0 / (2 * H)))
1
2
3
4
laplace_log_integral_derivative_wrt_intercept laplace_derivative_by_finite_differences
-0.16107362 -0.16107362
profile_log_integrand_derivative subtracted_curvature_term
-0.13745287 0.02362075
Here z_beta0 is negative. The multiplier $1+0.7\,d\hat z/d\beta_0$ in H_beta0 gives the resulting change in each linear predictor per unit change in the fixed intercept.
The last two numbers show the terms of the derivative. The sum of the eight response residuals gives $-0.13745$, the derivative of the log integrand with respect to the fixed intercept at the conditional mode. Half the derivative of $\log H$ is $0.02362$. Subtracting it gives $-0.16107$ for the derivative of the Laplace log integral. The first printed component obtains that sign by negating implicit$gradient[1]. The second negates a numerical derivative of the same cluster’s negative Laplace log likelihood. num_grad() uses its default Richardson calculation (Section 3.1). The two calculations agree to eight decimal places.
Inner accuracy and outer convergence
The accuracy of a numerical outer gradient depends on both the mode calculation and the difference step. The table varies these two settings separately for the first cluster.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
accuracy_rows <- list()
accurate_gradient <- implicit$gradient
for (tolerance in c(1e-3, 1e-6, 1e-10)) for (step in c(1e-2, 1e-4, 1e-6)) {
objective <- glmm_scalar(one_cluster, method = "Laplace",
inner_control = list(tol = tolerance))
evaluation <- objective$evaluate(u_true)
derivative <- num_grad(objective$fn, u_true, step = step)$gradient
accuracy_rows[[length(accuracy_rows) + 1L]] <- data.frame(inner_tolerance = tolerance,
difference_step = step, absolute_log_integrand_derivative_at_mode =
max(abs(evaluation$inner$log_integrand_gradient)),
negative_loglik_difference = evaluation$value - implicit$value,
gradient_error = max(abs(derivative - accurate_gradient)))
}
accuracy_table <- do.call(rbind, accuracy_rows)
print(accuracy_table, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
inner_tolerance difference_step absolute_log_integrand_derivative_at_mode negative_loglik_difference
1e-03 1e-02 4.898276e-04 8.161337e-06
1e-03 1e-04 4.898276e-04 8.161337e-06
1e-03 1e-06 4.898276e-04 8.161337e-06
1e-06 1e-02 3.966093e-09 0.000000e+00
1e-06 1e-04 3.966093e-09 0.000000e+00
1e-06 1e-06 3.966093e-09 0.000000e+00
1e-10 1e-02 1.387779e-17 -6.557777e-11
1e-10 1e-04 1.387779e-17 -6.557777e-11
1e-10 1e-06 1.387779e-17 -6.557777e-11
gradient_error
9.060394e-05
8.985755e-05
8.985680e-05
2.704521e-06
1.587201e-09
1.125348e-09
2.704523e-06
2.407168e-10
6.510090e-10
Each row uses the same eight responses. The reference for gradient_error is implicit$gradient, calculated by differentiating the Laplace formula with the default inner Newton tolerance of $10^{-8}$. For a row of the table, num_grad() instead perturbs one outer coordinate at a time by the specified absolute difference_step in either direction. Each perturbed evaluation solves for its own mode with that row’s tolerance. The error column reports the largest absolute difference from the reference over the intercept, slope and log standard deviation. The signed negative_loglik_difference subtracts the reference negative Laplace log likelihood from the value at the same unperturbed parameters.
With inner tolerance $10^{-3}$, the absolute derivative of the log integrand with respect to the standardized intercept at the returned mode is $4.9\times10^{-4}$. The negative log likelihood is about $8.2\times10^{-6}$ above its reference. Reducing the difference step from $10^{-2}$ to $10^{-6}$ leaves the gradient error near $9\times10^{-5}$. With tolerance $10^{-6}$, the last Newton update reduces the absolute inner derivative to $4.0\times10^{-9}$. The largest difference step gives an outer gradient error of $2.7\times10^{-6}$, while steps $10^{-4}$ and $10^{-6}$ give $1.6\times10^{-9}$ and $1.1\times10^{-9}$. Tightening the inner tolerance to $10^{-10}$ brings the absolute inner derivative to $1.4\times10^{-17}$. The two shorter steps give errors of $2.4\times10^{-10}$ and $6.5\times10^{-10}$, and the longest still gives about $2.7\times10^{-6}$. Further tightening therefore yields no uniform improvement in accuracy across the three steps. The table compares two ways of differentiating the Laplace approximation. Their differences alone cannot separate the effects of mode finding, finite difference truncation and rounding.
What happens to the full-data Laplace value if each cluster search can take only one Newton step?
1
2
3
4
5
failed_inner <- glmm_nll_laplace(u_true, binary, starts = matrix(3,80,1),
control = list(maxit = 1L))
print(c(valid = failed_inner$valid,
failed_clusters = length(failed_inner$failed_clusters),
returned_nll = failed_inner$value))
1
2
valid failed_clusters returned_nll
1.0000 0.0000 441.8853
glmm_nll_laplace() starts each of the 80 cluster searches at 3 and permits one Newton iteration per cluster. The returned total negative log likelihood is 441.8853, with a valid evaluation and zero failed clusters. The field failed_inner$clusters[[1]]$mode_search$fit$reason is "iteration_limit". The approximation was evaluated at the centers returned by unfinished mode searches, so valid does not certify an accurate mode calculation. Here the overall validity flag describes the integral calculation, while the reason inside the first cluster describes its Newton search. Neither field measures convergence of an outer parameter fit.
How many inner iterations does reusing modes save at comparable accuracy? The seven vectors in path move the fixed intercept and log standard deviation up together and the slope down by half as much. At each vector, evaluate_path() solves jointly for all 80 standardized modes and evaluates the negative marginal log likelihood by adaptive quadrature with 15 points per cluster. The first forward pass starts every search at zero. The next starts at zero once and uses the preceding solution thereafter. A third pass visits the same vectors in reverse order, beginning at zero at the other end.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
path <- lapply(seq(0, .02, length.out = 7), function(a) u_true + c(a, -a / 2, a))
evaluate_path <- function(reuse_previous_modes, order) {
objective <- glmm_scalar(binary, 15, reuse_previous_modes = reuse_previous_modes)
result <- lapply(path[order], objective$evaluate)
list(value = vapply(result, `[[`, 0.0, "value"),
gradient = do.call(rbind, lapply(result, `[[`, "gradient")),
iterations = vapply(result, function(r) r$inner$total_iterations, 0L))
}
from_zero <- evaluate_path(FALSE, 1:7)
from_previous_modes <- evaluate_path(TRUE, 1:7)
reverse <- evaluate_path(TRUE, 7:1)
print(c(previous_mode_value_gap = max(abs(from_previous_modes$value-from_zero$value)),
reverse_value_gap = max(abs(rev(reverse$value)-from_zero$value)),
previous_mode_gradient_gap = max(abs(from_previous_modes$gradient-from_zero$gradient)),
reverse_gradient_gap = max(abs(reverse$gradient[7:1,]-from_zero$gradient)),
joint_newton_steps_from_zero = sum(from_zero$iterations),
joint_newton_steps_from_previous_modes = sum(from_previous_modes$iterations)))
1
2
3
4
5
6
previous_mode_value_gap reverse_value_gap
5.684342e-14 5.684342e-14
previous_mode_gradient_gap reverse_gradient_gap
5.329071e-15 7.105427e-15
joint_newton_steps_from_zero joint_newton_steps_from_previous_modes
3.500000e+01 2.300000e+01
Reversing the third gradient matrix’s rows and its value vector aligns the parameter vectors with the first pass. Across these comparisons the maximum absolute differences are $5.68\times10^{-14}$ in value and $7.11\times10^{-15}$ in gradient components. The last two entries sum the forward iteration counts over seven evaluations. joint_newton_steps_from_zero is 35 and joint_newton_steps_from_previous_modes is 23. One joint Newton iteration updates the vector of modes for all 80 clusters.
A comparison of computational effort requires a stated accuracy for negative log likelihood values and gradients at common parameter vectors. An optimizer’s convergence message describes its own stopping test. It gives no numerical bound on the change in a cluster log integral when the mode is calculated more accurately. Over the seven specified vectors, starting from the preceding modes saved 12 joint Newton iterations while reproducing the negative log likelihood values and gradients to the precision observed in both orders. The TMB package provides Laplace approximation with derivatives through the conditional modes.
9.6 Penalized quasi-likelihood as repeated linear mixed model fitting
A binary response records a zero or one, but a linear mixed model needs a response on the same scale as its linear predictor. Penalized quasi-likelihood (PQL) constructs such a response at the current fitted probability. For one response $Y$ conditional on its cluster’s random effects $b$, write $\mu(\eta)$ for its mean. At the current value $\eta_0$ of the linear predictor, let $\mu_0=\mu(\eta_0)$ and $d_0=\mu^{\prime}(\eta_0)$. The first-order expansion $\mu(\eta)\approx\mu_0+d_0(\eta-\eta_0)$ converts a response residual into a change on the scale of the linear predictor. With $d_0\ne0$, replacing the mean on the left by the observed $y$ and solving for the linear predictor gives the working response $y^\ast $. With the expansion point fixed, dividing the response residual by $d_0$ also gives its conditional working variance. This working response becomes the dependent variable in the iteratively weighted calculation.
\[y^*=\eta_0+\frac{y-\mu_0}{d_0},\qquad \operatorname{Var}_0(Y^*\mid b)=\frac{\operatorname{Var}_0(Y\mid b)}{d_0^2}.\]At a fitted Bernoulli probability of one half, the logit is zero and $d_0=1/4$. A success moves the working response up by two logit units, and a failure moves it down by two.
The working responses within a cluster share the same random effects as the original observations. Let $y_i^\ast $ collect them for cluster $i$, and let $o_i$ be its vector of known offsets. With design matrices $X_i$ for the fixed effects and $Z_i$ for the random effects, the working linear mixed model is
\[y_i^*-o_i=X_i\beta+Z_i b_i+e_i,\qquad b_i\sim N(0,G).\]Here $e_i$ is a Gaussian working residual with independent coordinates conditional on $b_i$. Each observation has its own precision weight, the reciprocal of its conditional working variance from the expansion. The weighted fit measures squared residuals on the scale of the linear predictor and the normal distribution of $b_i$ penalizes departures from zero through $b_i^\top G^{-1}b_i$. Predicted random effects from this fit help locate the point for the next expansion. This is a Gaussian approximation used for the fitting step. Transforming a binary or count response in this way does not make its actual distribution Gaussian.
In the Bernoulli logit model, the derivative and the conditional response variance both equal $\mu(1-\mu)$, so the precision weight $w=(d\mu/d\eta)^2/\operatorname{Var}(Y\mid b)$ reduces to $\mu(1-\mu)$. With a Poisson log link function, both equal $\mu$ and $w=\mu$. These response models specify unit dispersion.
In this implementation, following MASS::glmmPQL(), the Gaussian fit treats the current weights as a fixed variance function and estimates a common residual variance $\sigma_w^2$. Thus the fitted residual variance for observation $j$ in cluster $i$ is $\hat\sigma_w^2/w_{ij}$. The weight specifies the relative precision of the row. The estimated working residual variance describes residual variation in the working responses and introduces no dispersion parameter into the original Bernoulli or Poisson model. Estimating this variance by Gaussian maximum likelihood (ML) is a choice of the implementation; it is not part of the definition of every PQL procedure.
The three code blocks below form glmm_pql(), which alternates between constructing working responses and fitting a weighted Gaussian mixed model. For the binary and count data, a generalized linear model with zero offsets and no random effects supplies the starting values. The initialization uses the linear predictors immediately before and after the last update of iteratively reweighted least squares (IRLS).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
glmm_pql <- function(data, n_rounds = 10L) {
family <- switch(data$family, binomial = binomial(), poisson = poisson(),
normal = gaussian())
if (data$family == "normal") {
beta <- drop(qr.coef(qr(data$X), data$y - data$offset))
eta <- drop(data$X %*% beta) + data$offset
zz <- data$y - data$offset
wz <- rep(1, data$N)
} else {
stopifnot(all(data$offset == 0))
reduced <- fit_glm(make_glm(data$X, data$y, data$family), method = "irls")
eta <- drop(data$X %*% reduced$par)
# The last IRLS fit used weights from the linear predictor before its update.
k <- length(reduced$history)
eta_previous <- if (k >= 2) drop(data$X %*% reduced$history[[k - 1]]$par) else
family$linkfun(if (data$family == "binomial") (data$y + .5) / 2 else data$y + .1)
mu_previous <- family$linkinv(eta_previous)
wz <- family$mu.eta(eta_previous)^2 / family$variance(mu_previous)
# Form the working response at the final GLM linear predictor.
zz <- eta + (data$y - family$linkinv(eta)) / family$mu.eta(eta)
}
The returned GLM coefficients give the linear predictor eta used in the working response zz. The last least-squares update used weights computed before that update, so eta_previous gives the first precision weights wz. If that update was the first, the code recovers its starting linear predictor from the responses.
For each working response, lmm_fit() attempts to maximize the profiled Gaussian likelihood and must satisfy its own stopping test before the PQL loop continues. The fitted coefficients and predicted random effects then give the next linear predictors.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
history <- list()
converged <- FALSE
reason <- "iteration_limit"
for (iteration in seq_len(n_rounds)) {
working <- lmm_design(zz, data$X, data$Z, data$id, wz)
fit <- lmm_fit(working, control = list(optimizer = "optim", variance_function = TRUE))
if (!fit$optimizer$converged) stop("working fit: ", fit$optimizer$reason)
b <- do.call(rbind, lapply(lmm_conditional(working, fit$beta, fit$G, fit$sigma2),
`[[`, "mean"))
# Match each observation to the cluster row of conditional means.
b_row <- match(as.character(data$id), vapply(working$blocks, `[[`, "", "id"))
eta_old <- eta
eta <- drop(data$X %*% fit$beta) +
rowSums(data$Z * b[b_row, , drop = FALSE]) + data$offset
Each row of b contains the conditional mean of one cluster’s random effects in the fitted Gaussian model. The order of working$blocks determines those rows. Matching group IDs gives b_row, so each observation’s random design row multiplies the conditional mean for its own cluster. Adding this product to the fixed part of the linear predictor and the offset gives its new eta. For the working fit, BFGS uses central differences with step $10^{-3}$, an iteration limit of 50 and relative tolerance $10^{-7}$.
The PQL loop stops when the sum of squared changes in the linear predictors over all observations falls below $10^{-6}$ times the sum of squared new linear predictors. If the test fails, the new linear predictor determines both the next working response and its weights. The default allows ten Gaussian fits.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Sum squared changes in the linear predictors across observations.
change <- sum((eta - eta_old)^2) / sum(eta^2)
history[[iteration]] <- list(change = change, beta = fit$beta, G = fit$G,
working_value = fit$value, optimizer = fit$optimizer)
if (sum((eta - eta_old)^2) < sum(eta^2) * 1e-6) {
converged <- TRUE
reason <- "stable_linear_predictor"
break
}
mu <- family$linkinv(eta)
zz <- eta + (data$y - mu) / family$mu.eta(eta) - data$offset
wz <- family$mu.eta(eta)^2 / family$variance(mu)
}
list(beta = fit$beta, G = fit$G, eta = eta, converged = converged, reason = reason,
iterations = length(history), history = history, residual_variance = fit$sigma2,
working_criterion = "normal ML", method = "PQL",
loglik_contributions = NULL, value = NA_real_)
}
The Bernoulli and Poisson calculations replace the nonlinear mean by its tangent and use the response variance at the expansion point. Integrating the resulting Gaussian density over the random effects gives a likelihood for the working responses. Its data and weights can change at the next fit. The GLMM marginal likelihood instead integrates the original conditional response probabilities over the random effects. The linearization can be checked where the response mean is already linear. For the normal responses in GROWTH4.rds, the identity link function has derivative one, the offset is zero, and the working response equals the observed response with unit weight at every step.
1
2
3
4
5
6
7
8
9
10
11
growth_rows <- readRDS("data/source/ch07/GROWTH4.rds")$long
normal_X <- cbind(1, growth_rows$time)
normal_data <- glmm_data(growth_rows$response, normal_X, normal_X, growth_rows$person,
"normal")
normal_pql <- glmm_pql(normal_data)
# Fit the Gaussian model directly with the same working-model settings.
normal_exact <- lmm_fit(lmm_design(normal_data$y, normal_X, normal_X, normal_data$id),
control = list(optimizer = "optim", variance_function = TRUE))
print(c(normal_beta_gap = max(abs(normal_pql$beta - normal_exact$beta)),
normal_G_gap = max(abs(normal_pql$G - normal_exact$G)),
residual_variance_gap = normal_pql$residual_variance - normal_exact$sigma2))
1
2
normal_beta_gap normal_G_gap residual_variance_gap
0 0 0
Both designs contain an intercept and time. A single direct Gaussian fit reproduced the returned fixed effects, every entry of the random-intercept and slope covariance matrix, and the residual variance. The three zeros measure differences between estimates. They give no count of the working fits made by the PQL loop. Both Gaussian fits estimate a free residual variance. This comparison does not use the unit residual variance imposed by the "normal" branch of glmm_response().
Comparing PQL with quadrature
PQL does not evaluate the marginal likelihood of the original responses. For the binary and count responses, a separate evaluation of the marginal likelihood at the returned estimates makes the fitted parameters comparable. The following source call also loads glmm_endpoint() for the score checks after this comparison.
1
source("code/checks/glmm_endpoint.R")
The binary quadrature fit already uses seven adaptive points. The next block obtains PQL fits for the binary and count data and a count fit with 15 adaptive points.
1
2
3
pql_binary <- glmm_pql(binary)
pql_count <- glmm_pql(count)
count_agq <- glmm_fit(count, "AGQ", 15)
The four rows below evaluate the PQL and quadrature estimates using the same 61-point adaptive rule within each dataset. This gives a common marginal-likelihood criterion even though PQL itself optimizes changing Gaussian working criteria.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
pql_table <- rbind(
data.frame(family = "binomial", method = "PQL", intercept = pql_binary$beta[1],
slope = pql_binary$beta[2],
SD = sqrt(pql_binary$G[1]), common61_nll = common_scalar(pql_binary),
iterations = pql_binary$iterations),
data.frame(family = "binomial", method = "AGQ", intercept = adaptive_fit$beta[1],
slope = adaptive_fit$beta[2],
SD = sqrt(adaptive_fit$G[1]), common61_nll = common_scalar(adaptive_fit),
iterations = adaptive_fit$optimizer$iterations),
data.frame(family = "poisson", method = "PQL", intercept = pql_count$beta[1],
slope = pql_count$beta[2],
SD = sqrt(pql_count$G[1]), common61_nll = glmm_integrate(count,pql_count$beta,
t(chol(pql_count$G)),"AGQ",61)$value,
iterations = pql_count$iterations),
data.frame(family = "poisson", method = "AGQ", intercept = count_agq$beta[1],
slope = count_agq$beta[2],
SD = sqrt(count_agq$G[1]), common61_nll = glmm_integrate(count,count_agq$beta,
t(chol(count_agq$G)),"AGQ",61)$value,
iterations = count_agq$optimizer$iterations))
print(pql_table, row.names = FALSE)
1
2
3
4
5
family method intercept slope SD common61_nll iterations
binomial PQL -0.1820426 0.6873733 0.5799534 422.0925 3
binomial AGQ -0.1911970 0.7212408 0.6057595 422.0517 31
poisson PQL 0.2990367 0.5153522 0.8210374 1026.7329 7
poisson AGQ 0.2532617 0.5153489 0.8465711 1026.5894 50
For the binary data, PQL gives a slope of 0.68737 and a random-intercept standard deviation of 0.57995. Adaptive quadrature gives 0.72124 and 0.60576. The common negative log likelihood is 422.0925 at the PQL estimates and 422.0517 at the quadrature estimates. For the counts, the corresponding standard deviations are 0.82104 and 0.84657 and the common values are 1026.7329 and 1026.5894.
PQL itself returns value = NA_real_. The missing value is deliberate: the changing Gaussian working criteria are not the marginal log likelihood of the original responses.
Why are the count slopes, 0.5153522 and 0.5153489, so close? All clusters have the same covariate values $x_j$ and zero offsets. Given the cluster total $T_i=\sum_j y_{ij}$, the counts are multinomial with probabilities $e^{x_j\beta_1}/S$, where $S=S(\beta_1)=\sum_j e^{x_j\beta_1}$. The random intercept cancels from these probabilities. Given random intercept $b_i$, the mean of $T_i$ is $e^{\beta_0+b_i}S$. Thus the likelihood for the totals depends on the slope through $\beta_0+\log S$, which a free intercept can absorb.
At a PQL fixed point, multiplying the working residual by its Poisson weight gives $y_{ij}-\mu_{ij}$. The fixed-effect equations become $\sum_{ij}(y_{ij}-\mu_{ij})=0$ for the intercept and $\sum_{ij}x_j(y_{ij}-\mu_{ij})=0$ for the slope. Since the fitted counts within each cluster are proportional to $e^{x_j\beta_1}$, eliminating the fitted total gives the slope equation obtained by differentiating the conditional multinomial log likelihood.
\[\sum_{ij}x_jy_{ij}=\left(\sum_i T_i\right)\frac{S'(\beta_1)}{S(\beta_1)}.\]This shared equation explains the slope agreement to about $3.3\times10^{-6}$ under the finite stopping tolerances. The next print gives the final changes for PQL.
1
2
3
print(c(binary_converged = pql_binary$converged, count_converged = pql_count$converged,
binary_last_change = tail(pql_binary$history,1)[[1]]$change,
count_last_change = tail(pql_count$history,1)[[1]]$change))
1
2
binary_converged count_converged binary_last_change count_last_change
1.000000e+00 1.000000e+00 9.758218e-07 2.237661e-08
Both PQL runs met the tolerance of $10^{-6}$ on the ratio of the sum of squared changes to the sum of squared new linear predictors, with final ratios of $9.8\times10^{-7}$ and $2.2\times10^{-8}$. Their iteration counts of 3 and 7 are Gaussian working fits. The quadrature counts of 31 and 50 add EM updates to reported BFGS iterations.
Within a cluster, a one-unit increase in the covariate adds 0.68737 to the fitted binary log odds under PQL. For the counts, it adds 0.51535 to the fitted log mean at the same random intercept. The fitted standard deviation measures between-cluster variation in the intercept on the scale of each model’s linear predictor. With eight binary observations per cluster, PQL gave a smaller standard deviation than quadrature in this sample. Assessing bias requires comparing estimates across repeated samples with the generating standard deviation and accounting for which fits returned estimates.
Scores at the returned quadrature estimates
Before comparing quadrature rules more closely, check the log likelihood derivatives at the returned quadrature estimates. The supplied glmm_endpoint() takes the grouped data, a fitted result and two comparison labels. It returns one diagnostic row per parameter coordinate, evaluating scores without refitting the model.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
glmm_endpoint <- function(data,fit,id,method) {
error <- inherits(fit,"error")
opt <- if (!error) fit$optimizer
reason <- if (error) conditionMessage(fit) else fit$reason
boundary <- !error && !is.null(fit$G) && all(fit$G==0)
q <- data$q
theta <- if (!error && !is.null(fit$theta) && !boundary) fit$theta else
if (!error && all(is.finite(fit$beta)) && length(fit$G)==1L && fit$G[1]>0)
c(fit$beta,.5*log(fit$G[1])) else rep(NA_real_,data$p+q*(q+1L)/2L)
if(boundary) theta[seq_len(data$p)] <- fit$beta
reported <- rep(NA_real_,length(theta))
if (length(opt$score)==length(theta)) reported <- opt$score
problem <- character()
rule <- if(data$family=="poisson") "AGQ" else "GHQ"
evaluate <- function(n) tryCatch({
if (boundary) {
# Fixed-effect score components at zero random-effect variance.
eta <- drop(data$X %*% fit$beta)+data$offset
terms <- glmm_response(data$y,eta,data$family)
s <- drop(crossprod(data$X,terms$residual))
return(c(s,NA_real_))
}
if(any(!is.finite(theta))) stop("no finite coordinates")
sc <- if(q==1L) -glmm_scalar(data,n,rule)$gr(theta) else {
fn <- function(v) glmm_integrate(data,v[seq_len(data$p)],
t(chol(glmm_par_to_D(v[-seq_len(data$p)]))),rule,n)$value
-num_grad(fn,theta)$gradient
}
if(any(!is.finite(sc))) stop("nonfinite score")
sc
},error=function(e) {problem <<- c(problem,paste0(n,": ",conditionMessage(e))); rep(NA_real_,length(theta))})
s31 <- evaluate(31L)
s61 <- evaluate(61L)
right <- NA_real_
if(boundary && q==1L) {
eta <- drop(data$X %*% fit$beta)+data$offset
mu <- if(data$family=="poisson") exp(eta) else plogis(eta)
vv <- if(data$family=="poisson") mu else mu*(1-mu)
z <- data$Z[,1]
right <- .5*sum(rowsum(z*(data$y-mu),data$id)^2-rowsum(z^2*vv,data$id))
}
data.frame(id=id,method=method,coordinate=seq_along(theta),estimate=theta,
groups=data$groups,converged=!error && isTRUE(fit$converged),
reason=if(length(reason)) reason else NA_character_,boundary=boundary,right_loglik_derivative_at_zero_variance=right,
em=if(length(opt$em_updates)) opt$em_updates else NA_integer_,
bfgs_iterations=paste(opt$bfgs_iterations,collapse="+"),bfgs_stops=paste(opt$bfgs_reason,collapse="+"),
reported_score_component=reported,quadrature_rule=rule,score_component_31_nodes=s31,score_component_61_nodes=s61,difference_61_minus_31=s61-s31,
score_component_61_nodes_per_group=s61/data$groups,diagnostic=paste(problem,collapse=" | "))
}
A failed fit gives missing coordinates and its error message as reason. When the fitted random-effect covariance is zero, boundary is true: the score components for the fixed coefficients are then $X^\top(y-\mu)$ from glmm_response(), and for a single random intercept right is the derivative of the log likelihood with respect to its variance at zero, $\tfrac12\sum_i\lbrace (\sum_jz_{ij}(y_{ij}-\mu_{ij}))^2-\sum_jz_{ij}^2v_{ij}\rbrace $, with $v_{ij}$ the conditional variance of $y_{ij}$. Otherwise evaluate() computes the score at the reported coordinates with 31 and with 61 nodes, Gauss-Hermite for binary responses and adaptive for counts: analytically through glmm_scalar() for one random effect, and by num_grad() (Section 3.1) applied to the negative log likelihood of glmm_integrate() for more. An evaluation that fails is recorded in diagnostic. Each row reports the coordinate, the convergence record of the fit, the score reported by the optimizer, the two quadrature scores, their difference and the 61-node score per group.
The binary random-intercept fits use 31 fixed or seven adaptive points, and the random-slope fit uses seven adaptive points per axis. The new count fit uses 15 adaptive points. Each row below corresponds to one fixed coefficient or covariance coordinate of one fit. For the random-slope fit, coordinates 1–5 are $(\beta_0,\beta_1,\log U_{11},U_{12},\log U_{22})$ with $G=U^\top U$. The fifth coordinate is not generally the log marginal standard deviation of the slope.
In the output, reported_score_component comes from the fit. The columns score_component_31_nodes and score_component_61_nodes evaluate the same log likelihood derivative at 31 and 61 points per axis, using fixed nodes for the binary models and adaptive nodes for the counts. Their difference subtracts the 31-point score from the 61-point score. Dividing the latter by 80 gives the derivative per cluster.
1
2
3
4
5
6
# Evaluate each score component at its fitted parameter vector.
fit_endpoints <- rbind(glmm_endpoint(binary,fixed_fit,"9.3","GHQ31"),
glmm_endpoint(binary,adaptive_fit,"9.3","AGQ7"),glmm_endpoint(slope,slope_agq,"slope",
"AGQ7"),
glmm_endpoint(count,count_agq,"count","AGQ15"))
print(fit_endpoints)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
id method coordinate estimate groups converged reason boundary
intercept 9.3 GHQ31 1 -0.19119729 80 TRUE converged_during_BFGS FALSE
x 9.3 GHQ31 2 0.72124182 80 TRUE converged_during_BFGS FALSE
9.3 GHQ31 3 -0.50126148 80 TRUE converged_during_BFGS FALSE
intercept1 9.3 AGQ7 1 -0.19119697 80 TRUE converged_during_BFGS FALSE
x1 9.3 AGQ7 2 0.72124082 80 TRUE converged_during_BFGS FALSE
6 9.3 AGQ7 3 -0.50127218 80 TRUE converged_during_BFGS FALSE
1 slope AGQ7 1 -0.23714306 80 TRUE converged_during_BFGS FALSE
2 slope AGQ7 2 0.60867001 80 TRUE converged_during_BFGS FALSE
3 slope AGQ7 3 -0.17597118 80 TRUE converged_during_BFGS FALSE
4 slope AGQ7 4 -0.03335902 80 TRUE converged_during_BFGS FALSE
5 slope AGQ7 5 -0.63535567 80 TRUE converged_during_BFGS FALSE
intercept2 count AGQ15 1 0.25326165 80 TRUE converged_during_BFGS FALSE
x2 count AGQ15 2 0.51534892 80 TRUE converged_during_BFGS FALSE
7 count AGQ15 3 -0.16656104 80 TRUE converged_during_BFGS FALSE
right_loglik_derivative_at_zero_variance em bfgs_iterations bfgs_stops
intercept NA 30 1 converged
x NA 30 1 converged
NA 30 1 converged
intercept1 NA 30 1 converged
x1 NA 30 1 converged
6 NA 30 1 converged
1 NA 30 10+10 iteration_limit+converged
2 NA 30 10+10 iteration_limit+converged
3 NA 30 10+10 iteration_limit+converged
4 NA 30 10+10 iteration_limit+converged
5 NA 30 10+10 iteration_limit+converged
intercept2 NA 30 10+10 iteration_limit+converged
x2 NA 30 10+10 iteration_limit+converged
7 NA 30 10+10 iteration_limit+converged
reported_score_component quadrature_rule score_component_31_nodes score_component_61_nodes
intercept 0.0005131636 GHQ 0.0005131636 0.0005131636
x -0.0019757424 GHQ -0.0019757424 -0.0019757424
-0.1206252897 GHQ -0.1206252897 -0.1206252897
intercept1 0.0005123175 GHQ 0.0005065706 0.0005065706
x1 -0.0019737540 GHQ -0.0019736073 -0.0019736073
6 -0.1205066527 GHQ -0.1204219698 -0.1204219698
1 0.0003299430 GHQ 0.0004260502 0.0004260408
2 0.0006616546 GHQ 0.0006760596 0.0006760329
3 -0.0036814636 GHQ -0.0024013232 -0.0024014012
4 0.0166307661 GHQ 0.0167415488 0.0167416604
5 0.0029682300 GHQ 0.0029763500 0.0029763785
intercept2 0.0003266803 AGQ 0.0003215375 0.0003215375
x2 0.0017323204 AGQ 0.0017312103 0.0017312103
7 0.0594586182 AGQ 0.0594652863 0.0594652862
difference_61_minus_31 score_component_61_nodes_per_group diagnostic
intercept 2.242315e-12 6.414545e-06
x 9.266563e-13 -2.469678e-05
-5.304909e-12 -1.507816e-03
intercept1 2.230781e-12 6.332132e-06
x1 9.203974e-13 -2.467009e-05
6 -5.294862e-12 -1.505275e-03
1 -9.370743e-09 5.325510e-06
2 -2.665374e-08 8.450412e-06
3 -7.800387e-08 -3.001752e-05
4 1.115888e-07 2.092708e-04
5 2.842513e-08 3.720473e-05
intercept2 9.145574e-12 4.019218e-06
x2 1.978293e-12 2.164013e-05
7 -1.157618e-10 7.433161e-04
The largest absolute score per cluster in the random-slope fit is 0.00020927, on the off-diagonal Cholesky coordinate. In the count fit, it is 0.00074332, on the log standard deviation. Both fits recorded two BFGS runs with iteration counters of ten after 30 EM updates. Division by the number of clusters changes the reporting scale; it does not remove dependence on the units of the parameters or establish a universal convergence threshold.
9.7 Checking quadrature accuracy and repeated-sample estimation error
In the binary example, moving from Laplace to seven adaptive points increased the estimated random-intercept standard deviation. How much does the estimate change if the rule is refined again? The five fits below use binary, the same eight responses per cluster from data/source/ch09/GLMM80-binary.rds.
With one point, glmm_fit() calls glmm_laplace_fit(). With 3, 7, 15 or 31 points, it uses EM and BFGS. In each row, own_nll is the negative log likelihood from that fit. The function common_scalar() reevaluates all 80 cluster integrals at the returned fixed coefficients and random-intercept standard deviation (SD), using 61 adaptive points per cluster. Moving across a row changes the integration rule at fixed parameter values. Moving down the common column changes the fitted values of the parameters under one rule. The one-point row therefore changes both the approximation and the fitting procedure. Differences from the multi-point rows cannot be attributed to node count alone.
1
2
3
4
5
6
7
8
9
10
node_grid <- c(1L,3L,7L,15L,31L)
node_fits <- lapply(node_grid, function(n) glmm_fit(binary, "AGQ", n))
node_table <- data.frame(nodes=node_grid,
intercept=vapply(node_fits,function(f) f$beta[1],0.0),
slope=vapply(node_fits,function(f) f$beta[2],0.0),
SD=vapply(node_fits,function(f) sqrt(f$G[1]),0.0),
# Evaluate each estimate under its fitted rule and under the common rule.
own_nll=vapply(node_fits,`[[`,0.0,"value"),
common61_nll=vapply(node_fits,common_scalar,0.0))
print(node_table,row.names=FALSE)
1
2
3
4
5
6
nodes intercept slope SD own_nll common61_nll
1 -0.1903597 0.7190606 0.5775068 422.3755 422.0668
3 -0.1902872 0.7184943 0.5891457 422.0595 422.0555
7 -0.1911970 0.7212408 0.6057595 422.0517 422.0517
15 -0.1911973 0.7212418 0.6057660 422.0517 422.0517
31 -0.1911973 0.7212418 0.6057660 422.0517 422.0517
The estimated SD rises from 0.57751 with one point to 0.58915 with three, then to 0.6057595 with seven. The 15- and 31-point estimates both round to 0.6057660. The fixed slope first decreases and then increases. In the first row, the fit’s own criterion of 422.3755 exceeds the common evaluation of 422.0668 by about 0.31. With three points, the corresponding values are 422.0595 and 422.0555. Both columns round to 422.0517 from seven points onward. One further comparison uses the 31-point estimates for both evaluations.
1
print(c(AGQ31_61_gap=common_scalar(node_fits[[5]],31)-common_scalar(node_fits[[5]],61)))
1
2
AGQ31_61_gap
0
The computed 31-point minus 61-point difference is zero at those estimates. Agreement in the sum leaves open whether the two rules assign similar probabilities to individual response patterns. A zero reported difference is agreement of two computed approximations at this parameter vector, not a bound of zero on their integration errors.
The success totals in cluster_table identify the three selected clusters: the first cluster, the first with no successes and the only cluster with eight. At the 31-point estimates, glmm_integrand() supplies the log joint density h() of the responses and standardized random intercept for each selected cluster. The call to integrate() exponentiates it and integrates on the real line. On the quadrature side, agh_rule() places the adaptive points of Section 5.4 for each cluster, and log_quadrature() (Section 5.3) sums the weighted contributions on the log scale.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
selected_clusters <- unique(c(1L, which.min(cluster_table$successes),
which.max(cluster_table$successes)))
reference_accuracy <- do.call(rbind, lapply(selected_clusters, function(i) {
f <- glmm_integrand(binary$blocks[[i]], node_fits[[5]]$beta, t(chol(node_fits[[5]]$G)),
"binomial")
# Integrate the joint density on its original scale.
independent <- stats::integrate(function(z) vapply(z, function(a) exp(f$h(a)), 0.0),
-Inf, Inf)
adaptive <- log_quadrature(f$h, agh_rule(61, f$h, f$gr))
data.frame(cluster = i, successes = sum(binary$blocks[[i]]$y),
log_integral = log(independent$value),
AGQ61_gap = adaptive$log_integral - log(independent$value),
integration_relative_error_estimate = independent$abs.error / independent$value)
}))
print(reference_accuracy, row.names = FALSE)
1
2
3
4
cluster successes log_integral AGQ61_gap integration_relative_error_estimate
1 3 -4.891201 2.453793e-07 0.007916433
33 0 -3.792133 5.578022e-09 0.001959620
40 8 -4.729877 1.404252e-08 0.003732509
The logs of the integrals returned by integrate() are $-4.891201$, $-3.792133$ and $-4.729877$ for clusters 1, 33 and 40. Subtracting these from the respective 61-point adaptive log integrals gives about $2.5\times10^{-7}$, $5.6\times10^{-9}$ and $1.4\times10^{-8}$. The last column uses another scale. It divides the absolute error estimated by integrate() by its returned integral on the probability scale. The ratio itself is not logged. Those ratios are 0.0079, 0.0020 and 0.0037. The small observed log differences show close agreement for these response patterns. Neither calculation supplies the true integration error.
For all 80 clusters, the five rows of node_table allow a comparison of the parameter estimates and the common criterion computed by common_scalar(). The following differences supply the two panels of Figure 9.1.
1
2
3
4
5
6
7
node_grid <- node_table$nodes
stopifnot(identical(as.integer(node_grid), c(1L, 3L, 7L, 15L, 31L)))
# Subtract each parameter's 31-node estimate from its five estimates.
estimate_changes <- sweep(as.matrix(node_table[c("intercept", "slope", "SD")]), 2,
as.numeric(node_table[5, c("intercept", "slope", "SD")]), "-")
# Compare all five fits using the same likelihood evaluation.
difference_in_negative_loglik <- node_table$common61_nll - min(node_table$common61_nll)
Figure 9.1. Both panels use a logarithmic horizontal scale for the number of adaptive nodes per cluster. In the left panel, circles mark the fixed intercept, triangles the fixed slope and squares the random-intercept SD. In the right panel, circles show differences in the 61-node criterion and the dotted line marks the plotting floor.
The left axis, “Estimate minus 31-node estimate”, shows that the SD is about 0.028 lower at one node and 0.017 lower at three. Both fixed coefficients are within 0.003 of their 31-node values throughout. On the axis labeled “Negative log likelihood minus lowest of five fits”, the one- and three-node fits lie about 0.015 and 0.004 above the lowest common value. The seven-node fit attains that minimum. A logarithmic axis cannot display zero, so pmax(difference_in_negative_loglik, 1e-12) draws zero and any positive difference below $10^{-12}$ at the floor. At 15 and 31 points the differences are about $10^{-6}$. The figure compares five returned parameter vectors. Their ordering alone cannot attribute a difference to a particular optimizer stop.
Estimation error across independently generated datasets
To study bias, the generating SD must be known and the data must vary. The repeated-sample study gives each of 80 independent clusters a normal random intercept. Within a cluster, the covariate takes equally spaced values from $-1$ to $1$. The conditional logit has fixed intercept $-0.4$ and slope $0.8$. Crossing cluster sizes of 3 and 12 with intercept SDs of 0.3 and 1.0 gives four scenarios. Each has 200 replications, with a separate L’Ecuyer-CMRG random number stream for each of the 800 samples, starting from seed 100907. All three methods receive the same responses within a replication.
The Laplace option calls glmm_laplace_fit(), which approximates each cluster integral with the equivalent of one adaptive point. Adaptive quadrature (AGQ) uses 15 points, and penalized quasi-likelihood (PQL) repeatedly fits a weighted Gaussian mixed model. Replication is therefore over whole datasets of 80 clusters. Three fits to one dataset supply one comparison of methods.
The saved objects give both the summaries and the individual fits that determine their denominators. Each method contributes an SD to its own summary when its returned convergence flag is true; the column success counts these retained fits. For the paired summary, the method and AGQ must both have converged on the same sample. The two selections can therefore have different denominators even though every method started with the same 200 samples.
The resulting bias and root mean squared error (RMSE) describe the returned estimates among the retained fits. They combine statistical estimation error, approximation and stopping behavior, and selection by the convergence flag; they do not isolate the bias due to an integral approximation.
For a method with $m$ converged fits, let $e_r$ be the fitted SD minus the generating SD in sample $r$. The estimated bias is their mean. Its Monte Carlo standard error (MCSE) is their sample SD divided by $\sqrt m$. The estimated RMSE is the square root of the mean of $e_r^2$. Its reported MCSE uses the delta method, dividing the MCSE of that mean square by twice the RMSE.
1
2
3
study <- readRDS("data/derived/ch09/study.rds")
study_summary <- readRDS("data/derived/ch09/study-summary.rds")
print(subset(study_summary$summary, parameter == "SD"), row.names = FALSE, digits = 4)
1
2
3
4
5
6
7
8
9
10
11
12
13
scenario size true_sd method parameter success failed boundary bias bias_MCSE RMSE RMSE_MCSE
1 3 0.3 Laplace SD 200 0 0 -0.007230 0.018317 0.2585 0.010739
1 3 0.3 AGQ SD 150 50 0 0.200281 0.018613 0.3029 0.018352
1 3 0.3 PQL SD 199 1 0 0.066241 0.021326 0.3073 0.013123
2 12 0.3 Laplace SD 200 0 0 -0.041399 0.009253 0.1369 0.006553
2 12 0.3 AGQ SD 200 0 0 -0.015560 0.007859 0.1120 0.004692
2 12 0.3 PQL SD 197 3 0 -0.035267 0.009203 0.1336 0.006269
3 3 1.0 Laplace SD 200 0 0 -0.129657 0.021162 0.3255 0.014409
3 3 1.0 AGQ SD 200 0 0 0.005473 0.022582 0.3186 0.014747
3 3 1.0 PQL SD 199 1 0 -0.039661 0.020353 0.2891 0.014334
4 12 1.0 Laplace SD 200 0 0 -0.018773 0.009627 0.1371 0.008084
4 12 1.0 AGQ SD 200 0 0 -0.002101 0.009716 0.1371 0.007929
4 12 1.0 PQL SD 200 0 0 -0.058299 0.008744 0.1364 0.008047
Every Laplace fit met its optimizer’s stopping rule. With size 3 and SD 0.3, AGQ reached its iteration limit 50 times. It converged in all 200 samples of each other scenario. PQL failed to converge in 1, 3, 1 and 0 samples, respectively. The recorded boundary count is zero throughout. The study marks a boundary when the returned random-intercept covariance has one entry and that variance is finite and exactly zero. A small positive variance does not meet this condition.
With size 3 and true SD 1.0, estimated biases are $-0.129657$ for Laplace and 0.005473 for AGQ, both over 200 samples, with MCSEs 0.021162 and 0.022582. PQL gives $-0.039661$ with MCSE 0.020353 over 199 samples.
To obtain the number of comparisons available within samples, the paired table uses the intersection of the two sets of converged fits. For paired samples, let $d_r$ be the method’s SD estimate minus the AGQ estimate and let $m_p$ count samples where both converged. The paired table reports
\[\bar d=\frac{1}{m_p}\sum_r d_r,\qquad \operatorname{MCSE}(\bar d)=\frac{\operatorname{sd}(d_r)}{\sqrt{m_p}}.\]1
print(subset(study_summary$paired, parameter == "SD"), row.names = FALSE, digits = 4)
1
2
3
4
5
6
7
8
9
scenario method parameter paired difference MCSE
1 Laplace SD 150 -0.11655 0.0024440
1 PQL SD 149 -0.02345 0.0050660
2 Laplace SD 200 -0.02584 0.0018966
2 PQL SD 197 -0.01854 0.0017748
3 Laplace SD 200 -0.13513 0.0016104
3 PQL SD 199 -0.04621 0.0035762
4 Laplace SD 200 -0.01667 0.0001013
4 PQL SD 200 -0.05620 0.0009993
For example, the first scenario contributes 150 Laplace comparisons but only 149 PQL comparisons with AGQ. For size 3 and true SD 1.0, Laplace minus AGQ within the shared samples averages $-0.13513$ with MCSE 0.0016104, and PQL minus AGQ averages $-0.04621$ with MCSE 0.0035762.
Positive covariance between estimates on the same data can reduce the variance of their difference. Increasing size to 12 at true SD 1.0 gives biases of $-0.018773$, $-0.002101$ and $-0.058299$ in method order, all over 200 samples, with MCSEs 0.009627, 0.009716 and 0.008744. The paired differences are $-0.01667$ and $-0.05620$.
At size 3 and true SD 0.3, the AGQ bias of 0.200281 has MCSE 0.018613 on its 150 converged fits. Subtracting it from the Laplace bias of $-0.007230$ with MCSE 0.018317 over 200 samples mixes two sets of responses. PQL has estimated bias 0.066241 with MCSE 0.021326 over 199 samples. Restricting Laplace to the 150 shared samples gives a difference of $-0.11655$. For PQL the 149 shared samples give $-0.02345$.
At size 12 and SD 0.3, the estimated biases are $-0.041399$, $-0.015560$ and $-0.035267$ with MCSEs 0.009253, 0.007859 and 0.009203, over 200, 200 and 197 samples. The RMSEs are 0.1369, 0.1120 and 0.1336 for Laplace, AGQ and PQL.
Stopping records and quadrature checks at the estimates
The saved Laplace and AGQ optimizer records include the reason for stopping, the convergence flag and the iteration count. Counting reasons directly from the records distinguishes a fit that stopped during EM from one that continued to BFGS.
1
2
3
4
5
6
7
glmm_records <- study$results
glmm_stops <- do.call(rbind, lapply(glmm_records, function(r) data.frame(
scenario = r$task$scenario, method = c("Laplace", "AGQ"),
reason = c(r$fits$Laplace$reason, r$fits$AGQ$reason))))
glmm_counts <- as.data.frame(table(scenario = glmm_stops$scenario,
method = glmm_stops$method, reason = glmm_stops$reason))
print(glmm_counts[glmm_counts$Freq > 0, ], row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
scenario method reason Freq
1 Laplace converged 200
2 Laplace converged 200
3 Laplace converged 200
4 Laplace converged 200
1 AGQ converged_during_BFGS 149
2 AGQ converged_during_BFGS 200
3 AGQ converged_during_BFGS 196
4 AGQ converged_during_BFGS 1
1 AGQ converged_during_EM 1
3 AGQ converged_during_EM 4
4 AGQ converged_during_EM 199
1 AGQ iteration_limit 50
For scenarios 1 through 4, the counts of AGQ stops during BFGS are 149, 200, 196 and 1. The corresponding EM counts are 1, 0, 4 and 199. All 50 iteration-limit stops are in the first scenario and are excluded from its AGQ bias calculation.
Each AGQ fit has a separate endpoint table. At positive variance it records each component of the log likelihood score vector at 31 and 61 fixed nodes, their difference in the order 61 minus 31, and the 61-node component divided by 80. At zero variance the fixed effects have directly calculable scores, the derivative with respect to the log SD is undefined and the table gives a separate right derivative with respect to variance. The endpoint tables show no exact zero variance here. A positive fitted variance can still be close to zero.
Across the 2,400 fits, the inner diagnostic fields are NULL, the attempt lists are empty and no warnings were recorded. These fields contain no record of inner convergence.
PQL records the change in its linear predictors, its fitted coefficients and its covariance after each working fit. Selecting the unsuccessful records makes it possible to check how far each fit proceeded.
1
2
3
4
failed_pql <- Filter(function(r) !r$fits$PQL$converged, glmm_records)
pql_reasons <- vapply(failed_pql, function(r) r$fits$PQL$reason, "")
pql_working_fits <- vapply(failed_pql, function(r) length(r$fits$PQL$working_history),
integer(1))
All five PQL records give the iteration limit as the reason and ten as the number of working fits. For AGQ, the stored results describe the returned estimates and stops. They do not give each cluster’s log probability at every intermediate parameter vector.
How much could further quadrature refinement change the calculation at the converged AGQ estimates?
1
print(readRDS("data/derived/ch09/study-accuracy.rds")$summary)
1
2
3
4
maximum15_31_gap maximum31_61_gap unconverged missing15_31
3.173751e-06 5.792913e-10 5.000000e+01 5.000000e+01
missing31_61 largest_gap_job refitted_parameter_change
5.000000e+01 4.680000e+02 6.573130e-03
The refinement check skipped the 50 AGQ fits that reached the iteration limit. Each of the other 750 supplied two finite differences in negative log likelihood at its own fixed parameter vector. The maximum absolute differences were $3.17\times10^{-6}$ between 15 and 31 points and $5.79\times10^{-10}$ between 31 and 61. Job 468 had the largest first difference. Only that sample was fitted again with 31 points, starting from its 15-point estimates. The largest absolute change among its two fixed coefficients and its random-intercept SD was 0.00657313. This last number measures a change in estimates when the parameters are free to move. The refit also performs additional optimization from a different starting point. Its parameter change cannot be assigned entirely to finer quadrature, and the criterion differences at fixed estimates do not bound errors throughout an optimization.
For the single simulated binary dataset, seven nodes already give the SD within 0.00001 of the 31-node estimate. That agreement addresses numerical sensitivity on one dataset. The repeated-sample bias addresses how far the estimates returned by the fitting procedure lie from the generating SD on average, with Monte Carlo uncertainty from the finite number of samples it fitted. Paired differences remove variation due to giving the methods different datasets. They still reflect the approximation each method uses and the parameter values where its fitting procedure stops. The method with the smallest observed absolute bias can change with cluster size, generating SD and the set of samples on which it converges.
9.8 Comparing estimates and likelihoods with existing GLMM fits
Do two programs assign the same probability to the observed responses when they fit the same model? For the binary random-intercept data, both programs use the same 80 clusters, a logit link function, a fixed intercept and slope, and one normal intercept with mean zero per cluster.
In lme4, the nAGQ argument of glmer() gives the number of adaptive Gauss-Hermite points per axis. One point gives the Laplace approximation. Seven points match the number of points per axis used to obtain adaptive_fit; this does not make the node placement and optimization procedures identical. The default glmerControl() uses BOBYQA for the preliminary optimization over covariance parameters and Nelder-Mead for the joint optimization. Thus glmer() supplies another implementation with its own optimizer. The corresponding Laplace and adaptive fitting methods developed here are available in glmmTMB and GLMMadaptive, respectively.
The third reference fit allows the slope as well as the intercept to vary by cluster. For this two-dimensional model, both fits use Laplace because glmer() supports more than one adaptive point only for a single scalar random effect.
1
2
3
4
5
6
7
8
control_glmer <- lme4::glmerControl()
reference_fits <- list(
Laplace = lme4::glmer(y ~ x + (1 | id), binary_input$observed, family = binomial(),
nAGQ = 1, control = control_glmer),
AGQ = lme4::glmer(y ~ x + (1 | id), binary_input$observed, family = binomial(),
nAGQ = 7, control = control_glmer),
slope = lme4::glmer(y ~ x + (1 + x | id), slope_input$observed, family = binomial(),
nAGQ = 1, control = control_glmer))
Each comparison uses two measures of parameter agreement. The first is the largest absolute difference over the fixed coefficients. The second applies the same calculation to the entries of the random-effect covariance matrix. For one random intercept, this compares variances on their original scale. To compare likelihoods, glmm_integrate() takes the reference coefficients and a lower Cholesky factor of the reference covariance matrix. The last column subtracts the negative marginal log likelihood at the reference estimates from the corresponding value at this book’s estimates, using one integration rule for both.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
reference_rows <- list()
for (method in names(reference_fits)) {
ref <- reference_fits[[method]]
own <- switch(method, Laplace = laplace_fit, AGQ = adaptive_fit, slope = slope_laplace)
data <- if (method == "slope") slope else binary
G <- as.matrix(lme4::VarCorr(ref)$id)
b <- unname(lme4::fixef(ref))
# Use the same integration rule at both fitted parameter vectors.
common_ref <- glmm_integrate(data, b, t(chol(G)), "AGQ",
if (method == "slope") 15 else 61)$value
common_own <- if (method == "slope") slope_common(own) else common_scalar(own)
reference_rows[[method]] <- data.frame(method = method, beta_gap = max(abs(own$beta-b)),
G_gap = max(abs(own$G-G)), common_rule_difference_in_negative_loglik =
common_own-common_ref)
}
reference_table <- do.call(rbind, reference_rows)
print(reference_table, row.names = FALSE)
1
2
3
4
method beta_gap G_gap common_rule_difference_in_negative_loglik
Laplace 0.0001015182 2.807074e-05 -4.509745e-05
AGQ 0.0006052491 4.679544e-03 3.841678e-04
slope 0.0004572389 5.600721e-04 -6.878604e-04
For the two scalar Laplace fits, the fixed-coefficient gap is about $1.0\times10^{-4}$ and the variance gap about $2.8\times10^{-5}$. Under the common 61-point rule, the signed difference is $-4.5\times10^{-5}$, so the book’s estimates give the smaller negative log likelihood. For the fits obtained with seven adaptive points, the coefficient and variance gaps are about $6.1\times10^{-4}$ and $4.7\times10^{-3}$. The positive 61-point difference of $3.8\times10^{-4}$ favors the glmer() estimates. The book’s adaptive fit fixes its nodes between placements. Evaluating the two returned vectors gives their values under the common criterion. It does not establish which update or stopping decision produced the difference.
In the random-slope model, (1 + x | id) allows a covariance between the intercept and slope. In the slope row, the maximum fixed-coefficient difference is about $4.6\times10^{-4}$. The maximum over the two variances and their covariance is about $5.6\times10^{-4}$. The book’s evaluator can use 15 adaptive points on each of the two axes at either set of estimates. On that grid, the negative log likelihood at the book’s estimates is about $6.9\times10^{-4}$ lower, giving the negative sign in the table.
Comparing the PQL working fits
For penalized quasi-likelihood, the settings to match are those of the weighted Gaussian working fits. The MASS function glmmPQL() fits a random intercept to the binary and count responses. The call to nlme::lmeControl() selects opt = "optim", which uses BFGS for the working models. The book option with the same name calls its own bfgs() implementation, so the algorithms are related but the functions called are different. The book’s PQL starts from irls(), adapted from glm.fit(), and follows the start, the stopping rule and the ten rounds of glmmPQL() (code/NOTICE.md), so this comparison checks a translation (Section E.3).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pql_references <- lapply(c("binomial","poisson"), function(family) {
observed <- if (family == "binomial") binary_input$observed else count_input$observed
MASS::glmmPQL(y ~ x, random = ~ 1 | id, family = family, data = observed,
verbose = FALSE, control = nlme::lmeControl(opt = "optim"))
})
pql_reference_table <- do.call(rbind, lapply(1:2, function(j) {
own <- if (j == 1L) pql_binary else pql_count
ref <- pql_references[[j]]
data.frame(family = c("binomial","poisson")[j],
beta_gap = max(abs(own$beta - nlme::fixef(ref))),
G_gap = abs(own$G[1] - as.numeric(nlme::getVarCov(ref))[1]),
residual_variance = sigma(ref)^2,
working_method = ref$method, reference_logLik = as.numeric(logLik(ref)))
}))
print(pql_reference_table, row.names = FALSE)
1
2
3
family beta_gap G_gap residual_variance working_method reference_logLik
binomial 1.652012e-13 2.017053e-12 0.9394668 ML NA
poisson 7.939277e-11 7.760844e-10 0.9645515 ML NA
For the binary data, the maximum fixed-coefficient gap and the absolute variance gap are approximately $1.7\times10^{-13}$ and $2.0\times10^{-12}$. For the counts, they are approximately $7.9\times10^{-11}$ and $7.8\times10^{-10}$. The last three columns describe each reference fit. Squaring its residual standard deviation gives 0.9394668 or 0.9645515 for the final Gaussian working model. Both working fits used ML. The NA returned by logLik() leaves no reference marginal log likelihood to subtract for PQL.
A matched case-control example
The comparisons so far used simulated clusters. The observed infert data distributed with R record infertility cases, coded 1, and controls, coded 0, in matched sets identified by stratum. The R dataset documentation describes the study. The fixed design includes age in years, parity, education and prior spontaneous and induced abortions. Both abortion variables enter numerically as 0, 1 or 2, where 2 means two or more. Education uses 0–5 years as the reference. With the other covariates and the set’s random intercept fixed, the age coefficient is the log-odds difference per year and the parity coefficient the log-odds difference per unit of parity. Each abortion coefficient imposes the same log-odds increment from code 0 to 1 as from 1 to 2 or more. Each education coefficient compares its category with the reference category. Exponentiating these coefficients gives the corresponding conditional odds ratios.
The fixed intercept is the model log odds when age, parity and both abortion codes are zero, education is at its reference level, and the random intercept is zero. A shared mean-zero normal intercept shifts the logits of all members of a set; its variance describes remaining between-set variation on the log-odds scale. The GLMM assumes independent sets and conditionally independent Bernoulli responses within a set. Both programs fit it with 15 adaptive points. Here the GLMM is a computational comparison; its fitted case probabilities should not be interpreted as population infertility risks under this sampling design.
1
2
3
4
5
6
7
8
9
10
11
12
infert_observed <- datasets::infert
infert_contrasts <- list(education = contr.treatment(levels(infert_observed$education),
base = 1))
infert_X <- model.matrix(~ age + parity + education + spontaneous + induced,
infert_observed, contrasts.arg = infert_contrasts)
infert_data <- glmm_data(infert_observed$case, infert_X, matrix(1,nrow(infert_X),1),
infert_observed$stratum)
infert_fit <- glmm_fit(infert_data, "AGQ", 15)
infert_reference <- lme4::glmer(case ~ age + parity + education + spontaneous + induced +
(1 | stratum),
data = infert_observed, family = binomial(), contrasts = infert_contrasts, nAGQ = 15,
control = control_glmer)
1
boundary (singular) fit: see help('isSingular')
The singular-fit message comes from glmer(). For the book’s second fit, the starting coefficients come from the first fit and the starting intercept standard deviation is 1.5.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Start at the first fixed effects and a random-intercept SD of 1.5.
infert_other_start <- glmm_fit(infert_data, "AGQ", 15, start = c(infert_fit$beta,
log(1.5)))
# Evaluate the reference parameters with 61 points.
infert_reference_nll <- glmm_integrate(infert_data, unname(lme4::fixef(infert_reference)),
matrix(sqrt(as.numeric(lme4::VarCorr(infert_reference)$stratum))), "AGQ", 61)$value
print(c(rows = infert_data$N, strata = infert_data$groups,
cases_per_set_min = min(tapply(infert_observed$case, infert_observed$stratum, sum)),
cases_per_set_max = max(tapply(infert_observed$case, infert_observed$stratum, sum)),
set_size_min = min(table(infert_observed$stratum)),
set_size_max = max(table(infert_observed$stratum)),
random_intercept_variance = infert_fit$G[1],
negative_marginal_loglik_AGQ15 = infert_fit$value,
reference_beta_gap = max(abs(infert_fit$beta - lme4::fixef(infert_reference))),
book15_minus_reference61_negative_loglik = infert_fit$value - infert_reference_nll,
second_start_nll_gap = infert_other_start$value - infert_fit$value))
1
2
3
4
5
6
7
8
9
10
11
12
rows strata
248.00000000 83.00000000
cases_per_set_min cases_per_set_max
1.00000000 1.00000000
set_size_min set_size_max
2.00000000 3.00000000
random_intercept_variance negative_marginal_loglik_AGQ15
0.01704248 129.18231980
reference_beta_gap book15_minus_reference61_negative_loglik
0.02200578 0.28347470
second_start_nll_gap
-0.10313763
The 248 observations form 83 sets with one case per set by design. Since each set has two or three members, 248 observations imply 82 triples and one pair. In the default book fit the intercept variance is 0.01704 and the 15-point negative marginal log likelihood is 129.18232. The maximum fixed-coefficient difference from glmer() is about 0.022. The reported 0.28347 subtracts the reference value evaluated with 61 points from the book’s returned 15-point value. This mixed-rule difference does not isolate the effect of changing estimates. The second-start comparison does use 15 points for both values. Subtracting the default value from the alternate value gives $-0.10314$.
The next diagnostic compares the log likelihood scores at the two returned parameter vectors. Coordinates one through seven follow the columns of infert_X; coordinate eight is the log standard deviation of the random intercept. As in Section 9.6, the last columns compare the 31- and 61-point scores and report the latter per matched set.
1
2
3
infert_endpoints <- rbind(glmm_endpoint(infert_data,infert_fit,"default","AGQ15"),
glmm_endpoint(infert_data,infert_other_start,"alternate","AGQ15"))
print(infert_endpoints)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
id method coordinate estimate groups converged reason boundary
(Intercept) default AGQ15 1 -1.16755332 83 TRUE converged_during_BFGS FALSE
age default AGQ15 2 0.04053135 83 TRUE converged_during_BFGS FALSE
parity default AGQ15 3 -0.83596380 83 TRUE converged_during_BFGS FALSE
education6-11yrs default AGQ15 4 -1.06191737 83 TRUE converged_during_BFGS FALSE
education12+ yrs default AGQ15 5 -1.42521087 83 TRUE converged_during_BFGS FALSE
spontaneous default AGQ15 6 2.06351590 83 TRUE converged_during_BFGS FALSE
induced default AGQ15 7 1.30358985 83 TRUE converged_during_BFGS FALSE
default AGQ15 8 -2.03602315 83 TRUE converged_during_BFGS FALSE
(Intercept)1 alternate AGQ15 1 -1.13822698 83 TRUE converged_during_BFGS FALSE
age1 alternate AGQ15 2 0.03971530 83 TRUE converged_during_BFGS FALSE
parity1 alternate AGQ15 3 -0.82970438 83 TRUE converged_during_BFGS FALSE
education6-11yrs1 alternate AGQ15 4 -1.06416795 83 TRUE converged_during_BFGS FALSE
education12+ yrs1 alternate AGQ15 5 -1.41981925 83 TRUE converged_during_BFGS FALSE
spontaneous1 alternate AGQ15 6 2.05184927 83 TRUE converged_during_BFGS FALSE
induced1 alternate AGQ15 7 1.28917191 83 TRUE converged_during_BFGS FALSE
1 alternate AGQ15 8 -2.26326460 83 TRUE converged_during_BFGS FALSE
right_loglik_derivative_at_zero_variance em bfgs_iterations
(Intercept) NA 30 10+20+30+1
age NA 30 10+20+30+1
parity NA 30 10+20+30+1
education6-11yrs NA 30 10+20+30+1
education12+ yrs NA 30 10+20+30+1
spontaneous NA 30 10+20+30+1
induced NA 30 10+20+30+1
NA 30 10+20+30+1
(Intercept)1 NA 30 10+20+30+40+50+18
age1 NA 30 10+20+30+40+50+18
parity1 NA 30 10+20+30+40+50+18
education6-11yrs1 NA 30 10+20+30+40+50+18
education12+ yrs1 NA 30 10+20+30+40+50+18
spontaneous1 NA 30 10+20+30+40+50+18
induced1 NA 30 10+20+30+40+50+18
1 NA 30 10+20+30+40+50+18
bfgs_stops
(Intercept) iteration_limit+iteration_limit+iteration_limit+converged
age iteration_limit+iteration_limit+iteration_limit+converged
parity iteration_limit+iteration_limit+iteration_limit+converged
education6-11yrs iteration_limit+iteration_limit+iteration_limit+converged
education12+ yrs iteration_limit+iteration_limit+iteration_limit+converged
spontaneous iteration_limit+iteration_limit+iteration_limit+converged
induced iteration_limit+iteration_limit+iteration_limit+converged
iteration_limit+iteration_limit+iteration_limit+converged
(Intercept)1 iteration_limit+iteration_limit+iteration_limit+iteration_limit+iteration_limit+converged
age1 iteration_limit+iteration_limit+iteration_limit+iteration_limit+iteration_limit+converged
parity1 iteration_limit+iteration_limit+iteration_limit+iteration_limit+iteration_limit+converged
education6-11yrs1 iteration_limit+iteration_limit+iteration_limit+iteration_limit+iteration_limit+converged
education12+ yrs1 iteration_limit+iteration_limit+iteration_limit+iteration_limit+iteration_limit+converged
spontaneous1 iteration_limit+iteration_limit+iteration_limit+iteration_limit+iteration_limit+converged
induced1 iteration_limit+iteration_limit+iteration_limit+iteration_limit+iteration_limit+converged
1 iteration_limit+iteration_limit+iteration_limit+iteration_limit+iteration_limit+converged
reported_score_component quadrature_rule score_component_31_nodes score_component_61_nodes
(Intercept) 0.028725828 GHQ 0.028725828 0.028725828
age 0.126133985 GHQ 0.126133985 0.126133985
parity 0.008045260 GHQ 0.008045260 0.008045260
education6-11yrs -0.004737652 GHQ -0.004737652 -0.004737652
education12+ yrs 0.052456100 GHQ 0.052456100 0.052456100
spontaneous 0.022046916 GHQ 0.022046916 0.022046916
induced -0.058257110 GHQ -0.058257110 -0.058257110
-0.560767088 GHQ -0.560767088 -0.560767088
(Intercept)1 0.004334297 GHQ 0.004334297 0.004334297
age1 0.088090450 GHQ 0.088090450 0.088090450
parity1 -0.015033507 GHQ -0.015033507 -0.015033507
education6-11yrs1 0.056044700 GHQ 0.056044700 0.056044700
education12+ yrs1 -0.024714252 GHQ -0.024714252 -0.024714252
spontaneous1 -0.016661980 GHQ -0.016661980 -0.016661980
induced1 0.060856016 GHQ 0.060856016 0.060856016
1 -0.358679371 GHQ -0.358679371 -0.358679371
difference_61_minus_31 score_component_61_nodes_per_group diagnostic
(Intercept) 4.565792e-15 3.460943e-04
age 1.626754e-13 1.519687e-03
parity 8.843620e-15 9.693084e-05
education6-11yrs 2.212640e-15 -5.708015e-05
education12+ yrs 2.380041e-15 6.320012e-04
spontaneous 5.061923e-15 2.656255e-04
induced 1.748601e-15 -7.018929e-04
3.330669e-16 -6.756230e-03
(Intercept)1 3.597816e-15 5.222045e-05
age1 9.106604e-14 1.061331e-03
parity1 8.366571e-15 -1.811266e-04
education6-11yrs1 1.630640e-15 6.752374e-04
education12+ yrs1 1.585537e-15 -2.977621e-04
spontaneous1 5.422746e-15 -2.007467e-04
induced1 6.036838e-16 7.332050e-04
1 1.665335e-16 -4.321438e-03
Both book runs reported convergence during BFGS at positive variances. Each 61-point score component sums over the 83 matched sets. Dividing by 83 gives the mean contribution per set. At both endpoints the largest component in absolute value is the derivative with respect to log standard deviation. Its magnitude is 0.006756 at the default estimates and 0.004321 at the alternate estimates. These are derivatives at the returned coordinates. The different starting values led to different endpoints, and the records give no cause for that difference.
The sampling design raises a separate question: what likelihood conditions on the one case fixed by design in each set? To condition on the matched design, let $Y_{ij}$ indicate case status for member $j$ of set $i$, and let $X_i$ have covariate rows $x_{ij}^{\top}$. If member $c$ is the sole case, the product of Bernoulli probabilities has numerator $\exp(b_i+x_{ic}^{\top}\beta)$ and the same denominator for every possible $c$. Dividing by the sum of those pattern probabilities cancels both the denominator and the factor $\exp(b_i)$ from the shared intercept. The conditional probability is
\[\Pr\!\left(c\text{ is the case}\mid\sum_j Y_{ij}=1,X_i\right) =\frac{\exp(x_{ic}^{\top}\beta)}{\sum_j\exp(x_{ij}^{\top}\beta)}.\]For two members $c$ and $k$, the ratio of their probabilities of being the sole case is $\exp\lbrace (x_{ic}-x_{ik})^\top\beta\rbrace $. A one-unit covariate difference contributes its coefficient to the log of this ratio, with other covariates equal. Conditioning on one case removes the shared intercept and its variance from the likelihood. The GLMM instead integrates the probability of the whole pattern, including its design-imposed total. Its zero-variance logistic reduction still includes that total. The likelihood conditional on the case count is the basis of conditional logistic regression. Any covariate constant within a matched set also cancels, so its separate coefficient cannot be estimated from this conditional likelihood. This conditioning on a case count differs from the GLMM response distribution conditional on a specified random intercept.
Recovering cluster log probabilities
Return to the simulated binary random-intercept data with 80 clusters. In the adaptive fit, adaptive_fit$loglik_contributions contains 80 log marginal probabilities. Negating their sum recovers the criterion for its observed response vectors. The beta and G fields identify the parameters used, and optimizer$reason records how the fit stopped. The function glmm_laplace_fit() returns the negative log likelihood for all clusters in value. Its binary cluster log probabilities can be recovered by evaluating the Laplace formula separately at the fitted parameters. The returned modes were recomputed at those same coefficients and covariance.
1
2
laplace_log_probabilities <- glmm_integrate(binary, laplace_fit$beta,
t(chol(laplace_fit$G)), method = "Laplace")$loglik_contributions
For PQL, successive entries of pql_binary$history give the changes in the linear predictors used in its stopping test. A likelihood comparison needs the probability of the same observed response vector under the same conditioning and integration rule. With those choices fixed, subtracting the two negative log likelihoods shows which fitted parameters assign higher probability to the observed data and by how much on the log scale.
