Post

Generalized latent variable models for mixed responses

A person’s record may combine a continuous measurement with a rating or a count. A researcher may be interested in whether these observations reflect a common factor, although the observations are recorded on different scales. A one-unit difference has a different meaning in each response, and the possible values differ as well. A generalized latent variable model for mixed responses allows the relationship with common factors to be studied while respecting how each response is recorded. The chapter uses the simulated two-factor sample MIXED6 to compare two ways of handling the integral over the factors: approximating it at each person’s conditional mode, and replacing it by a variational lower bound.

11.1 A factor model for continuous, binary, ordinal, and count responses

Here, mixed responses means responses of different measurement types recorded for the same observational unit; the model relates them through common latent factors. It does not mean a mixture of latent classes.

Each row of the simulated MIXED6 data represents one independently sampled person. Write $Y_{ij}$ for response $j$ of person $i$ and $y_{ij}$ for its observed value. Two common factors describe variation among people. For person $i$ they form a random column vector $z_i=(z_{i1},z_{i2})^\top$ with a bivariate normal distribution $N_2(0,I_2)$, where $I_2$ is the two-dimensional identity matrix. Each factor has mean zero and variance one, and the factors are independent. One factor unit is therefore one population standard deviation. For response $j$, let $\alpha_j$ be its intercept and let $\lambda_j$ contain its two factor loadings. Its linear predictor is

\[\eta_{ij}=\alpha_j+\lambda_j^\top z_i =\alpha_j+\lambda_{j1}z_{i1}+\lambda_{j2}z_{i2}.\]

The second measurement, for example, has linear predictor $0.5+0.2z_{i1}+0.8z_{i2}$. Among people with the same first factor, a one-unit increase in the second factor corresponds to a difference of $0.8$ in this linear predictor. The other five linear predictors use the same pair of factor values with their own loadings.

For the two measurements, each linear predictor is on the scale of the recorded value. Their conditional distributions are normal, with means $\eta_{i1}$ and $\eta_{i2}$ and residual standard deviations of one in their respective measurement units. For either measurement, $\alpha_j$ is its mean when both factors are zero, and $\lambda_{jh}$ is the change in that mean per unit of factor $h$, with the other factor fixed. The remaining deviation $Y_{ij}-\eta_{ij}$ has mean zero given the factors. Its variance is the residual variance, measured in squared measurement units; it describes response variation among people with the same factor values.

The third column is a Bernoulli response. Its linear predictor is the log odds of a success, so the conditional probability of a one is $F(\eta_{i3})$, where $F(t)=1/(1+\exp(-t))$ is the inverse logit function. Here $\alpha_3$ is the log odds at zero on both factors, giving probability $F(\alpha_3)$. Increasing factor $h$ by one unit with the other fixed adds $\lambda_{3h}$ to the log odds and multiplies the odds by $\exp(\lambda_{3h})$. The corresponding probability change depends on the starting factor values.

The fourth column is a rating scored 0, 1 or 2. A cumulative logit model specifies the log odds of scoring at or below each of the first two category scores. The same loading vector enters both logits, giving the proportional odds model. The scores 0, 1 and 2 indicate order; they do not impose equal distances between rating categories. With cutpoints $c_1=-0.7$ and $c_2=0.7$, those probabilities are

\[\Pr(Y_{i4}\le k\mid z_i)=F(c_{k+1}-\eta_{i4}),\qquad k=0,1.\]

Increasing the linear predictor lowers both cumulative probabilities and shifts probability toward higher ratings. At zero on both factors, the cumulative log odds at boundary $k$ are $c_{k+1}-\alpha_4$. A cutpoint is the value of the linear predictor at which its cumulative probability equals one half; with two factors, it does not specify a unique factor vector. A one-unit increase in factor $h$, with the other fixed, subtracts $\lambda_{4h}$ from both cumulative log odds. Thus a positive loading favors higher ratings. Raising one cutpoint with the linear predictor fixed and the cutpoints still ordered increases the probability at or below its boundary.

The rating probabilities depend on each cutpoint only through its difference from the linear predictor. Adding a constant to the ordinal intercept and to both cuts would give the same probabilities for every person. Fixing $\alpha_4=0$ sets the origin against which both cutpoints can be estimated.

The last two columns are counts taking values $0,1,2,\ldots$. Both have conditional mean $\mu_{ij}=\exp(\eta_{ij})$. The fifth is Poisson, so its conditional variance equals its mean. Its intercept $\alpha_5$ is the log expected count when both factors are zero. At fixed value of the other factor, increasing factor $h$ by one unit multiplies this mean by $\exp(\lambda_{5h})$.

The sixth is negative binomial with positive size $r$ and conditional variance $\mu_{i6}+\mu_{i6}^2/r$. Here $\alpha_6$ is the log expected count at zero on both factors, and a one-unit increase in factor $h$ multiplies the mean by $\exp(\lambda_{6h})$ with the other factor fixed. Size controls a different part of this response distribution. At a given mean, the second term allows additional count variation even among people with identical factors. The model sets $r=4$. The R function dnbinom() evaluates the probability of the observed count with mu equal to its conditional mean and size equal to four. The abbreviation NB in the code denotes negative binomial. The size $r$ need not be an integer; larger $r$ means less extra conditional variance at a fixed mean. This parameter must be distinguished from its reciprocal, which is used later as the dispersion parameter.

The loadings require a separate choice. With the loadings $\lambda_j^\top$ as the rows of a matrix $\Lambda$, any orthogonal matrix $Q$ gives $(\Lambda Q)(Q^\top z_i)=\Lambda z_i$, and the rotated factors have the same standard normal distribution. Restrictions on the first two loading rows fix the orientation. For the first measurement, the second loading is fixed at zero and the first must be positive. Its loading vector $(0.8,0)$ thus points along the positive first axis. The second measurement has loadings $(0.2,0.8)$. Requiring its second loading to be positive fixes the direction of the second axis. Together the two rows give a lower triangular leading block with positive diagonal entries. These restrictions remove the displayed shifts and rotations when the leading loading block has full rank. They do not by themselves prove that every response parameter is identified from the observed distribution.

Assume local independence: the responses within a row are independent conditional on that person’s factor vector and the model parameters. Write $f_j(y_{ij}\mid\eta_{ij})$ for the conditional density or probability evaluated at the observation in column $j$, with the other parameters of its family fixed. Conditional independence gives the conditional joint density or probability of the six responses as the product of these six values. Taking its logarithm gives the person’s conditional log likelihood,

\[\ell_i(z_i)=\log\!\left\{\prod_{j=1}^{6} f_j(y_{ij}\mid\eta_{ij})\right\} =\sum_{j=1}^{6}\log f_j(y_{ij}\mid\eta_{ij}).\]

For the rating, the probability of category 0 is the first cumulative probability. The middle category has lower and upper cutpoints $a=c_1$ and $b=c_2$. At linear predictor value $\eta$, subtracting the probability at the lower cut from the probability at the upper cut isolates that category. Putting the two logistic fractions over a common denominator gives

\[\begin{aligned} F(b-\eta)-F(a-\eta) &=\frac{e^{b-\eta}-e^{a-\eta}}{(1+e^{b-\eta})(1+e^{a-\eta})}\\ &=F(b-\eta)F(\eta-a)\{1-e^{a-b}\}. \end{aligned}\]

Taking logarithms turns the product of these three terms into a sum. If $p$ denotes the middle category probability at $\eta$, then

\[\log p=-\log(1+e^{\eta-b})-\log(1+e^{a-\eta})+\log(1-e^{a-b}).\]

Only the first two terms depend on the linear predictor. The last term can be evaluated with expm1(), which computes an exponential minus one accurately near zero. This form avoids subtracting nearly equal cumulative probabilities. Using $a=-\infty$ for the lowest category or $b=+\infty$ for the highest gives the corresponding single tail probability.

Conditional log terms for the first person

For a calculation with the first person’s observations, start R in the book directory. Load the numerical and response functions with source(). The constructor mixed6_model() supplies the model independently of the 400-by-6 observed matrix that readRDS() reads into Y2. The sample was simulated with seed 1101. The constructor stores one intercept and one loading row per response, with columns for the standard normal factors.

FieldQuantity in the conditional response model
family[j]Distribution of response $j$
intercept[j]$\alpha_j$ in the linear predictor
loading[j, ]$\lambda_j^\top$, the loading row
sd[j]Residual standard deviation for a normal response
cutsCutpoints for the ordinal response
size[j]Size parameter for a negative binomial response

The response family selects which additional parameters it uses. The standard normal factor distribution is specified by the model’s generator and integrand; it is not another field in this list.

1
2
3
4
5
6
7
8
9
10
11
12
13
source("code/lib/stability.R")
source("code/lib/glmm.R")
source("code/lib/mixed_factor.R")

mixed6_model <- function(q = 2L, families = c("normal","normal","Bernoulli","ordinal","Poisson","NB")) {
  stopifnot(q %in% 1:2, length(families) == 6L)
  L <- matrix(c(.8,0, .2,.8, .7,.2, .1,.7, .6,.3, .3,.6), 6, 2, byrow = TRUE)
  list(family = families, intercept = c(0,.5,-.3,0,.2,-.1), loading = L[,seq_len(q),drop=FALSE],
    sd = rep(1,6), cuts = c(-.7,.7), size = rep(4,6))
}

model2 <- mixed6_model()
Y2 <- readRDS("data/source/ch11/MIXED6.rds")

For one conditional response contribution, the imported function mixed_response() returns the log density or log probability in log_density, its derivative with respect to the linear predictor in score, and its negative second derivative in weight. For the Bernoulli and Poisson responses, it calls glmm_response() and uses the residual, the observation minus its conditional mean, as the derivative of the log probability with respect to the linear predictor. The field score is a derivative of a log likelihood contribution, not a rating score or a factor score. The field weight is the negative second derivative for this observation; for a negative binomial response it depends on the observed count and is not an expectation over that count. The function is in code/lib/mixed_factor.R.

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
mixed_response <- function(y, eta, model, j) {
  family <- model$family[j]
  e <- eta
  if (family == "normal") {
    variance <- model$sd[j]^2
    return(list(log_density = dnorm(y, e, sqrt(variance), log = TRUE),
      score = (y-e)/variance, weight = rep(1/variance,length(e))))
  }
  if (family %in% c("Bernoulli","Poisson")) {
    t <- glmm_response(y, e, if (family == "Poisson") "poisson" else "binomial")
    return(list(log_density = t$log_density, score = t$residual, weight = t$weight))
  }
  if (family == "NB") {
    r <- model$size[j]
    # For a count, log_density is the log probability mass. Its derivative with respect to the log mean is y - (y+r) mu/(mu+r).
    fraction <- plogis(e - log(r))
    return(list(log_density = dnbinom(y, size = r, mu = exp(e), log = TRUE),
      score = y - (y+r)*fraction, weight = (y+r)*fraction*plogis(log(r)-e)))
  }
  stopifnot(family == "ordinal", all(y %in% (0:length(model$cuts))))
  cuts <- model$cuts
  # Pad the two outer thresholds. Both have infinite width and log width factor zero.
  lower_threshold <- c(-Inf,cuts)[as.integer(y)+1L]
  upper_threshold <- c(cuts,Inf)[as.integer(y)+1L]
  lower <- e-lower_threshold
  upper <- e-upper_threshold
  width <- log(-expm1(lower_threshold-upper_threshold))
  # Factor the category probability before taking logs; the width is independent of eta.
  list(log_density = -log1pexp(-lower) - log1pexp(upper) + width,
    score = plogis(-lower) - plogis(upper),
    weight = plogis(lower)*plogis(-lower) + plogis(upper)*plogis(-upper))
}

For a normal response the three fields are the normal log density, $(y-\eta)/\sigma^2$ and $1/\sigma^2$. For a negative binomial response, fraction is $\mu/(\mu+r)$, so score is $y-(y+r)\mu/(\mu+r)$ and weight is $(y+r)\mu r/(\mu+r)^2$. For the ordinal response, category $k$ has probability $F(\eta-\tau_k)-F(\eta-\tau_{k+1})$ with $F$ the logistic distribution function, $\tau_0=-\infty$ and $\tau_K=\infty$; lower and upper are $\eta-\tau_k$ and $\eta-\tau_{k+1}$. The code writes this probability as $F(\eta-\tau_k)\lbrace 1-F(\eta-\tau_{k+1})\rbrace \lbrace 1-e^{\tau_k-\tau_{k+1}}\rbrace $, whose last factor, width, does not depend on $\eta$. Its derivatives give score $=1-F(\eta-\tau_k)-F(\eta-\tau_{k+1})$ and weight $=F(\eta-\tau_k)\lbrace 1-F(\eta-\tau_k)\rbrace +F(\eta-\tau_{k+1})\lbrace 1-F(\eta-\tau_{k+1})\rbrace $.

Row 1 of Y2 gives the six observations for this person. At $z_i=(0,0)^\top$, each linear predictor equals its intercept. In vapply(), the index j selects both a response in row 1 and its model parameters. Each call returns one log_density value for the numeric vector at_zero.

1
2
3
4
at_zero <- vapply(1:6,function(j) mixed_response(Y2[1,j],model2$intercept[j],
  model2,j)$log_density,0.0)
print(data.frame(person=1L,response=1:6,family=model2$family,observation=Y2[1,],
  linear_predictor_at_zero=model2$intercept,log_density_or_probability=at_zero))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  person response    family observation linear_predictor_at_zero
1      1        1    normal  -0.7721177                      0.0
2      1        2    normal   2.2797892                      0.5
3      1        3 Bernoulli   1.0000000                     -0.3
4      1        4   ordinal   0.0000000                      0.0
5      1        5   Poisson   0.0000000                      0.2
6      1        6        NB   0.0000000                     -0.1
  log_density_or_probability
1                 -1.2170214
2                 -2.5027634
3                 -0.8543552
4                 -1.1031860
5                 -1.2214028
6                 -0.8157103

In log_density_or_probability, the first two entries, $-1.21702$ and $-2.50276$, are log densities evaluated on the recorded measurement scales. With residual standard deviations of one, the second measurement is about $1.78$ standard deviations above its mean and the first is about $0.77$ below its mean. The larger distance accounts for the smaller second density. Each density has units reciprocal to those of its measurement. The success in column three contributes the log probability $\log F(-0.3)$. The last three zeros represent different events. The lowest rating has probability $F(-0.7)$. The Poisson zero has log probability $-\exp(0.2)$, and the negative binomial zero has log probability $4\log\lbrace 4/(4+\exp(-0.1))\rbrace $. Adding the six entries gives

1
print(c(person=1, sum_conditional_log_terms_at_zero=sum(at_zero)))
1
2
                           person sum_conditional_log_terms_at_zero 
                         1.000000                         -7.714439 

The value of sum_conditional_log_terms_at_zero is the conditional log likelihood $\ell_1((0,0)^\top)=-7.714439$. To obtain this person’s contribution to the marginal likelihood, the product of the six conditional densities and probabilities must be averaged over both factors together. Averaging each of them separately would allow a different pair of factor values for each response from the same person.

Two entries can be checked directly at the same linear predictor values. For the first measurement, dnorm() evaluates a normal density at the recorded value with mean zero and the first residual standard deviation in model2$sd. For the third response, plogis() converts the intercept to a success probability and dbinom() evaluates the probability of the observed outcome in one trial. The argument log=TRUE requests logarithms in both calls.

1
2
3
4
print(c(conditional_normal=at_zero[1],
  direct_normal=dnorm(Y2[1,1],0,model2$sd[1],log=TRUE),
  conditional_bernoulli=at_zero[3],
  direct_bernoulli=dbinom(Y2[1,3],1,plogis(-.3),log=TRUE)))
1
2
3
4
   conditional_normal         direct_normal conditional_bernoulli 
           -1.2170214            -1.2170214            -0.8543552 
     direct_bernoulli 
           -0.8543552 

The direct normal log density equals the first entry of at_zero at $-1.2170214$. The binomial calculation gives $-0.8543552$ for a success, the same value the mixed model adds to this person’s log likelihood for the third response. The gllvm package fits generalized latent variable models for mixed responses.

11.2 Poisson and negative binomial models for multivariate abundance data

Abundance data record the number of individuals of each species at a survey site. Here two simulated matrices each contain 400 independently sampled sites and six species. The counts in a row share two unobserved site factors and are conditionally Poisson in one matrix and negative binomial in the other. This separates association between species from variation within a species at fixed factors. The same structure can describe several event counts per person when observation periods are comparable and the counts are independent given the common factors. If the expected count is proportional to an observed time at risk $t_{ij}>0$, different observation periods can be represented by the known offset $\log t_{ij}$ in the log mean. The present examples use comparable observation periods and contain no such offset.

For species $j$ at site $i$, the conditional mean is $\mu_{ij}=\exp(\alpha_j+\lambda_j^\top z_i)$. In the Poisson model, $\alpha_j$ is the log expected abundance at zero on both site factors, and a unit increase in factor $h$ multiplies the expected abundance by $\exp(\lambda_{jh})$ with the other factor fixed. In the negative binomial model, $\exp(\alpha_j)$ is the expected abundance at zero on both factors, and $\exp(\lambda_{jh})$ is the mean ratio for a unit increase in factor $h$ with the other fixed. Size additionally controls variation around that conditional mean. The two models use the same coefficient values in these simulations. Each site factor has population variance one, so the loading compares sites one factor standard deviation apart at the same value of the other factor.

Since the site factors $z_i$ have covariance matrix $I_2$, the covariance of the linear predictors for species $j$ and $k$ is the loading inner product $\lambda_j^\top\lambda_k$. To find the covariance of their counts, consider distinct species. Conditional independence gives $E(Y_{ij}Y_{ik}\mid z_i)=\mu_{ij}\mu_{ik}$. The product contains the sum of the two loading vectors in its exponent. For any vector $t$ of two coefficients, the standard normal moment generating function gives $E\lbrace \exp(t^\top z_i)\rbrace =\exp(\Vert t\Vert ^2/2)$. Take $t=\lambda_j$ to obtain the marginal mean $m_j=E(Y_{ij})$. Taking $t=\lambda_j+\lambda_k$ gives the cross-moment for the same site,

\[\begin{aligned} m_j &= \exp\{\alpha_j+\|\lambda_j\|^2/2\},\\ E(Y_{ij}Y_{ik}) &=\exp\{\alpha_j+\alpha_k+\|\lambda_j+\lambda_k\|^2/2\}\\ &=m_jm_k\exp(\lambda_j^\top\lambda_k). \end{aligned}\]

Subtracting $m_jm_k$ gives $\operatorname{Cov}(Y_{ij},Y_{ik})=m_jm_k\lbrace \exp(\lambda_j^\top\lambda_k)-1\rbrace $. The sign of the loading inner product therefore determines the sign of the count covariance in either model. A common orthogonal rotation of the loadings preserves their lengths and inner products, so it also preserves these marginal means and covariances. This covariance is for counts from different species at the same site. Conditional variance around each mean still contributes to each species’ marginal variance.

The negative binomial log probability and its derivatives

For a single species at fixed factors, write $y$ for its observed count, $\mu$ for its conditional mean and $r>0$ for its negative binomial size. With probability parameter $0<p<1$, its negative binomial probability contains $p^r(1-p)^y$. Setting $p=r/(r+\mu)$ gives mean $r(1-p)/p=\mu$ and variance $r(1-p)/p^2=\mu+\mu^2/r$. The choice of size thus affects dispersion even after the factors have specified the mean. For nonnegative integer $y$, the gamma function $\Gamma$ gives the coefficient multiplying the two powers. Substituting for $p$ and taking logarithms gives the probability and its logarithm,

\[\begin{aligned} \Pr(Y=y\mid\mu,r)&=\frac{\Gamma(y+r)}{\Gamma(r)\Gamma(y+1)} \left(\frac{r}{r+\mu}\right)^r \left(\frac{\mu}{r+\mu}\right)^y,\\ \ell(y;\mu,r)&=\log\Gamma(y+r)-\log\Gamma(r)-\log\Gamma(y+1)\\ &\quad +r\log r+y\log\mu-(r+y)\log(r+\mu). \end{aligned}\]

The last term depends on both parameters. It enters both derivatives even if the count is zero.

Let $\eta=\log\mu$ and $\rho=\log r$. In the derivative with respect to $\eta$, the term $y\log\mu$ gives $y$ and the derivative of $\log(r+\mu)$ is $\mu/(r+\mu)$. For the derivative with respect to size, write $\psi(r)=d\log\Gamma(r)/dr$ for the digamma function. The two gamma terms involving size then contribute $\psi(y+r)-\psi(r)$. Differentiating $r\log r$ gives $\log r+1$, and differentiating $(r+y)\log(r+\mu)$ requires the product rule. Multiplying the derivative with respect to size by $dr/d\rho=r$ gives the derivative with respect to log size. The two partial derivatives are

\[\begin{aligned} s_\eta&=y-(r+y)\frac{\mu}{r+\mu}=\frac{r(y-\mu)}{r+\mu},\\ s_\rho&=r\left[\psi(y+r)-\psi(r)+\log\!\left(\frac{r}{r+\mu}\right) +1-\frac{r+y}{r+\mu}\right]. \end{aligned}\]

In an intercept-only fit, all sites have the same $\eta$, the log of their common fitted mean. The intercept-only fit pools variation from differences in site means and variation around those means. After averaging over normally distributed site factors, this count distribution is generally not itself negative binomial. The intercept-only size therefore estimates a different dispersion description from the size conditional on the factors.

At fixed size, the intercept-only fit minimizes the negative sum of the site log probabilities using the negative sum of $s_\eta$ as its gradient. Estimating size adds a second coordinate whose gradient component is the negative sum of $s_\rho$.

The simulated counts and intercept-only fits

The count matrices counts-Poisson.rds and counts-NB.rds were generated with seeds 1102 and 1103, respectively. The two simulations use the same intercepts and loadings from model2 and draw new site factors for each sample. The second simulation sets size to four. From the book directory, load the functions and read the two samples. The separate mixed-response matrix Y2 supplies only the row count for the intercept-only design. The response values for the fits come from the site counts in counts$NB$Y.

1
2
3
4
5
6
7
8
9
10
11
12
source("code/lib/result.R")
source("code/lib/differentiation.R")
source("code/lib/newton.R")
source("code/lib/mixed_factor.R")
model2 <- mixed6_model()
Y2 <- readRDS("data/source/ch11/MIXED6.rds")
counts <- lapply(c("Poisson","NB"), function(family) {
  model <- mixed6_model(families=rep(family,6L))
  data <- readRDS(paste0("data/source/ch11/counts-",family,".rds"))
  list(Y=data,model=model)
})
names(counts) <- c("Poisson","NB")

For each column of the negative binomial matrix, supply a single column of ones as the design. The six fits in fixed_start use the default size of four. For species six, estimate_size=TRUE starts the additional coordinate at $\log 4$. Both types of fit start the intercept at the logarithm of the sample mean, with a lower bound of 0.1 on the mean used for initialization.

1
2
3
fixed_start <- lapply(seq_len(6L),function(j)
  nb_glm_start(counts$NB$Y[,j],matrix(1,nrow(Y2),1)))
nb_start <- nb_glm_start(counts$NB$Y[,6],matrix(1,nrow(Y2),1),estimate_size=TRUE)

Both functions are in code/lib/mixed_factor.R.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
nb_glm_start <- function(y, X, size = 4, estimate_size = FALSE) {
  start <- c(rep(0, ncol(X)), if (estimate_size) log(size))
  start[1] <- log(max(mean(y), .1))
  calc <- function(u) {
    eta <- drop(X %*% u[seq_len(ncol(X))])
    r <- if (estimate_size) exp(tail(u,1)) else size
    w <- plogis(eta-log(r))
    list(value = -sum(dnbinom(y, size=r, mu=exp(eta), log=TRUE)),
      gradient = -c(drop(crossprod(X, y-(y+r)*w)),
        if (estimate_size) sum(nb_size_score(y, eta, log(r)))))
  }
  fn <- function(u) calc(u)$value
  gr <- function(u) calc(u)$gradient
  newton(fn, gr, function(u) num_hess(fn, u, gr=gr)$hessian, start)
}
1
2
3
4
5
6
7
nb_size_score <- function(y, eta, log_size) {
  r <- exp(log_size)
  mu <- exp(eta)
  # Differentiate the gamma-function terms and the mean/size normalizing constant.
  original <- digamma(y+r) - digamma(r) + log(r/(r+mu)) + 1 - (r+y)/(r+mu)
  r * original
}

In nb_size_score(), original is the derivative of the log probability with respect to $r$, and multiplying it by $r$ gives $s_\rho$. In nb_glm_start(), calc() returns the negative log likelihood and its gradient, $-X^\top s_\eta$ followed by $-\sum_i s_\rho$ when the size is estimated. The calls to nb_glm_start() implement the intercept-only criteria above. The quantity plogis(eta-log(r)) in the fitting function equals $\mu/(r+\mu)$, the fraction in $s_\eta$, and nb_size_score() supplies $s_\rho$ when size is estimated. The Hessian comes from num_hess() (Section 3.1) applied to the analytic gradient, and newton() (Section 2.6) uses it to compute its step.

The next table compares conditional means and variances with marginal means and covariances under the generating models. It also reports the six fitted intercepts, which are not inputs to the joint factor fits.

1
2
3
4
5
6
7
8
9
10
11
linear_predictor_covariance <- tcrossprod(model2$loading)
conditional_mu <- exp(model2$intercept)
marginal_mu <- conditional_mu*exp(diag(linear_predictor_covariance)/2)
first_covariance <- marginal_mu[1]*marginal_mu*expm1(linear_predictor_covariance[1,])
# A within-species variance also includes conditional count variation.
first_covariance[1] <- NA_real_
print(data.frame(species=seq_len(6L),mean_at_zero=conditional_mu,
  Poisson_variance=conditional_mu,
  NB_variance=conditional_mu+conditional_mu^2/4,marginal_mean=marginal_mu,
  covariance_with_species_1=first_covariance,
  initial_intercept=vapply(fixed_start,function(f)unname(f$par[1]),0.0)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  species mean_at_zero Poisson_variance NB_variance marginal_mean
1       1    1.0000000        1.0000000   1.2500000     1.3771278
2       2    1.6487213        1.6487213   2.3282917     2.3163670
3       3    0.7408182        0.7408182   0.8780211     0.9656054
4       4    1.0000000        1.0000000   1.2500000     1.2840254
5       5    1.2214028        1.2214028   1.5943589     1.5295904
6       6    0.9048374        0.9048374   1.1095201     1.1331485
  covariance_with_species_1 initial_intercept
1                        NA       0.359421170
2                 0.5534881       0.667829373
3                 0.9982158       0.004987542
4                 0.1472738       0.165514438
5                 1.2977246       0.465305108
6                 0.4232816      -0.017654935

Between species and initial_intercept, the five columns describe the generating models. tcrossprod() applied to the loading matrix gives all pairwise inner products, and expm1() converts each inner product with species one into the multiplier for the count covariance. The column initial_intercept reports the fitted intercepts.

When both factors equal zero, the conditional mean count of species two is 1.64872. Its Poisson variance is also 1.64872, while its negative binomial variance is 2.32829. Averaging over the distribution of the site factors gives marginal means from 0.96561 to 2.31637. Species one and two have loading inner product $0.8(0.2)=0.16$, giving count covariance $1.3771278(2.3163670)(e^{0.16}-1)=0.55349$ to five decimal places. The NA in the first row leaves out the variance of species one. That variance is the sum of the variance of its conditional mean and its expected conditional variance. To check the fitted intercept for species six, use a generalized linear model with the same log link function and fixed size.

1
2
3
4
nb_reference <- stats::glm(y~1,data=data.frame(y=counts$NB$Y[,6]),
  family=MASS::negative.binomial(theta=4))
print(c(fixed_size=4,Newton=fixed_start[[6]]$par[1],
  reference=unname(coef(nb_reference)[1])))
1
2
 fixed_size      Newton   reference 
 4.00000000 -0.01765494 -0.01765494 

Both estimates give $-0.017655$. At any fixed positive size, $r/(r+\mu)$ is common to all sites in this fit. Setting the summed derivative with respect to the intercept to zero therefore gives $\hat\mu=\bar y$, the sample mean. The 393 individuals across 400 sites give $\log(393/400)=-0.017655$ to six decimals. The finite intercept solution requires $\bar y>0$. With all counts zero, the likelihood increases as the intercept tends to $-\infty$; the starting-value floor does not create a finite maximum.

For the count five at $\eta=0.4$ and $r=4$, num_grad() (Section 3.1) approximates both derivatives of the log probability.

1
2
3
4
5
log_mass <- function(u) dnbinom(5,mu=exp(u[1]),size=exp(u[2]),log=TRUE)
nb_par <- c(.4,log(4))
print(data.frame(coordinate=c("log mean","log size"),
  analytic=c(mixed_response(5,.4,model2,6)$score,
    nb_size_score(5,.4,log(4))),numerical=num_grad(log_mass,nb_par)$gradient))
1
2
3
  coordinate   analytic  numerical
1   log mean  2.5551983  2.5551983
2   log size -0.2849679 -0.2849679

The derivatives with respect to the linear predictor and log size agree with their numerical approximations at the printed precision. Increasing the log mean raises the log probability of five locally, whereas increasing log size lowers it. For the intercept-and-size fit, exponentiating the second coordinate gives size on its original scale. The last calculation compares negative binomial and Poisson log probabilities for the same count and mean.

1
2
3
print(list(count=nrow(counts$NB$Y),intercept=nb_start$par[1],size=exp(nb_start$par[2]),
  stop=nb_start$reason,Poisson_limit=dnbinom(5,1e7,mu=exp(.4),log=TRUE)-
    dpois(5,exp(.4),log=TRUE)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
$count
[1] 400

$intercept
[1] -0.01765494

$size
[1] 1.568218

$stop
[1] "converged"

$Poisson_limit
[1] 3.653171e-07

The fit met the scaled gradient tolerance of $10^{-6}$. Estimating size preserves the intercept because the same mean solves its score equation for every positive size. The fitted size of 1.568218 is smaller than the generating conditional size of four. At a fixed mean, increasing size sends inverse size $\phi=1/r$ toward zero. For fixed count $y$, the probability can be written as

\[\frac{\mu^y}{y!}\left\{\prod_{h=0}^{y-1}(1+h/r)\right\}(1+\mu/r)^{-(r+y)}.\]

The product tends to one and the last term tends to $e^{-\mu}$, giving the Poisson probability in the limit $r\to\infty$, or equivalently $\phi=1/r\to0$ from above. Thus zero is the boundary on the inverse-size scale; it is not a finite value of size. At size $10^7$, the negative binomial log probability exceeds the Poisson log probability by $3.653171\times10^{-7}$ for the specified count and mean. A negative inverse size would fall outside the count model. The site factors can still induce covariance at the Poisson boundary. Shrinking a factor’s scale to zero removes its contribution to the linear predictors if all associated unscaled loadings remain fixed and finite. The gllvm package fits count factor models, and MASS provides negative binomial regression.

11.3 Multidimensional conditional modes and Laplace approximation

The six responses of one person in MIXED6 give a conditional log likelihood $\ell_i(z)$ at each possible factor vector $z$. Where should the integration nodes be centered for this person, and how far apart should they be? With the model parameters fixed, the integrand is the product of the conditional likelihood and the standard normal factor density. Let $d=2$ be the number of factors, $h_i(z)$ the negative logarithm of that product and $L_i$ the person’s contribution to the marginal likelihood. Including the normal density’s constant gives

\[h_i(z)=-\ell_i(z)+\tfrac12 z^\top z+\tfrac d2\log(2\pi), \qquad L_i=\int_{\mathbb R^d}e^{-h_i(z)}\,dz .\]

The factor density conditional on the observed responses is $e^{-h_i(z)}/L_i$. Its mode $\hat z_i$ minimizes $h_i$ because $L_i$ is constant in $z$. Here conditional mode means the maximizer of the factor density given this person’s responses at fixed model parameters. It is not a maximum likelihood estimate obtained by omitting the normal factor density. Let $s_{ij}$ be the derivative of response $j$’s conditional log density or log probability with respect to its linear predictor, and let $w_{ij}$ be the negative second derivative of that same log term. The linear predictor has gradient $\lambda_j$ in $z$. Applying the chain rule once gives the gradient $g_i$ and applying it again gives the Hessian $H_i$,

\[g_i(z)=z-\sum_j\lambda_j s_{ij}, \qquad H_i(z)=I_d+\sum_j w_{ij}\lambda_j\lambda_j^\top .\]

The negative log factor density contributes $z$ to the gradient and the identity matrix $I_d$ to the Hessian. A response with two nonzero loadings can therefore contribute to the off-diagonal curvature.

These derivatives can be checked for the first person in MIXED6. From the book directory, load the functions and read the observed responses. The next calculation expresses the generating model in the coordinates required for numerical integration and defines h_first() for the first person. The objects named truth2 contain the supplied generating parameters; they are not estimates from these responses.

1
2
3
4
5
6
7
8
9
10
11
source("code/lib/differentiation.R")
source("code/lib/integration.R")
source("code/lib/mixed_factor.R")
source("code/lib/mixed_laplace.R")
model2 <- mixed6_model()
Y2 <- readRDS("data/source/ch11/MIXED6.rds")
items2 <- laplace_items(Y2,model2$family)
truth2 <- laplace_coordinates(model2,items2)
y1 <- items2$Y[1,]
h_first <- function(z) laplace_person_h(z,y1,items2,truth2$par,truth2$loadings)
derivative_point <- c(.3,-.2)

For the numerical evaluation, laplace_items() adds one to the binary and ordinal codes throughout the observed matrix. For person one, the success becomes category 2 and the lowest rating becomes category 1. The returned type selects each response family, K gives the category count for binary and ordinal responses, and index[[j]] selects response $j$’s coordinates in the packed parameter vector. Each block begins with its first loading, followed by its intercepts and any residual variance or inverse size. This example contains every rating category; laplace_items() otherwise infers $K$ from the number of observed codes, which can disagree with the specified categories if some are absent.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
laplace_items <- function(Y, families, K = NULL) {
  map <- c(normal = "normal", Bernoulli = "GRM", ordinal = "GRM", Poisson = "poisson",
    NB = "negbin")
  type <- unname(map[families])
  stopifnot(!anyNA(type))
  Y <- as.matrix(Y)
  observed <- K
  K <- rep(1L, ncol(Y))
  for (j in which(type == "GRM")) {
    Y[, j] <- Y[, j] + 1
    K[j] <- if (is.null(observed)) length(unique(Y[, j])) else observed[j]
  }
  # Coordinates of each item: loading, then its own intercepts and scale.
  sizes <- ifelse(type == "GRM", 1L + K - 1L, ifelse(type == "poisson", 2L, 3L))
  ends <- cumsum(sizes)
  index <- lapply(seq_along(sizes), function(j) (ends[j] - sizes[j] + 1L):ends[j])
  list(Y = Y, type = type, K = K, index = index, length = sum(sizes))
}

A binary or ordinal response has one loading and $K-1$ intercepts, a Poisson response a loading and an intercept, and a normal or negative binomial response one more coordinate; sizes counts them and index lists their positions.

laplace_coordinates() expresses the generating model in the form used by laplace_item(). The matrix truth2$loadings supplies both loadings for each response. The vector truth2$par supplies the response parameters. It uses the normal residual variances, subtracts the ordinal cutpoints from the ordinal intercept to give the intercepts for the exceedance probabilities, and expresses negative binomial dispersion as inverse size.

1
2
3
4
5
6
7
8
9
10
11
12
laplace_coordinates <- function(model, items) {
  par <- numeric(items$length)
  for (j in seq_along(items$type)) {
    a <- model$loading[j, 1]
    par[items$index[[j]]] <- switch(items$type[j],
      normal = c(a, model$intercept[j], model$sd[j]^2),
      poisson = c(a, model$intercept[j]),
      negbin = c(a, model$intercept[j], 1 / model$size[j]),
      GRM = if (items$K[j] == 2) c(a, model$intercept[j]) else c(a, model$intercept[j] - model$cuts))
  }
  list(par = par, loadings = model$loading)
}

For each response, laplace_item() stores its derivatives in the matrix C. The first three columns give the negative log term, $-s_{ij}$ and $w_{ij}$. In laplace_person_h(), the second column times the loading vector adds to gradient. The third column times the outer product of the loading vector adds to hessian.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
laplace_person_h <- function(z, y, items, par, loadings) {
  p <- length(z)
  value <- sum(z^2) / 2 + p * log(2 * pi) / 2
  gradient <- z
  hessian <- diag(p)
  for (j in seq_along(items$type)) {
    a <- loadings[j, ]
    d <- laplace_item(y[j], items$type[j], sum(a * z), par[items$index[[j]]], items$K[j])$C
    value <- value + d[1, 1]
    gradient <- gradient + d[1, 2] * a
    hessian <- hessian + d[1, 3] * tcrossprod(a)
  }
  list(value = value, gradient = gradient, hessian = hessian)
}

The function starts from the standard normal factor terms, $z^\top z/2+\tfrac p2\log(2\pi)$ with gradient $z$ and Hessian $I$, and adds each response’s contribution at the linear predictor $\lambda_j^\top z$; value is the negative log of the joint density of the responses and the factors.

At the trial vector $(0.3,-0.2)^\top$, away from the mode, num_grad() and num_hess() differentiate the scalar value returned by h_first() for comparison with its analytic derivatives.

1
2
3
4
5
print(c(gradient_check=max(abs(num_grad(function(z) h_first(z)$value,
  derivative_point)$gradient-
    h_first(derivative_point)$gradient)),
  hessian_check=max(abs(num_hess(function(z) h_first(z)$value,derivative_point)$hessian-
    h_first(derivative_point)$hessian))))
1
2
gradient_check  hessian_check 
  1.417702e-10   4.818768e-10 

The largest absolute differences are about $1.4\times10^{-10}$ for a gradient component and $4.8\times10^{-10}$ for a Hessian entry. Use the gradient and Hessian in Newton iterations to find the conditional mode, with the response parameters and loadings fixed.

Laplace approximations and adaptive quadrature

For valid parameters in the response families used here, each $w_{ij}$ is nonnegative, so $H_i(z)$ is positive definite because of its identity-matrix term. This mathematical property assumes positive residual variances and size and correctly ordered cutpoints; a numerical routine must still enforce these domains. At the conditional mode, the linear term in the expansion of $h_i$ vanishes. Write $u=z-\hat z_i$ and $H=H_i(\hat z_i)$. When $H$ is positive definite, replacing $h_i(\hat z_i+u)$ by $h_i(\hat z_i)+u^\top H u/2$ makes the integrand proportional to a normal density with covariance $B=H^{-1}$. This covariance describes the spread of the local normal approximation to this person’s conditional factor distribution at fixed model parameters. It need not equal the exact conditional covariance. The logarithm of the resulting integral is the first-order Laplace approximation,

\[A_{1i}=-h_i(\hat z_i)+\tfrac d2\log(2\pi)-\tfrac12\log|H|.\]

The quadratic term sets the width of the integrand. To account for departures from that shape, let $c_{3j}$ and $c_{4j}$ denote the third and fourth derivatives of the negative conditional log term with respect to its linear predictor, evaluated at the mode. Take a centered normal displacement $U$ with covariance $B$ and write $V_j=\lambda_j^\top U$ for the displacement in linear predictor $j$. The covariance of $V_j$ and $V_k$ is $G_{jk}=\lambda_j^\top B\lambda_k$, with variance $g_j=G_{jj}$. In the Taylor expansion of $h_i$, the cubic and quartic terms are $T_3=\sum_j c_{3j}V_j^3/6$ and $T_4=\sum_j c_{4j}V_j^4/24$. The cubic term alone averages to zero by symmetry. Expanding the exponential gives the correction $E(-T_4+T_3^2/2)$ to this order. The normal moments needed are $E(V_j^4)=3g_j^2$ and $E(V_j^3V_k^3)=6G_{jk}^3+9g_jg_kG_{jk}$. With the Taylor coefficients $-1/24$ and $1/72$, these give the relative correction

\[\epsilon=-\frac18\sum_j c_{4j}g_j^2 +\frac1{12}\sum_{j,k}c_{3j}c_{3k}G_{jk}^3 +\frac18\sum_{j,k}c_{3j}c_{3k}g_jg_kG_{jk}.\]

The corrected approximation multiplies the first-order integral by $1+\epsilon$. When $1+\epsilon$ is positive, the second-order approximation to $\log L_i$ is $A_{1i}+\log(1+\epsilon)$. The orders refer to the approximation of the integral: the first uses the quadratic expansion, and the second adds terms formed from third and fourth derivatives. A positive $1+\epsilon$ permits the logarithm but does not guarantee a more accurate result. With only six responses per person, increasing the number of people alone does not make each person’s conditional density increasingly concentrated.

Adaptive Gauss-Hermite quadrature uses the same center and curvature to evaluate the original integrand at several points. For a product node $x_\nu$, let $w_{\nu a}$ be the ordinary Hermite weight along axis $a$ for the weight function $e^{-x^2}$. The lower triangular Cholesky factor $L$ satisfies $LL^\top=B$. The transformed node $z_\nu$, the adjusted product weight $W_\nu$ and the approximate marginal likelihood are

\[z_\nu=\hat z_i+\sqrt{2}\,Lx_\nu,\qquad W_\nu=\prod_{a=1}^d w_{\nu a}\exp(x_{\nu a}^2),\qquad L_i\ \approx\ 2^{d/2}|H|^{-1/2}\sum_\nu W_\nu e^{-h_i(z_\nu)} .\]

The exponential in each weight cancels the Hermite weight function. The change of variables multiplies the volume element by $2^{d/2}\vert H\vert ^{-1/2}$. These adjusted integration weights need not sum to one and are not probabilities of factor values.

The function laplace_person() combines the mode search with either order of the Laplace approximation or adaptive quadrature, using the same conditional likelihood and factor density for all three calculations.

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
laplace_person <- function(y, items, par, loadings, method = "Laplace", accuracy = 2L,
                           start = rep(0, ncol(loadings)), tol = 1e-8, maxit = 100L) {
  p <- ncol(loadings)
  J <- length(items$type)
  derivs <- function(z) lapply(seq_len(J), function(j)
    laplace_item(y[j], items$type[j], sum(loadings[j, ] * z),
      par[items$index[[j]]], items$K[j])$C)
  z0 <- start
  steps <- 0L
  mode <- NULL

  # Update both factors using all six response gradients and Hessians.
  for (iter in seq_len(maxit)) {
    d <- derivs(z0)
    g <- z0
    H <- diag(p)
    for (j in seq_len(J)) {
      a <- loadings[j, ]
      g <- g + d[[j]][1, 2] * a
      H <- H + d[[j]][1, 3] * tcrossprod(a)
    }
    z1 <- z0 - solve(H, g)
    steps <- iter
    done <- ifelse(z0 == 0, abs(z1) < tol, abs((z0 - z1) / z0) < tol)
    if (all(done & !is.na(done))) {
      mode <- z1
      break
    }
    z0 <- z1
  }
  if (is.null(mode)) stop("Newton steps for the mode did not settle")

  # Recompute the height and curvature at the accepted mode.
  d <- derivs(mode)
  h0 <- sum(mode^2) / 2 + p * log(2 * pi) / 2
  H <- diag(p)
  for (j in seq_len(J)) {
    h0 <- h0 + d[[j]][1, 1]
    H <- H + d[[j]][1, 3] * tcrossprod(loadings[j, ])
  }
  B <- solve(H)
  logdet <- as.numeric(determinant(H, logarithm = TRUE)$modulus)
  if (method == "Laplace") {
    value <- -h0 - logdet / 2 + p * log(2 * pi) / 2
    epsilon <- 0

    # Correct the quadratic integral using derivatives with respect to the linear predictors at the mode.
    if (accuracy == 2L) {
      c3 <- vapply(d, function(x) x[1, 4], 0)
      c4 <- vapply(d, function(x) x[1, 5], 0)
      G <- loadings %*% B %*% t(loadings)  # lambda_j' B lambda_k
      g <- diag(G)
      epsilon <- -sum(c4 * g^2) / 8 + sum(outer(c3, c3) * G^3) / 12 +
        sum(outer(c3 * g, c3 * g) * G) / 8
      value <- value + log(1 + epsilon)
    }
    return(list(value = value, mode = mode,
      hessian = H, epsilon = epsilon, steps = steps))
  }

  # Transform the product grid and sum the weighted joint densities.
  rule <- hermite_rule(accuracy)
  grid <- as.matrix(expand.grid(rep(list(rule$x), p)))
  weights <- apply(as.matrix(expand.grid(rep(list(rule$w), p))), 1, prod)
  L <- t(chol(B))
  terms <- vapply(seq_len(nrow(grid)), function(k) {
    node <- drop(sqrt(2) * L %*% grid[k, ]) + mode
    hq <- sum(node^2) / 2 + p * log(2 * pi) / 2
    for (j in seq_len(J)) hq <- hq + laplace_item(y[j], items$type[j],
      sum(loadings[j, ] * node),
      par[items$index[[j]]], items$K[j])$C[1, 1]
    weights[k] * exp(-hq)
  }, 0)
  list(value = log(sum(terms)) + p * log(2) / 2 - logdet / 2, mode = mode, hessian = H,
    steps = steps)
}

Starting at zero, laplace_person() evaluates both derivatives at the current vector z0. The line z1 <- z0 - solve(H, g) solves the Newton equations for the two factors together. The response parameters and loadings remain fixed. For a nonzero old coordinate, the stopping test divides its absolute change by its absolute old value. For an old coordinate equal to zero, it tests the absolute change directly. Both coordinates must pass the tolerance $10^{-8}$. A previous mode can also serve as the start. If no step meets the criterion within 100 iterations, the two-factor routine signals an error.

In laplace_person(), p is the number of factors and columns four and five of each response’s derivative matrix supply c3 and c4. In R, c4 * g^2 gives the six quartic contributions before division by $-8$. The two outer() calls form all response pairs for the cubic contributions, and g <- diag(G) now contains the six variances of the displacements in the linear predictors.

For adaptive quadrature, hermite_rule() already includes the exponential adjustment in rule$w. Multiplying those weights across axes gives weights[k] for grid row k. The change in volume supplies the two terms added to log(sum(terms)). This calculation exponentiates the negative log integrand before summing, so very small integrands can round to zero even when their logarithms are finite.

Three integration methods for the first person

To compare the three integration methods for this person, pass the same observed row and generating parameters to every call. For the Laplace method, accuracy selects the expansion order. For adaptive quadrature, it gives the number of nodes on each axis, so the 11-node rule evaluates $11^2$ pairs of factor values. The object center stores the mode from the second-order calculation so that h_first() can evaluate the gradient there.

1
2
3
4
5
6
7
8
9
10
first_person <- lapply(list(Laplace1=list("Laplace",1L),Laplace2=list("Laplace",2L),
  AGQ11=list("AGQ",11L),
  AGQ15=list("AGQ",15L),AGQ31=list("AGQ",31L)),function(m)
  laplace_person(y1,items2,truth2$par,truth2$loadings,m[[1]],m[[2]]))
center <- first_person$Laplace2$mode
print(list(mode=center,Newton_steps=first_person$Laplace2$steps,
  gradient=h_first(center)$gradient,
  curvature=first_person$Laplace2$hessian,
    second_order_epsilon=first_person$Laplace2$epsilon,
  log_integrals=vapply(first_person,function(f) f$value,0.0)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$mode
[1] -0.4454162  0.2373560

$Newton_steps
[1] 4

$gradient
[1]  8.326673e-17 -5.551115e-17

$curvature
          [,1]      [,2]
[1,] 2.2112524 0.4968409
[2,] 0.4968409 2.0613944

$second_order_epsilon
[1] -0.001251496

$log_integrals
 Laplace1  Laplace2     AGQ11     AGQ15     AGQ31 
-8.218655 -8.219907 -8.219901 -8.219901 -8.219901 

Four Newton steps give the mode $(-0.44542,0.23736)^\top$. Both gradient components have magnitude below $10^{-16}$. The curvature matrix has diagonal entries 2.21125 and 2.06139 and off-diagonal entry 0.49684. The printed field second_order_epsilon reports $-0.001251496$ before taking the logarithm. Adding $\log(1-0.001251496)$ moves the first-order result from $-8.218655$ to $-8.219907$. The 11-, 15- and 31-node rules all give $-8.219901$ to six decimals. The first-order result is about 0.00125 above that value and the second-order result is about 0.000006 below it. For independent people, the sample marginal log likelihood is the sum of their log integrals. Each row therefore requires its own mode and curvature for these calculations.

1
2
3
4
5
6
7
row_values <- vapply(list(Laplace1=list("Laplace",1L),Laplace2=list("Laplace",2L),
  AGQ11=list("AGQ",11L)),
  function(m) sum(vapply(seq_len(nrow(Y2)),function(i)
    laplace_person(items2$Y[i,],items2,truth2$par,truth2$loadings,
      m[[1]],m[[2]])$value,0.0)),0.0)
print(c(row_values,
  Laplace2_minus_AGQ11=unname(row_values["Laplace2"]-row_values["AGQ11"])))
1
2
3
4
            Laplace1             Laplace2                AGQ11 
       -3.174345e+03        -3.174606e+03        -3.174617e+03 
Laplace2_minus_AGQ11 
        1.065047e-02 

For all 400 people, the first-order, second-order and 11-node totals are $-3174.345$, $-3174.606$ and $-3174.617$. The second-order total exceeds the 11-node total by 0.01065047. This signed difference sums discrepancies that can vary across people. The checks with 15 and 31 nodes on each axis concern only the first person. Neither this total difference nor agreement to six decimals for the first person is an error bound for all 400 integrals.

Starting at the previous mode

A small change in a model parameter can leave the previous conditional mode close to the new one. Increasing the first normal intercept by 0.02 and reconstructing the parameters with laplace_coordinates() gives a neighboring model for the same observed row. Comparing a start at zero with a start at the previous mode measures the work saved in this example. Both calls use the default second-order Laplace correction.

1
2
3
4
5
6
7
near <- model2
near$intercept[1] <- near$intercept[1]+.02
near_truth <- laplace_coordinates(near,items2)
print(lapply(list(from_zero=c(0,0),from_previous_mode=center),function(z) {
  f <- laplace_person(y1,items2,near_truth$par,near_truth$loadings,start=z)
  list(start=z,mode=f$mode,Newton_steps=f$steps,value=f$value)
}))
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
$from_zero
$from_zero$start
[1] 0 0

$from_zero$mode
[1] -0.4530686  0.2391990

$from_zero$Newton_steps
[1] 4

$from_zero$value
[1] -8.227922


$from_previous_mode
$from_previous_mode$start
[1] -0.4454162  0.2373560

$from_previous_mode$mode
[1] -0.4530686  0.2391990

$from_previous_mode$Newton_steps
[1] 3

$from_previous_mode$value
[1] -8.227922

Both starts give the new mode $(-0.45307,0.23920)^\top$ and the second-order approximation $-8.227922$ to the log integral. Starting at the old mode takes three steps, one fewer than starting at the origin. At the old mode, the intercept change adds $0.8(0.02)=0.016$ to the first gradient component because the measurement has unit residual variance and first loading 0.8. Its second loading is zero, yet both factor coordinates move when the coupled Newton equations are solved.

The two Laplace orders give different approximations to the same person’s log integral. For the full sample, the comparison with quadrature measures a difference in the summed log likelihood at the generating parameters. To affect an estimated intercept or loading, the difference between two approximations must vary with the model parameters. A difference constant over the parameter space would give the same set of maximizers. Comparing estimates therefore requires optimizing the likelihood under each approximation. The lamle package provides Laplace approximation and adaptive quadrature for latent variable models.

11.4 A lower bound on the marginal log likelihood using a normal approximation to the conditional factor distribution

The conditional mode locates the peak of the factor density after observing person $i$’s response vector $y_i$. To approximate the whole conditional distribution, use an approximating density $q_i$ for person $i$’s $d$ factors and choose it from the normal family $N_d(m_i,V_i)$. Choosing the mean and covariance by maximizing the lower bound below is called a normal variational approximation (VA). Its mean vector $m_i$ locates the center, and its full, positive definite covariance matrix $V_i$ describes both uncertainty in each factor and dependence between them. Even with independent factors in the population, observing a response that loads on two factors can associate them conditionally. A full covariance allows the normal approximation to follow that dependence. Both $m_i$ and $V_i$ can vary with the person’s responses. How should they be chosen when the marginal likelihood needed to normalize the conditional density is itself difficult to evaluate?

Fix the model parameters $\theta$ and write $p(y_i,z\mid\theta)$ for the joint density of the observations and factors, using the probability mass function for the discrete responses. Its integral over $z$ is the person’s contribution $L_i(\theta)$ to the marginal likelihood. Assume $0<L_i(\theta)<\infty$ and that the log ratios below have finite expectations. In this model the joint density at the observed responses and the trial density $q_i$ are positive on the same factor space, and $q_i$ integrates to one. Dividing the joint density by $q_i$ and averaging under $q_i$ thus recovers $L_i(\theta)$. Jensen’s inequality for the concave logarithm bounds $\log L_i(\theta)$ from below by the expected log ratio. Writing $\mathcal L_i$ for the expected log ratio gives

\[\mathcal L_i=E_{q_i}\!\left[\log\frac{p(y_i,Z\mid\theta)}{q_i(Z)}\right]\leq \log L_i(\theta).\]

To find the gap, factor the numerator as $L_i(\theta)p(z\mid y_i,\theta)$. The first of these is constant over $z$. Moving the remaining expectation to the other side gives

\[\log L_i(\theta)=\mathcal L_i+ \underbrace{E_{q_i}\!\left[\log\frac{q_i(Z)}{p(Z\mid y_i,\theta)}\right]} _{\operatorname{KL}\!\left(q_i\,\|\,p(\cdot\mid y_i,\theta)\right)} .\]

The Kullback-Leibler (KL) divergence on the right is nonnegative and vanishes exactly when the two normalized densities agree almost everywhere. Its direction matters: the expectation is taken under $q_i$, with the conditional factor density in the denominator. Thus $\mathcal L_i$ is a lower bound on the marginal log likelihood. Equality requires agreement throughout the factor distribution, including its spread; matching the conditional mode alone is insufficient.

The same joint density can also be factored in the order in which the model generates the observations. Let $\phi_d$ be the standard normal factor density with mean zero and covariance $I_d$. Given $z$, the response model supplies $p(y_i\mid z,\theta)$. Substitution of their product into the expected log ratio gives

\[\begin{aligned} \mathcal L_i &=E_{q_i}\log p(y_i\mid Z,\theta) +E_{q_i}\log\phi_d(Z)-E_{q_i}\log q_i(Z)\\ &=E_{q_i}\log p(y_i\mid Z,\theta) -\operatorname{KL}\!\left(q_i\,\|\,N_d(0,I_d)\right). \end{aligned}\]

The first term averages the conditional log likelihood of the observed responses under the proposed distribution of this person’s factors. Local independence makes it a sum of expected response log densities and log probabilities. In this expression for $\mathcal L_i$, the divergence compares $q_i$ with the population factor distribution $N_d(0,I_d)$, also called the factor prior. The gap from $\mathcal L_i$ to $\log L_i(\theta)$ instead compares $q_i$ with the factor distribution conditional on the responses. Choosing the population distribution for $q_i$ makes the subtracted divergence zero, but generally leaves a positive gap to the marginal log likelihood. No prior distribution on the shared model parameters is introduced here.

For a normal $q_i$, the divergence to the factor prior can be evaluated from $m_i$ and $V_i$. In the log ratio $\log q_i(z)-\log\phi_d(z)$, the two normalizing terms involving $2\pi$ cancel. The prior contributes a positive quadratic $z^\top z/2$ to this difference. Its expectation involves $E_{q_i}(ZZ^\top)=V_i+m_im_i^\top$. The quadratic from $q_i$ is centered at $m_i$ and has a minus sign. Its expected value before multiplication by $-1/2$ is $\operatorname{tr}(V_i^{-1}V_i)=d$. The normalizing constant of $q_i$ contributes the remaining log determinant, giving

\[\operatorname{KL}\!\left(q_i\,\|\,N_d(0,I_d)\right) =\tfrac12\left\{\operatorname{tr}(V_i)+m_i^\top m_i-d-\log|V_i|\right\}.\]

Write $C$ for the lower triangular Cholesky factor with positive diagonal entries and $V_i=CC^\top$. The trace is $\sum_{j,k}C_{jk}^2$. Triangularity gives $\vert C\vert =\prod_j C_{jj}$, and $\vert V_i\vert =\vert C\vert ^2$ then gives $\log\vert V_i\vert =2\sum_j\log C_{jj}$.

To see where this enters the bound, consider a constructed example with two normal measurements for one person. The loading matrix is $\Lambda$, the intercepts are zero, and the residual covariance matrix is $D=\operatorname{diag}(0.4,0.7)$. These diagonal entries are the residual variances. For loading row $\lambda_j^\top$, the expected squared residual is $(y_j-\lambda_j^\top m)^2+\lambda_j^\top V\lambda_j$, where $m,V$ are the trial moments. For $d$ factors, the divergence from $N(m,V)$ to the standard normal distribution is $\lbrace \operatorname{tr}V+m^\top m-d-\log\vert V\vert \rbrace /2$; normal_kl() in code/lib/mixed_factor.R evaluates it from the lower Cholesky factor $C$ of $V$.

1
2
3
4
normal_kl <- function(m, C) {
  # C is the lower-triangular Cholesky factor of V = C C', so tr(V) is the sum of its squared entries.
  (sum(C^2) + sum(m^2) - length(m) - 2*sum(log(diag(C))))/2
}

Here $\operatorname{tr}V$ is the sum of the squared entries of $C$ and $\log\vert V\vert $ is twice the sum of the logs of its diagonal. From the book directory, load the divergence function and define normal_bound() for the two recorded values.

1
2
3
4
5
6
7
8
9
source("code/lib/mixed_factor.R")
loadings <- matrix(c(1,.3,.2,.8),2,byrow=TRUE)
residual <- c(.4,.7)
y <- c(1,-.5)
normal_bound <- function(m,V) {
  expected <- dnorm(y,drop(loadings%*%m),sqrt(residual),log=TRUE) -
    diag(loadings%*%V%*%t(loadings))/(2*residual)
  sum(expected)-normal_kl(m,t(chol(V)))
}

The call to dnorm() evaluates each measurement’s log density using the trial mean of its linear predictor and the residual standard deviation. The diagonal of $\Lambda V\Lambda^\top$ supplies the variances of the linear predictors. For example, at $V=I_2$ the first variance is $1^2+0.3^2=1.09$, so averaging over the factors reduces that log term by $1.09/(2\times0.4)$. The final line subtracts the divergence once for the person after adding the two expected log densities. t(chol(V)) gives normal_kl() the lower triangular Cholesky factor it requires. The supplied function normal_kl() adds sum(C^2) and sum(m^2), subtracts length(m) and 2*sum(log(diag(C))), and halves the result.

At fixed $\theta$, varying $m_i$ or $V_i$ can change the bound for person $i$ while leaving that person’s marginal likelihood fixed. Maximizing the bound over those variational parameters therefore minimizes the divergence from $q_i$ to that person’s conditional distribution. The equivalence between maximizing the bound and minimizing the conditional-distribution divergence concerns $\mathcal L_i$ with its response expectations evaluated exactly. Section 11.5 introduces additional bounds on some expectations; maximizing that further bound need not minimize the KL divergence to the original conditional factor density.

The loadings, response intercepts and residual variances play a different role. They belong to $\theta$ and specify the measurement model shared by the sampled people. For independent people, their bounds add, and the shared model parameters can be estimated by maximizing the sum. The result for a loading is a point estimate. A Bayesian posterior for the loading would require a prior on that parameter. Here the density optimized for each person describes uncertainty about that person’s factors at specified loadings.

In the two-measurement example, the same loadings and residual variances enter both evaluations of the bound below, one at the exact conditional moments and one at the prior moments. For the specified vector $y=(1,-0.5)^\top$, the exact conditional factor distribution can be obtained by completing the square. In the joint normal exponent, twice the negative log density up to a constant is $z^\top z+(y-\Lambda z)^\top D^{-1}(y-\Lambda z)$. Collecting the terms in $z$ gives the conditional precision $P$ and the linear coefficient $b$,

\[\begin{aligned} P&=I_2+\Lambda^\top D^{-1}\Lambda,\qquad b=\Lambda^\top D^{-1}y,\qquad m=P^{-1}b,\\ z^\top Pz-2z^\top b&=(z-m)^\top P(z-m)-m^\top Pm . \end{aligned}\]

Here $m$ and $V=P^{-1}$ are the exact conditional mean and covariance of the factors. Both loading rows contribute a positive term to $P_{12}$. Inverting this two-by-two precision matrix gives $V_{12}=-P_{12}/\vert P\vert <0$, a conditional association that the full trial covariance can represent. The marginal distribution of the two measurements is also normal, with mean zero and covariance $S=\Lambda\Lambda^\top+D$. Its density gives a separate evaluation of the marginal likelihood.

1
2
3
4
5
6
7
8
precision <- diag(2)+crossprod(loadings,loadings/residual)
V <- chol2inv(chol(precision))
m <- drop(V %*% crossprod(loadings,y/residual))
S <- tcrossprod(loadings)+diag(residual)
R <- chol(S)
exact <- -log(2*pi)-sum(log(diag(R)))-sum(forwardsolve(t(R),y)^2)/2
print(c(log_marginal=exact,bound_at_conditional=normal_bound(m,V),
  bound_at_prior=normal_bound(c(0,0),diag(2))))
1
2
        log_marginal bound_at_conditional       bound_at_prior 
           -2.737423            -2.737423            -4.478180 

Dividing the rows of loadings by residual weights each measurement by the reciprocal of its variance. For the upper triangular Cholesky factor R of $S$, sum(log(diag(R))) is half the log determinant, and the squared length of forwardsolve(t(R),y) is the quadratic $y^\top S^{-1}y$.

At the exact conditional mean and covariance, bound_at_conditional agrees with log_marginal at $-2.737423$. At these moments the trial density equals the conditional density everywhere, so the divergence in the gap vanishes. At the prior mean and covariance, the penalty inside the bound vanishes instead, and bound_at_prior is the expected conditional log likelihood, $-4.478180$. The difference $-2.737423-(-4.478180)\approx1.74076$ is the divergence from the prior used as the trial density to the conditional factor density for these two measurements.

The gllvm package implements normal variational approximations for generalized latent variable models.

11.5 Expected response terms in closed form and variational bounds

For the person with two normal measurements, averaging each log density under the trial distribution required only the mean and variance of its linear predictor. How does the spread of that linear predictor enter the log probability of a success, a rating or a count? Fix one person’s observations and the model parameters. Under the trial distribution $q=N(m,V)$ for the factors $Z$, response $j$ has linear predictor $\eta_j=\alpha_j+\lambda_j^\top Z$. Its mean is $\bar\eta_j=\alpha_j+\lambda_j^\top m$. Subtracting this mean gives $\lambda_j^\top(Z-m)$, whose expected square is $\lambda_j^\top V\lambda_j$. The linear predictor therefore has a univariate normal distribution with variance $2c_{Qj}$, where $c_{Qj}=\lambda_j^\top V\lambda_j/2$. This projection suffices for an individual response term because its conditional log density or log probability depends on the factors only through $\eta_j$. All six expectations use the same factor distribution.

To obtain the variances of all six linear predictors, write $V=CC^\top$ with $C$ lower triangular. Row $j$ of $\Lambda C$ is $\lambda_j^\top C$, so its squared length gives $2c_{Qj}$. The function mixed_family_terms() takes one half of this variance as its argument cQ. It is in code/lib/mixed_va.R.

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
86
87
88
89
90
91
92
93
94
95
96
97
98
mixed_family_terms <- function(Y, eta, cQ, family, log_phi, zeta, levels_K = NULL) {
  n <- nrow(Y)
  p <- ncol(Y)
  value <- 0
  d_eta <- matrix(0, n, p)
  d_cQ <- matrix(0, n, p)
  d_phi <- numeric(p)
  d_zeta <- numeric(length(zeta))
  logcosh2 <- function(w) w + log1p(exp(-2 * w))
  ratio <- function(w) ifelse(w > 0, tanh(w) / (4 * w), 1 / 4)
  zeta_at <- 0L
  for (j in seq_len(p)) {
    y <- Y[, j]
    e <- eta[, j]
    c <- cQ[, j]
    fam <- family[j]
    if (fam == "gaussian") {
      s <- exp(log_phi[j])
      s2 <- s * s
      Tm <- y * e - .5 * e * e - c - .5 * y * y
      value <- value + sum(-Tm / s2 + .5 * log(2 * s2) + log(pi) / 2)
      d_eta[, j] <- -(y - e) / s2
      d_cQ[, j] <- 1 / s2
      d_phi[j] <- sum(2 * Tm / s2 + 1)
    } else if (fam == "binomial") {
      w <- .5 * sqrt(e * e + 2 * c)
      value <- value + sum(-(y - .5) * e + logcosh2(w))
      d_eta[, j] <- -(y - .5) + ratio(w) * e
      d_cQ[, j] <- ratio(w)
    } else if (fam == "poisson") {
      m <- exp(e + c)
      value <- value + sum(-y * e + m + lgamma(y + 1))
      d_eta[, j] <- -y + m
      d_cQ[, j] <- m
    } else if (fam == "negative.binomial") {
      g <- log_phi[j]
      s <- exp(g)
      mu <- exp(e)
      mc <- exp(e - c)
      log_mass <- s * log(s / (s + mu)) + lgamma(y + s) - lgamma(s) - lgamma(y + 1) +
        y * log(mu / (s + mu))
      lt1 <- log1p(exp(e - g))
      lt2 <- log1p(exp(e - c - g))
      extra <- (y + s) * (lt1 - lt2) - (y + s) * c
      value <- value + sum(-log_mass - extra)
      d_eta[, j] <- -(s * (y - mu) / (s + mu)) - (y + s) * (mu / (s + mu) - mc / (s + mc))
      d_cQ[, j] <- (y + s) * s / (s + mc)
      d_log_mass_s <- log(s / (s + mu)) + 1 - s / (s + mu) + digamma(y + s) - digamma(s) - y / (s + mu)
      d_extra_g <- s * (lt1 - lt2 - c) + (y + s) * (-mu / (s + mu) + mc / (s + mc))
      d_phi[j] <- sum(-s * d_log_mass_s - d_extra_g)
    } else if (fam == "ordinal") {
      K <- if (is.null(levels_K)) max(y) else levels_K[sum(family[seq_len(j)] == "ordinal")]
      cuts <- c(0, cumsum(exp(zeta[zeta_at + seq_len(K - 2)])))
      lowest <- y == 1
      highest <- y == K
      middle <- !lowest & !highest
      dz <- numeric(K - 2)
      if (any(lowest)) {
        a <- cuts[1] - e[lowest]
        w <- .5 * sqrt(a * a + 2 * c[lowest])
        value <- value + sum(-.5 * a + logcosh2(w))
        d_eta[lowest, j] <- .5 - ratio(w) * a
        d_cQ[lowest, j] <- ratio(w)
      }
      if (any(highest)) {
        a <- cuts[K - 1] - e[highest]
        w <- .5 * sqrt(a * a + 2 * c[highest])
        value <- value + sum(.5 * a + logcosh2(w))
        d_eta[highest, j] <- -.5 - ratio(w) * a
        d_cQ[highest, j] <- ratio(w)
        # d cut_(K-1) / d zeta_k = exp(zeta_k) for every k.
        dz <- dz + sum(.5 + ratio(w) * a) * exp(zeta[zeta_at + seq_len(K - 2)])
      }
      if (any(middle)) {
        k <- y[middle]
        upper <- cuts[k]
        lower <- cuts[k - 1]
        delta <- upper - lower
        a_hi <- upper - e[middle]
        a_lo <- lower - e[middle]
        wu <- .5 * sqrt(a_hi * a_hi + 2 * c[middle])
        wl <- .5 * sqrt(a_lo * a_lo + 2 * c[middle])
        value <- value + sum(-mixed_logsinh(delta / 2) - log(2) + logcosh2(wu) + logcosh2(wl))
        d_eta[middle, j] <- -ratio(wu) * a_hi - ratio(wl) * a_lo
        d_cQ[middle, j] <- ratio(wu) + ratio(wl)
        for (m in seq_len(K - 2)) {
          dup <- as.numeric(k - 1 >= m) * exp(zeta[zeta_at + m])
          dlo <- as.numeric(k - 2 >= m) * exp(zeta[zeta_at + m])
          coth <- 1 / tanh(delta / 2)
          dz[m] <- dz[m] + sum(-.5 * coth * (dup - dlo) + ratio(wu) * a_hi * dup + ratio(wl) * a_lo * dlo)
        }
      }
      d_zeta[zeta_at + seq_len(K - 2)] <- dz
      zeta_at <- zeta_at + K - 2
    } else stop("family not handled: ", fam)
  }
  list(value = value, d_eta = d_eta, d_cQ = d_cQ, d_phi = d_phi, d_zeta = d_zeta)
}

For each response, value adds the expected negative log probability or density under the trial distribution, or an upper bound for it, and the matrices d_eta and d_cQ and the vectors d_phi and d_zeta receive its derivatives with respect to $\bar\eta_{ij}$, $c_{Q,ij}$, the log dispersion and the log cut spacings. For a normal response the expectation is exact. For a Poisson count, $E(e^{\eta})=e^{\bar\eta+c_Q}$, so the term is also exact. For a binary response the negative log probability is $-(y-\tfrac12)\eta+\log\lbrace 2\cosh(\eta/2)\rbrace $. Because $\log\cosh\sqrt x$ is concave in $x$, replacing $\eta^2$ inside the second term by its expectation $\bar\eta^2+2c_Q$ gives an upper bound, which logcosh2(w) evaluates with $w=\tfrac12(\bar\eta^2+2c_Q)^{1/2}$; ratio(w) is the derivative factor $\tanh(w)/(4w)$. The ordinal terms apply the same bound to the two cumulative probabilities that limit each category, and the negative binomial term evaluates the translated program’s expression from $\bar\eta$, $c_Q$ and the size.

For one normal measurement, write $y$ for its recorded value, $\eta$ for its linear predictor and $\sigma^2$ for its residual variance given the factors. Use $\bar\eta$ and $c_Q$ for the mean and half-variance of this response’s linear predictor. In the conditional log density, only the squared residual depends on $\eta$. Writing $y-\eta=(y-\bar\eta)-(\eta-\bar\eta)$ makes the cross product vanish in expectation. The result is

\[E_q\log p(y\mid\eta) =-\tfrac12\log(2\pi\sigma^2) -\frac{(y-\bar\eta)^2+2c_Q}{2\sigma^2}.\]

Evaluating the log density at $\bar\eta$ accounts for the distance between the measurement and the trial mean of its linear predictor. Averaging over the linear predictor reduces that value by $c_Q/\sigma^2$. The denominator uses the residual variance on the measurement scale, while $2c_Q$ in the numerator measures uncertainty about the mean. For both measurements in the mixed model, the residual variance is one, so each reduction equals the half-variance of the corresponding linear predictor.

For a Poisson count, the conditional log probability is $y\eta-e^\eta-\log(y!)$. Its first term has expectation $y\bar\eta$. To average the conditional mean $e^\eta$, write $\eta=\bar\eta+\sqrt{2c_Q}\,U$ with $U$ standard normal. Completing the square in the standard normal density times $e^{tU}$ gives $E(e^{tU})=e^{t^2/2}$. Setting $t=\sqrt{2c_Q}$ yields

\[E_q\log p(y\mid\eta)=y\bar\eta-e^{\bar\eta+c_Q}-\log(y!).\]

The term lgamma(y + 1) in the calculation is the log factorial. When the recorded count is zero, the expected log probability is just $-e^{\bar\eta+c_Q}$. The normal exponential moment makes this expectation exact even though the conditional mean is nonlinear.

For a Bernoulli observation $y$, the part of the log probability that still needs averaging is a log normalizer. The identity $1+e^x=e^{x/2}\,2\cosh(x/2)$ puts the conditional log probability in the form $(y-\tfrac12)x-\log(2\cosh(x/2))$. Let $X$ have mean $a$ and variance $2c_Q$, and define $h(t)=\log(2\cosh(\sqrt{t}/2))$ for $t\geq0$. This function is concave. To see why, set $u=\sqrt{t}/2$. For $u>0$, $h^{\prime}(t)=\tanh(u)/(8u)$. The ratio $\tanh(u)/u$ is the average of the decreasing function $1/\cosh^2(v)$ over $0\leq v\leq u$, so the derivative decreases from its limit at zero. Jensen’s inequality gives $E_q h(X^2)\leq h(a^2+2c_Q)$. Write $H(a,c_Q)=h(a^2+2c_Q)$.

For a Bernoulli response, $X=\eta$ and $a=\bar\eta$. The minus sign on the normalizer makes $(y-\tfrac12)\bar\eta-H(\bar\eta,c_Q)$ a lower bound on the expected Bernoulli log probability.

For an ordinal response with logistic cumulative probabilities, take $X=k-\eta$ at a cutpoint $k$, so $a=k-\bar\eta$. For the lowest category, the bound is $a/2-H(a,c_Q)$ at the first cut. For the highest, it is $-a/2-H(a,c_Q)$ at the last cut. For a category other than the lowest or highest, between consecutive finite cutpoints $k_L<k_U$, subtracting the two logistic cumulative probabilities gives a numerator $2\sinh((k_U-k_L)/2)$ over the product of $2\cosh((k_U-\eta)/2)$ and $2\cosh((k_L-\eta)/2)$. Thus the expected log probability is bounded below by

\[\log\!\left(2\sinh((k_U-k_L)/2)\right)-H(k_U-\bar\eta,c_Q)-H(k_L-\bar\eta,c_Q).\]

For fixed model parameters, the positive spacing between cutpoints is constant as the factor varies, so the inequality is applied only to the two log-cosh terms. The spacing is estimated when the model parameters are varied.

For a negative binomial count of size $r>0$ and conditional mean $e^\eta$, the nonlinear log term is $-(y+r)\log(r+e^\eta)$. Factoring out $e^\eta$ inside the logarithm and applying concavity of the logarithm gives

\[E_q\log(r+e^\eta) =\bar\eta+E_q\log(1+r e^{-\eta}) \leq\bar\eta+\log(1+r e^{-\bar\eta+c_Q}).\]

Here $E_q e^{-\eta}=e^{-\bar\eta+c_Q}$ follows from the same normal moment used for the Poisson count. The negative coefficient $-(y+r)$ turns this upper bound into a lower bound on the expected log probability. Put $\mu=e^{\bar\eta}$. Here $e^{\bar\eta}$ is the conditional mean at the mean linear predictor. The mean count averaged over $q$ is $e^{\bar\eta+c_Q}$, which is a different quantity when $c_Q>0$. The upper bound on the log normalizer is $\log r+c_Q+\log(1+\mu e^{-c_Q}/r)$, while at the mean of the linear predictor the normalizer is $\log r+\log(1+\mu/r)$. The linear term $y\eta$ averages to $y\bar\eta$. Starting with the negative binomial log probability at $\mu$, the adjustment is therefore

\[(y+r)\left\{\log(1+\mu/r)-\log(1+\mu e^{-c_Q}/r)-c_Q\right\}.\]

There is an important limit to this negative binomial bound. Fix $\bar\eta$, $y$ and $c_Q>0$ and let $r\to\infty$. The log probability at $\mu$ has a finite Poisson limit, but the adjustment contains $-(y+r)c_Q$ while its remaining terms have finite limits. The bound therefore tends to $-\infty$, although the exact expected log probability tends to its finite Poisson value. This further approximation does not preserve the Poisson limit at fixed positive predictor variance.

The six expected terms for the first person

For the first person in MIXED6, how close is each calculated term to the expected log density or log probability? From the book directory, readRDS() loads the observed matrix, and mixed6_model() gives the intercepts, loadings and response distributions used to generate it. Set the trial mean to $(0.3,-0.2)^\top$ and the covariance to $V$ with diagonal entries $0.7,0.5$ and off-diagonal entry $0.2$.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
source("code/lib/stability.R")
source("code/lib/differentiation.R")
source("code/lib/glmm.R")
source("code/lib/integration.R")
source("code/lib/mixed_factor.R")
source("code/lib/mixed_va.R")
model2 <- mixed6_model()
Y2 <- readRDS("data/source/ch11/MIXED6.rds")
gfam <- mixed_va_families(model2$family)
yg <- mixed_va_prepare(Y2,gfam)[1,]
vm <- c(.3,-.2)
vC <- t(chol(matrix(c(.7,.2,.2,.5),2)))
person_eta <- model2$intercept+drop(model2$loading%*%vm)
person_cQ <- rowSums((model2$loading%*%vC)^2)/2

The product with vC, the lower Cholesky factor, gives the variance of each linear predictor by the squared row length calculation. For example, the first loading row is $(0.8,0)$, so the variance of its linear predictor is $0.8^2(0.7)=0.448$. The call to mixed_va_families() translates the family names and mixed_va_prepare() changes the ordinal codes to start at one. Both are in code/lib/mixed_va.R.

1
2
3
4
5
6
7
mixed_va_families <- function(families) {
  map <- c(normal = "gaussian", Bernoulli = "binomial", ordinal = "ordinal",
    Poisson = "poisson", NB = "negative.binomial")
  out <- unname(map[families])
  stopifnot(!anyNA(out))
  out
}
1
2
3
4
5
6
mixed_va_prepare <- function(Y, family) {
  Y <- as.matrix(Y)
  ordinal <- family == "ordinal"
  if (any(ordinal) && min(Y[, ordinal]) == 0) Y[, ordinal] <- Y[, ordinal] + 1
  Y
}

The new names are those of the translated lower-bound code; an ordinal column is shifted only when its smallest code is zero. The first person’s rating has code zero in the data and one in yg. Both denote the lowest category.

The ordinal calculation fixes its first cut at zero. Subtracting the original first cut $-0.7$ from both cuts and from the linear predictor shifts the cuts to $0,1.4$ and the mean of the linear predictor from $-0.11$ to $0.59$. The first cut minus the mean is $-0.59$ in either representation. The trial moments in this comparison come from vm and vC.

The function mixed_va_layout() identifies integer positions in the optimization vector. Its fields index and phi_columns identify parameter positions and response columns. At the corresponding positions, mixed_va_coordinates() stores the normal residual standard deviations, the negative binomial size and the ordinal cut spacing on the log scale. For column j, column_terms() evaluates the formula for that observation using the model parameters in these coordinates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mixed_va_layout <- function(Y, family, q, diagonal, levels_K = NULL) {
  n <- nrow(Y)
  p <- ncol(Y)
  phi_columns <- which(family %in% c("gaussian", "negative.binomial"))
  ordinal_columns <- which(family == "ordinal")
  # Ordinal responses are coded 1, ..., K inside the lower-bound calculation; K is the largest code unless given.
  if (is.null(levels_K)) levels_K <- vapply(ordinal_columns, function(j) max(Y[, j]), 0)
  n_zeta <- sum(levels_K - 2)
  n_lambda <- p * q - q * (q + 1) / 2
  n_off <- if (diagonal) 0 else n * q * (q - 1) / 2
  sizes <- c(b = p, lv_scale = q, lambda = n_lambda, u = n * q, log_phi = length(phi_columns),
    var_chol = n * q + n_off, zeta = n_zeta)
  ends <- cumsum(sizes)
  index <- Map(function(e, s) if (s > 0) (e - s + 1):e else integer(0), ends, sizes)
  names(index) <- names(sizes)
  list(n = n, p = p, q = q, family = family, phi_columns = phi_columns,
    ordinal_columns = ordinal_columns, levels_K = levels_K, diagonal = diagonal,
    index = index, length = sum(sizes))
}

For $n$ people, $p$ responses and $q$ factors, the vector contains in order: the $p$ intercepts b, the $q$ factor scales lv_scale, the $pq-q(q+1)/2$ free entries lambda of a loading matrix $\theta$ with ones on its diagonal and zeros above it, the $nq$ variational means u, one log dispersion log_phi for each normal or negative binomial response, the variational covariance factors var_chol ($nq$ log diagonal entries, followed by the off-diagonal entries unless diagonal is true), and the log spacings zeta of the cuts, $K-2$ for an ordinal response with $K$ categories. The list index gives the positions of each group.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
mixed_va_coordinates <- function(model, layout) {
  L <- layout
  q <- L$q
  par <- numeric(L$length)
  sigma <- diag(model$loading[1:q, 1:q, drop = FALSE])
  theta <- sweep(model$loading[, 1:q, drop = FALSE], 2, sigma, "/")
  par[L$index$b] <- model$intercept
  par[L$index$lv_scale] <- sigma
  par[L$index$lambda] <- theta[lower.tri(theta)]
  lg <- ifelse(L$family == "gaussian", log(model$sd), log(model$size))
  par[L$index$log_phi] <- lg[L$phi_columns]
  par[L$index$var_chol][seq_len(L$n * q)] <- log(0.3)
  for (j in L$ordinal_columns) {
    par[L$index$b][j] <- model$intercept[j] - model$cuts[1]
    par[L$index$zeta] <- log(diff(model$cuts))
  }
  par
}

Here the factor scales $\sigma$ are the diagonal entries of the first $q$ rows of the loading matrix, and dividing each loading column by its scale gives $\theta$. Each variational log standard deviation starts at $\log0.3$. For an ordinal response the stored intercept is the intercept minus the first cut, which moves that cut to zero, and zeta contains the logs of the differences between successive cuts.

For comparison, normal_rule(31L) supplies standard normal nodes and probability weights. At each node the code evaluates mixed_response() at the original mean of the linear predictor plus its standard deviation times the node. The weighted sum averages the conditional log density or log probability itself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
layout2 <- mixed_va_layout(mixed_va_prepare(Y2,gfam),gfam,2L,TRUE)
truth_va <- mixed_va_coordinates(model2,layout2)
log_phi2 <- numeric(6)
log_phi2[layout2$phi_columns] <- truth_va[layout2$index$log_phi]
eta_g <- person_eta
eta_g[4] <- truth_va[layout2$index$b][4]+sum(model2$loading[4,]*vm)
column_terms <- function(j,eta,cQ) mixed_family_terms(matrix(yg[j],1),
  matrix(eta,1),matrix(cQ,1),gfam[j],
  log_phi2[j],if (gfam[j]=="ordinal") truth_va[layout2$index$zeta] else numeric(0),
  layout2$levels_K)
rule31 <- normal_rule(31L)
expected <- do.call(rbind,lapply(seq_len(6),function(j) {
  bound <- -column_terms(j,eta_g[j],person_cQ[j])$value
  quadrature_mean <- sum(rule31$weights*mixed_response(Y2[1,j],
    person_eta[j]+sqrt(2*person_cQ[j])*rule31$nodes,model2,j)$log_density)
  data.frame(response=j,family=model2$family[j],mean=person_eta[j],
    variance=2*person_cQ[j],
    variational_term=bound,quadrature_log_term_31=quadrature_mean,
    gap=quadrature_mean-bound)
}))
print(expected)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  response    family  mean variance variational_term quadrature_log_term_31
1        1    normal  0.24    0.448       -1.6551297             -1.6551297
2        2    normal  0.40    0.412       -2.8917423             -2.8917423
3        3 Bernoulli -0.13    0.419       -0.8116729             -0.8100224
4        4   ordinal -0.11    0.280       -1.0646871             -1.0623621
5        5   Poisson  0.32    0.369       -1.6561572             -1.6561572
6        6        NB -0.13    0.315       -1.3175160             -0.8873975
            gap
1 -8.881784e-16
2  4.440892e-16
3  1.650537e-03
4  2.324959e-03
5 -6.661338e-16
6  4.301185e-01

The mean column uses the original means of the linear predictors, which range from $-0.13$ to $0.40$. The variance column gives the full variances, from $0.280$ to $0.448$. The two measurement terms in variational_term agree with quadrature_log_term_31 at $-1.65513$ and $-2.89174$, and the Poisson row reproduces $-1.65616$. For the success, the bound of $-0.81167$ is about $0.00165$ below the quadrature value of $-0.81002$. The lowest rating has a gap of about $0.00232$. For the negative binomial zero, subtracting its bound of $-1.31752$ from the quadrature value of $-0.88740$ gives about $0.43012$. Both recorded counts are zero. For the Poisson zero the exponential moment accounts for all the variation of the linear predictor. For the negative binomial zero the logarithm of $r+e^\eta$ still has to be averaged, even at $y=0$.

For the first person’s Poisson zero, the mean of the linear predictor is $0.32$ and its variance is $0.369$. At the mean alone the log probability is $-e^{0.32}\approx-1.37713$. Including the variance gives $-e^{0.32+0.369/2}\approx-1.65616$. The normal exponential moment accounts for the difference between evaluating at the mean and averaging over the trial distribution.

For this person and these trial moments, the two normal rows and the Poisson row have printed gaps within $10^{-15}$ of zero. The formulas give the exact expectations for those three responses, and numerical integration and rounding account for the tiny signed differences. For the other three expectations, the 31-node rule supplies the numerical reference. The inequalities establish the direction of their bounds, while the table estimates how much each bound reduces the sum. Of the total reduction of about $0.43409$, the negative binomial zero accounts for $0.4301185$. The divergence from the trial distribution to the factor prior is the same whichever response terms enter the sum. Subtracting it from the sum of the exact and bounded terms therefore gives a computable lower bound on $\mathcal L$, the lower bound on the marginal log likelihood derived in Section 11.4. Write $b_j$ for the term used for response $j$, $\ell_j$ for its conditional log density or log probability, and $\widetilde{\mathcal L}$ for the resulting bound for this person. For response vector $y$ and model parameters $\theta$, the two sources of the gap to the marginal log likelihood are

\[\log L(\theta)-\widetilde{\mathcal L} =\operatorname{KL}\!\left(q\,\|\,p(\cdot\mid y,\theta)\right) +\sum_{j=1}^{6}\left(E_q\ell_j-b_j\right).\]

The printed gaps approximate the terms in this sum. With six Poisson responses, that sum vanishes for every choice of the normal trial distribution. With mixed responses, joint estimation maximizes the sum of the computable bounds over people, varying both the shared model parameters and each person’s trial moments. The individual gap values compare an expected response log term with its further bound. They are not each a KL divergence between the factor distributions. The 31-node calculations are numerical approximations to those expectations.

Implementation and derivative checks

The formulas above are implemented in the sourced mixed_family_terms() function. For a normal response, Tm stores minus half the expected squared residual. For a Bernoulli response, w is half the square root of the second moment and logcosh2(w) evaluates $H(a,c_Q)$. For a negative binomial response, log_mass is the log probability at $\mu$ and extra is the adjustment derived above. Their sum bounds the expected log probability. The function accumulates negative response terms in value so that the criterion can be minimized.

The derivative comparisons use the same three observations that required inequalities. For each call to column_terms(), the first coordinate is the mean of the linear predictor used by the variational formula and the second is its half-variance. The pairs are $(-0.13,0.2095)$ for the success, $(0.59,0.140)$ for the rating and $(-0.13,0.1575)$ for the negative binomial zero. The comparison changes one coordinate at a time with the response and the other coordinate fixed. The fields d_eta and d_cQ differentiate value, the negative of the term in variational_term. The function num_grad() (Section 3.1) estimates those same partial derivatives.

1
2
3
4
5
6
7
for (j in c(3L,4L,6L)) {
  t0 <- column_terms(j,eta_g[j],person_cQ[j])
  print(data.frame(response=j,coordinate=c("mean","half variance"),
    formula_derivative=c(t0$d_eta,t0$d_cQ),
    numerical_derivative=num_grad(function(x) column_terms(j,x[1],x[2])$value,
      c(eta_g[j],person_cQ[j]))$gradient))
}
1
2
3
4
5
6
7
8
9
  response    coordinate formula_derivative numerical_derivative
1        3          mean         -0.5313687           -0.5313687
2        3 half variance          0.2412979            0.2412979
  response    coordinate formula_derivative numerical_derivative
1        4          mean          0.6402355            0.6402355
2        4 half variance          0.2376874            0.2376874
  response    coordinate formula_derivative numerical_derivative
1        6          mean          0.6316758            0.6316758
2        6 half variance          3.3683242            3.3683242

For the success, the formula and central-difference calculations both give $-0.5313687$ for the mean and $0.2412979$ for the half-variance. Raising the mean locally increases the bound for a success, which explains the negative sign for the derivative of value. For the lowest rating, the corresponding derivatives are $0.6402355$ and $0.2376874$ in both columns. A higher linear predictor shifts probability toward higher categories. For the negative binomial zero, the two calculations give $0.6316758$ and $3.3683242$. In particular, the latter number measures change per unit of half-variance. Differentiating with respect to the full variance would divide it by two.

The ordinal probabilities and parts of the lower-bound derivatives of the supplied variational code follow the gllvm package (code/NOTICE.md), which provides this variational method for mixed responses.

11.6 Joint estimation and the covariance of the approximating factor distribution

With six Poisson counts per site, every expected log probability can be evaluated exactly under a normal trial distribution. Which quantities can change when the sum of the sites’ variational bounds is maximized? An intercept or a loading belongs to a species and can change its contribution at all sites. The trial mean and covariance of the two factors belong to a single site. Changing them affects that site’s contribution alone.

For a sample of $n$ independent sites, write $m_i$ for the two trial means at site $i$ and $A_i$ for the lower triangular Cholesky factor of its trial covariance on the standardized factor scale. A positive diagonal makes $A_iA_i^\top$ positive definite. An unrestricted two-factor covariance takes three parameters. Together with the two means, this gives five free quantities for one site. A diagonal restriction on this covariance concerns uncertainty about the two factors at a site. Both factors can still induce associations between species counts. An unrestricted covariance here means any positive definite two-by-two covariance. It does not mean that population factors have an estimated covariance: their distribution remains $N_2(0,I_2)$.

To express how the model parameters and trial moments enter each response term, use $\theta$ for the loading matrix with ones on the diagonal of its leading two rows and zeros above that diagonal. Let $\Delta=\operatorname{diag}(\vert \sigma_1\vert ,\vert \sigma_2\vert )$ contain the two factor scales. The matrix of loadings on the standardized factors is $\Lambda=\theta\Delta$. Under the trial distribution, the standardized factors in row $i$ have mean $m_i$ and covariance $A_iA_i^\top$. Multiplying the factors by $\Delta$ gives mean $\Delta m_i$ and covariance $S_i=\Delta A_iA_i^\top\Delta$. Write $\theta_j^\top$ and $\lambda_j^\top$ for row $j$ of $\theta$ and $\Lambda$. In this section $\theta$ denotes this loading matrix, whereas in Section 11.4 it denoted the collection of model parameters. The scale $\vert \sigma_d\vert $ is the diagonal loading on standardized factor $d$. With intercept $\alpha_j$ for species $j$, the mean and half-variance of the linear predictor can be written as

\[\bar\eta_{ij}=\alpha_j+\lambda_j^\top m_i,\qquad c_{Q,ij}=\tfrac12\theta_j^\top S_i\theta_j =\tfrac12\lambda_j^\top A_iA_i^\top\lambda_j.\]

Why does a change in a trial mean involve a sum over species, while a change in an intercept involves a sum over sites? The function mixed_va_objective() adds the negative response terms from mixed_family_terms() to the divergences from the trial distributions to the standard normal prior. Denote that sum by $J$. For a Poisson count $y_{ij}$, the derivative of the negative response term with respect to $\bar\eta_{ij}$ is $d_{\eta,ij}=e^{\bar\eta_{ij}+c_{Q,ij}}-y_{ij}$. The half-variance is independent of $m_i$ and $\alpha_j$. Differentiating the mean therefore gives

\[\nabla_{m_i}J=m_i+\sum_j\lambda_j\,d_{\eta,ij},\qquad \frac{\partial J}{\partial\alpha_j}=\sum_i d_{\eta,ij}.\]

The first summand $m_i$ comes from the squared mean $m_i^\top m_i/2$ in the normal divergence.

The three parts below form mixed_va_objective() in code/lib/mixed_va.R.

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
mixed_va_objective <- function(par, Y, layout, gradient = FALSE) {
  L <- layout
  n <- L$n; p <- L$p; q <- L$q
  b <- par[L$index$b]
  sig_raw <- par[L$index$lv_scale]
  sig <- abs(sig_raw)
  theta <- mixed_va_theta(par[L$index$lambda], p, q)
  u <- matrix(par[L$index$u], n, q)
  var_chol <- par[L$index$var_chol]
  # A_i entries as n-vectors: A[[r]][[c]] for r >= c.
  A <- vector("list", q)
  for (r in seq_len(q)) A[[r]] <- vector("list", q)
  for (d in seq_len(q)) A[[d]][[d]] <- exp(var_chol[(d - 1) * n + seq_len(n)])
  k <- 0L
  if (q > 1) for (c in 1:(q - 1)) for (r in (c + 1):q) {
    A[[r]][[c]] <- if (L$diagonal) numeric(n) else var_chol[n * q + k * n + seq_len(n)]
    k <- k + 1L
  }
  entry <- function(r, c) if (r >= c) A[[r]][[c]] else numeric(n)
  # Kullback-Leibler part.
  log_diag <- 0
  frob <- numeric(n)
  for (r in seq_len(q)) for (c in seq_len(r)) frob <- frob + entry(r, c)^2
  for (d in seq_len(q)) log_diag <- log_diag + sum(log(A[[d]][[d]]))
  value <- -(log_diag - .5 * (sum(frob) + sum(u * u))) - .5 * n * q

The first part reads the intercepts $\alpha_j$ from b, the factor scales $\vert \sigma_d\vert $ from sig, $\theta$ from lambda and the trial means $m_i$ from the rows of u. Entry $(r,c)$ of $A_i$ is stored for all people at once in the vector A[[r]][[c]]; the diagonal entries are the exponentials of the stored log values. The divergence of each trial distribution from $N_q(0,I_q)$ is $\lbrace \operatorname{tr}(A_iA_i^\top)+m_i^\top m_i-q\rbrace /2-\log\vert A_i\vert $, and value is its sum over people: frob adds the squared entries of each $A_i$ and log_diag the logs of their diagonals.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  # M_i = Delta A_i, S_i = M_i M_i'.
  M <- function(r, c) sig[r] * entry(r, c)
  S <- matrix(list(), q, q)
  for (r in seq_len(q)) for (s in seq_len(q)) {
    total <- numeric(n)
    for (k2 in seq_len(q)) total <- total + M(r, k2) * M(s, k2)
    S[[r, s]] <- total
  }
  us <- sweep(u, 2, sig, "*")
  eta <- matrix(b, n, p, byrow = TRUE) + us %*% t(theta)
  cQ <- matrix(0, n, p)
  for (j in seq_len(p)) {
    total <- numeric(n)
    for (r in seq_len(q)) for (s in seq_len(q)) total <- total + theta[j, r] * S[[r, s]] * theta[j, s]
    cQ[, j] <- .5 * total
  }
  log_phi <- numeric(p)
  log_phi[L$phi_columns] <- par[L$index$log_phi]
  terms <- mixed_family_terms(Y, eta, cQ, L$family, log_phi, par[L$index$zeta], L$levels_K)
  value <- value + terms$value
  d_eta <- terms$d_eta
  d_cQ <- terms$d_cQ
  d_phi <- terms$d_phi
  d_zeta <- terms$d_zeta

The second part forms $S_i=\Delta A_iA_i^\top\Delta$ entry by entry in S, the means $\bar\eta_{ij}$ in eta from $\Delta m_i$ (us), and the half-variances $c_{Q,ij}=\theta_j^\top S_i\theta_j/2$ in cQ. The function mixed_family_terms() (Section 11.5) returns the sum of the negative response terms for these moments and their derivatives with respect to $\bar\eta_{ij}$, $c_{Q,ij}$, the log dispersions and the cut spacings; adding the sum to the divergences gives $J$.

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
  if (!gradient) return(value)
  g <- numeric(L$length)
  g[L$index$b] <- colSums(d_eta)
  # eta = b + (u Delta) theta'.
  g_us <- d_eta %*% theta
  g_theta <- crossprod(d_eta, us)
  g_u_eta <- sweep(g_us, 2, sig, "*")
  g_sig <- colSums(g_us * u)
  # cQ_ij = theta_j' S_i theta_j / 2: d/d theta_j = S_i theta_j; d/d S_i[r, s] = theta_jr theta_js / 2.
  G_S <- matrix(list(), q, q)
  for (r in seq_len(q)) for (s in seq_len(q)) G_S[[r, s]] <- .5 * drop(d_cQ %*% (theta[, r] * theta[, s]))
  for (j in seq_len(p)) for (r in seq_len(q)) {
    total <- 0
    for (s in seq_len(q)) total <- total + sum(d_cQ[, j] * S[[r, s]]) * theta[j, s]
    g_theta[j, r] <- g_theta[j, r] + total
  }
  # S = M M': dS/dM gives G_M = (G_S + G_S') M.
  G_M <- matrix(list(), q, q)
  for (r in seq_len(q)) for (k2 in seq_len(q)) {
    total <- numeric(n)
    for (s in seq_len(q)) total <- total + (G_S[[r, s]] + G_S[[s, r]]) * M(s, k2)
    G_M[[r, k2]] <- total
  }
  # M = Delta A.
  g_A <- matrix(list(), q, q)
  for (r in seq_len(q)) for (c in seq_len(r)) {
    g_A[[r, c]] <- sig[r] * G_M[[r, c]] + entry(r, c)
    g_sig[r] <- g_sig[r] + sum(G_M[[r, c]] * entry(r, c))
  }
  g[L$index$lv_scale] <- g_sig * ifelse(sig_raw < 0, -1, 1)
  free <- lower.tri(theta)
  g[L$index$lambda] <- g_theta[free]
  g[L$index$u] <- as.vector(g_u_eta + u)
  g[L$index$log_phi] <- d_phi[L$phi_columns]
  gA <- numeric(length(var_chol))
  for (d in seq_len(q)) gA[(d - 1) * n + seq_len(n)] <- g_A[[d, d]] * A[[d]][[d]] - 1
  if (!L$diagonal && q > 1) {
    k <- 0L
    for (c in 1:(q - 1)) for (r in (c + 1):q) {
      gA[n * q + k * n + seq_len(n)] <- g_A[[r, c]]
      k <- k + 1L
    }
  }
  g[L$index$var_chol] <- gA
  g[L$index$zeta] <- d_zeta
  list(value = value, gradient = g)
}

The third part applies the chain rule. The intercept derivatives are the column sums of d_eta, $\sum_id_{\eta,ij}$, and the derivative for $m_i$ is g_u_eta + u, $\Delta\theta^\top d_{\eta,i}+m_i$, the gradient displayed above. A change in $\theta_j$ changes $\bar\eta_{ij}$ and $c_{Q,ij}$, so g_theta adds both contributions. The derivatives for $S_i$ pass to $M_i=\Delta A_i$ through $S_i=M_iM_i^\top$ and then to $A_i$ and the scales; the divergence adds $A_i$ itself, and a diagonal entry stored as a logarithm multiplies its derivative by the entry and subtracts the one contributed by $-\log\vert A_i\vert $. A negative stored scale reverses the sign of its derivative because the model uses its absolute value.

Diagonal and unrestricted fits to the Poisson counts

A comparison of diagonal and unrestricted trial covariances uses the simulated Poisson matrix of 400 sites and six species. From the book directory, load the optimization and model functions and read the Poisson counts.

1
2
3
4
5
6
7
source("code/lib/result.R")
source("code/lib/quasi_newton.R")
source("code/lib/mixed_factor.R")
source("code/lib/mixed_va.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
Yc <- readRDS("data/source/ch11/counts-Poisson.rds")
cfam <- rep("poisson",6L)

The sourced file code/lib/mixed_va.R supplies the layout, starting-value and objective functions used by mixed_va_fit() below. The fitting function uses BFGS to minimize $J$ jointly over all free model and variational parameters in a stage. BFGS denotes the Broyden-Fletcher-Goldfarb-Shanno quasi-Newton method. Each run starts with its own approximation to the inverse Hessian, uses relative tolerance $10^{-10}$ and allows at most 6,000 iterations. The comparison uses two routes: a complete diagonal-covariance fit followed by an unrestricted fit, and an unrestricted fit from the initial values.

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
mixed_va_fit <- function(Y, family, q, start = NULL, rel_tol = 1e-10, maxit = 6000L,
                         structure = c("unstructured", "diagonal"), diag_iter = 1L,
                         starting_val = c("res", "zero")) {
  structure <- match.arg(structure)
  if (is.null(start)) start <- mixed_va_start(Y, family, q,
      starting_val = match.arg(starting_val))
  Y <- start$Y
  run <- function(par, layout) {
    last <- NULL
    current <- NULL
    evaluate <- function(x) {
      if (!identical(x, last)) {
        current <<- mixed_va_objective(x, Y, layout, TRUE)
        last <<- x
      }
      current
    }
    fit <- bfgs(function(x) evaluate(x)$value, function(x) evaluate(x)$gradient, par,
      list(rel_tol = rel_tol, maxit = maxit))
    fit$layout <- layout
    fit
  }
  # Copy shared parameters and means, then insert the supplied Cholesky coordinates.
  relayout <- function(par, from, to, var_chol) {
    out <- numeric(to$length)
    for (nm in setdiff(names(from$index), "var_chol")) out[to$index[[nm]]] <-
      par[from$index[[nm]]]
    out[to$index$var_chol] <- var_chol
    out
  }
  L0 <- mixed_va_layout(Y, family, q, TRUE)
  first_diagonal <- structure == "diagonal" || diag_iter > 0 || q == 1
  L1 <- mixed_va_layout(Y, family, q, first_diagonal)
  par1 <- if (first_diagonal) start$par else
    relayout(start$par, L0, L1, c(start$par[L0$index$var_chol],
      rep(0, L1$n * q * (q - 1) / 2)))
  first <- run(par1, L1)
  stages <- list(first)
  names(stages) <- if (first_diagonal) "diagonal" else "unstructured"
  final <- first
  if (structure == "unstructured" && diag_iter > 0 && q > 1) {
    L2 <- mixed_va_layout(Y, family, q, FALSE)
    par2 <- relayout(first$par, L1, L2, c(pmax(first$par[L1$index$var_chol], log(1e-6)),
      rep(0, L2$n * q * (q - 1) / 2)))
    second <- run(par2, L2)
    stages$unstructured <- second
    if (is.finite(second$value) && all(is.finite(second$par)) &&
        (!is.finite(first$value) || second$value <= first$value)) final <- second
  }
  list(par = final$par, value = final$value, lower_bound = -final$value,
    layout = final$layout,
    Y = Y, family = family, q = q, stages = stages, start = start)
}

Within run(), evaluate() computes the negative bound and its gradient together when the parameter vector changes. A second request at the same vector uses the stored calculation.

The layout objects used by the wrapper describe where each parameter group lies in the optimization vector. In order, mixed_va_layout() places the response intercepts in b, the factor scales in lv_scale, the free loadings below a unit diagonal in lambda, the variational means in u, the response-specific log dispersions in log_phi, the Cholesky coordinates in var_chol and the ordinal log cutpoint increments in zeta. The model loading matrix is recovered by filling $\theta$ with the free loadings and multiplying its columns by the absolute scales to form $\Lambda=\theta\Delta$. Using an absolute value permits zero and gives the same value for either sign of the stored coordinate. At zero the criterion can be nondifferentiable, although the code selects the positive-side derivative. Within u, positions $i$ and $n+i$ give the two means for row $i$.

Within unrestricted var_chol, positions $i,n+i,2n+i$ give the two log diagonals of $A_i$ and its untransformed entry below the diagonal, respectively. The covariance between the two standardized factors under the trial distribution is $A_{i,11}A_{i,21}$. In a diagonal fit, $A_{i,21}=0$. The $n$ off-diagonal Cholesky entries are then absent. The general mixed-response interface also uses a log residual standard deviation in log_phi for a normal response and a log size for a negative binomial response. The all-Poisson model needs neither dispersion parameters nor cutpoints.

The derivative expressions above also explain the calculations inside the sourced mixed_va_objective(). There, d_eta %*% theta sums over responses, and multiplying its columns by the factor scales applies $\Delta$. Adding u gives one gradient row for each site. For the intercept, colSums(d_eta) collects the derivative from every site where that species was counted.

The two covariance layouts differ in the positions reserved for their parameters. In the call that constructs par2, relayout() uses group names to copy the fitted model parameters and the 400 trial mean vectors from the diagonal layout L1 to the unrestricted layout L2. For the Cholesky coordinates, it copies each fitted log diagonal with a floor of $\log(10^{-6})$, then appends one zero per site for the newly free entry. At the start of this second run the covariances are still diagonal. The new parameters allow BFGS to move away from that restriction.

With starting_val="zero", the six intercepts and all trial means start at zero. The two factor scales and the loadings below the unit diagonal start at one. Every site starts with $A_i=0.3I_2$, so its initial standardized covariance is $0.09I_2$. For the first species, the initial loading row $(1,0)$ thus gives its linear predictor a half-variance of $0.045$. At site $i$ its contribution to the intercept derivative is $e^{0.045}-y_{i1}$. All sites share that intercept, and each site contributes its own observed count to the sum.

The first call below uses the default diagonal stage followed by an unrestricted stage. Setting diag_iter=0L in the second call makes the off-diagonal entries free on the first BFGS step, starting them at zero along with the fixed initial means. The seed is set to 1108 before each call. The fixed starting rule assigns its parameter values directly. In this implementation diag_iter decides whether the diagonal stage is used; its positive value is not a count of diagonal-stage iterations. The diagonal stage is itself a complete optimization run.

1
2
3
4
set.seed(1108)
va_counts <- mixed_va_fit(Yc,cfam,2L,starting_val="zero")
set.seed(1108)
va_counts_direct <- mixed_va_fit(Yc,cfam,2L,starting_val="zero",diag_iter=0L)

How many parameters does BFGS estimate at each stage? There are six intercepts and two factor scales. The first loading column has five free entries below its diagonal and the second has four, giving $6+2+9=17$ shared parameters. In the diagonal stage, the two means and two log diagonals contribute $400\times4$ more coordinates. Freeing one off-diagonal entry for each site changes the total from 1,617 to 2,017. The function stage_row() reports the length of the fitted parameter vector alongside its negative bound, the BFGS evaluation counts and the largest absolute component of the final gradient.

1
2
3
4
5
6
7
8
9
stage_row <- function(name,f) data.frame(fit=name,coordinates=length(f$par),
  negative_lower_bound=f$value,
  function_evaluations=f$evaluations[["objective"]],
  gradient_evaluations=f$evaluations[["gradient"]],
  max_abs_gradient_component=max(abs(f$gradient)),converged=f$converged,reason=f$reason)
print(rbind(stage_row("diagonal variational covariance",va_counts$stages$diagonal),
  stage_row("then unrestricted variational covariance",va_counts$stages$unstructured),
  stage_row("unrestricted variational covariance from the start",
    va_counts_direct$stages$unstructured)))
1
2
3
4
5
6
7
8
9
10
11
12
                                                 fit coordinates
1                    diagonal variational covariance        1617
2           then unrestricted variational covariance        2017
3 unrestricted variational covariance from the start        2017
  negative_lower_bound function_evaluations gradient_evaluations
1             3562.095                  294                  109
2             3552.586                  163                   53
3             3552.586                  325                  121
  max_abs_gradient_component converged    reason
1                0.009308805      TRUE converged
2                0.003207786      TRUE converged
3                0.005102955      TRUE converged

The negative bound falls from $3562.095$ to $3552.586$ when the staged fit allows within-site dependence in the trial distribution. This increases the fitted lower bound by about $9.509$ on the same observations. The unrestricted fit from the fixed start reaches $3552.586$ at the same printed precision.

BFGS reports 294 function and 109 gradient evaluations in the diagonal stage, then 163 and 53 in the unrestricted stage. That gives 457 function and 162 gradient evaluations across both stages, compared with 325 and 121 on the direct route. These are counts of optimizer requests. The stored joint calculation can answer both kinds of request, and the gradient call made for the final report is outside the gradient counter. Elapsed time would require a separate measurement.

All three runs report converged. BFGS sets this flag when its progress tests end the run before the iteration limit. The largest absolute gradient components at their returned parameters are about $0.0093$, $0.0032$ and $0.0051$, respectively. The relative tolerance applies to changes in the negative bound. The gradient column reports the largest absolute partial derivative of the negative bound at the returned vector. The fitting function retains the second stage when its coordinates and criterion are finite and its negative bound does not exceed that of the first stage. Both stages are evaluated for the same observations and measurement units.

Loadings from the two unrestricted fits

Do the two unrestricted fits also give similar loadings? The all-Poisson model used to generate the counts supplies a template with the same six species in the same order. Given a fitted parameter vector, mixed_va_model() reconstructs $\theta$, multiplies each column by the corresponding absolute factor scale and stores the result in loading; it reads intercept from b. The returned list has the same response-model fields as the template, without the person-specific variational means and covariances.

1
2
3
4
5
6
7
8
9
10
11
12
mixed_va_theta <- function(lambda, p, q) {
  theta <- matrix(0, p, q)
  k <- 0L
  for (d in seq_len(q)) {
    theta[d, d] <- 1
    if (d < p) for (j in (d + 1):p) {
      k <- k + 1L
      theta[j, d] <- lambda[k]
    }
  }
  theta
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
mixed_va_model <- function(fit, template) {
  L <- fit$layout
  p <- L$p; q <- L$q
  par <- fit$par
  theta <- mixed_va_theta(par[L$index$lambda], p, q)
  model <- template
  model$loading <- sweep(theta, 2, abs(par[L$index$lv_scale]), "*")
  b <- par[L$index$b]
  phi <- rep(NA_real_, p)
  phi[L$phi_columns] <- exp(par[L$index$log_phi])
  model$intercept <- b
  normal <- L$family == "gaussian"
  model$sd[normal] <- phi[normal]
  is_nb <- L$family == "negative.binomial"
  model$size[is_nb] <- phi[is_nb]
  for (k in seq_along(L$ordinal_columns)) {
    j <- L$ordinal_columns[k]
    before <- sum(L$levels_K[seq_len(k - 1L)] - 2)
    zeta <- c(0, cumsum(exp(par[L$index$zeta][before + seq_len(L$levels_K[k] - 2)])))
    model$intercept[j] <- 0
    model$cuts <- zeta - b[j]
  }
  model
}

The function mixed_va_theta() places ones on the diagonal of $\theta$ and fills the entries below it column by column from lambda. In mixed_va_model(), the residual standard deviations and the negative binomial sizes are the exponentials of log_phi. For an ordinal response the cuts are $0$ followed by the cumulative sums of the exponentiated zeta, minus the stored intercept, and the intercept is set to zero, which restores the representation of mixed6_model(). Using the same template for both fits puts every difference on the scale of reported loadings.

1
2
3
4
5
6
count_model <- mixed6_model(families = rep("Poisson", 6L))
fitted_counts <- mixed_va_model(va_counts,count_model)
print(list(loading=fitted_counts$loading,true_loading=count_model$loading,
  intercept=fitted_counts$intercept,
  direct_start_gap=max(abs(mixed_va_model(va_counts_direct,count_model)$loading-
    fitted_counts$loading))))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$loading
          [,1]      [,2]
[1,] 0.8146630 0.0000000
[2,] 0.2661225 0.7855722
[3,] 0.6701586 0.1970707
[4,] 0.1562429 0.7412162
[5,] 0.5791009 0.4005015
[6,] 0.3137858 0.6477928

$true_loading
     [,1] [,2]
[1,]  0.8  0.0
[2,]  0.2  0.8
[3,]  0.7  0.2
[4,]  0.1  0.7
[5,]  0.6  0.3
[6,]  0.3  0.6

$intercept
[1] -0.10486658  0.54202462 -0.39817921 -0.07654929  0.05970990 -0.19748586

$direct_start_gap
[1] 1.540046e-05

For the first species, the staged fit estimates loadings of about $(0.815,0)$ against the generating $(0.8,0)$. The second loading in that row is fixed by the triangular convention. The second species has estimates $(0.266,0.786)$ against $(0.2,0.8)$. Its fitted intercept of about $0.542$ is the log expected count when both factors are zero, compared with a generating intercept of $0.5$. The maximum absolute difference between corresponding loadings from the two fitted routes is $1.540046\times10^{-5}$. Similar bounds can accompany different loading matrices because a rotation of the factors can preserve the linear predictors when the loadings and trial moments rotate together. Here, the direct comparison shows that the two routes also give nearly identical loadings in the chosen orientation.

The same conversion interface also supports mixed responses. For a mixed-response template, exponentiated dispersion coordinates supply the normal sd and negative binomial size. For an ordinal response, the function sets the response intercept to zero and subtracts the fitted intercept from the cutpoints, preserving each cutpoint minus linear predictor. The mixed-response example in this chapter has one ordinal response. Although the parameter arrangement can describe several ordinal columns, the model’s single cuts field is overwritten for each such column. Distinct ordinal responses would require separate cutpoint vectors throughout generation, evaluation and conversion.

The gllvm package provides joint variational estimation for these models.

11.7 Starting values, covariance constraints, and loading identification

On the Poisson counts, both routes from the fixed start gave the same bound to three decimal places. The default starting rule constructs loadings and factor-score estimates from residuals; the fixed rule assigns the scales and free loading entries in advance. Comparing their attained bounds tests sensitivity to these starting values.

In the leading triangular loading block, the diagonal loading $\vert \sigma_d\vert $ fixes the sign and direction of factor $d$ when it is positive. At exactly zero, the positive-diagonal condition cannot select that factor’s sign. Very small positive values can also make this choice numerically unstable. A small diagonal entry alone does not show that the whole loading column, or the factor’s contribution, is small. A BFGS stopping flag records the outcome of its numerical tests; stationarity requires examining derivatives at the returned parameters.

Response fits without common factors

To construct residuals for MIXED6, first fit each response without factors. The following calls read the observed responses and load their model and fitting functions from the book directory. The six columns for each of the 400 people include a rating that mixed_va_prepare() codes from one to $K$, with $K=3$ here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
source("code/lib/result.R")
source("code/lib/stability.R")
source("code/lib/quasi_newton.R")
source("code/lib/logit.R")
source("code/lib/glm.R")
source("code/lib/dogleg.R")
source("code/lib/lbfgsb.R")
source("code/lib/factor.R")
source("code/lib/mixed_factor.R")
source("code/lib/mixed_va.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
model2 <- mixed6_model()
Y2 <- readRDS("data/source/ch11/MIXED6.rds")
gfam <- mixed_va_families(model2$family)

Here null model means the separate response models without common factors. It is a device for obtaining starting values, not a fitted null hypothesis for a test of the number of factors. For the ordinal column, fix the first cut at zero and let the intercept supply its location. The next function fits the response intercepts, dispersions and ordinal cut spacing.

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
mixed_null_fit <- function(Y, family) {
  n <- nrow(Y)
  p <- ncol(Y)
  L <- mixed_va_layout(Y, family, 1L, TRUE)
  zeta0 <- unlist(lapply(L$ordinal_columns, function(j) {
    cut <- proportional_odds_cuts(Y[, j])$cuts
    row <- c(0, cut[-1L] - cut[1L])
    log(diff(row))
  }))
  invisible(runif(p, 0, 0.001))  # Advance the random-number sequence.
  ib <- seq_len(p)
  iphi <- p + seq_along(L$phi_columns)
  izeta <- p + length(L$phi_columns) + seq_along(zeta0)
  terms <- function(par) {
    log_phi <- numeric(p)
    log_phi[L$phi_columns] <- par[iphi]
    mixed_family_terms(Y, matrix(par[ib], n, p, byrow = TRUE), matrix(0, n, p), family,
      log_phi, par[izeta], L$levels_K)
  }
  fit <- dogleg_minimize(c(rep(0, p), rep(0, length(iphi)), zeta0),
    function(par) terms(par)$value,
    function(par) {
      t <- terms(par)
      c(colSums(t$d_eta), t$d_phi[L$phi_columns], t$d_zeta)
    }, control = list(rel_tol = 1e-8, max_iter = 200L, max_evals = 3000L))
  phi <- rep(NA_real_, p)
  phi[L$phi_columns] <- exp(fit$par[iphi])
  is_nb <- family == "negative.binomial"
  phi[is_nb] <- 1 / phi[is_nb]
  # Cut points of each ordinal column: 0 and the cumulated exponentiated increments.
  cuts <- lapply(seq_along(L$ordinal_columns), function(k) {
    K <- L$levels_K[k]
    before <- sum(L$levels_K[seq_len(k - 1L)] - 2)
    c(0, cumsum(exp(fit$par[izeta][before + seq_len(K - 2)])))
  })
  list(b = fit$par[ib], phi = phi, cuts = cuts, zeta_start = zeta0, fit = fit)
}

To start the ordinal cutpoints, proportional_odds_cuts() fits an intercept-only binary logit to the indicator $y>\lfloor K/2\rfloor$. The split puts the 140 lowest ratings in one group and the 260 higher ratings in the other. If the fitted binary intercept is $b$, the cumulative log odds at the split are $-b$. The function takes $\operatorname{logit}(k/K)$ for $k=1,\ldots,K-1$ and shifts all the cuts by the same amount to put the split at $-b$. BFGS then minimizes the negative log likelihood of the observed categories over the first cut and the log gaps. Its cutpoint transformation reconstructs the finite ordered cutpoints from the first cut and log gaps. This calculation uses all three specified categories. The starting function recodes observed values with factor(y); an absent category can therefore change the number and meaning of its cutpoints.

Inside mixed_va_start(), null <- mixed_null_fit(Y, family) uses the recoded observations. The half-variances of the linear predictors are all zero, so mixed_family_terms() evaluates the negative log likelihood at the response intercepts. The double-dogleg optimizer starts at zero intercepts, zero log dispersions and the fitted ordinal log gap. Its analytic gradient sums the derivatives with respect to the intercepts over people and includes the derivatives in the log dispersions and cut increment.

Starting loadings from randomized residuals

To put measurements, ratings and counts on a common residual scale, let $F$ be the fitted cumulative distribution function (CDF) for a column. For a continuous observation $y$, the residual is $\Phi^{-1}(F(y))$, where $\Phi$ is the standard normal cumulative distribution function. For a discrete observation, $F(y^-)$ is the cumulative probability just below $y$. The jump from $F(y^-)$ to $F(y)$ equals the probability of the observed category. With an independent $v$ uniform on $(0,1)$ for each discrete response, the randomized quantile residual is

\[r=\Phi^{-1}\!\left(F(y^-)+v\{F(y)-F(y^-)\}\right).\]

To initialize two factors, use the correlation pattern among the six residual columns. The concentrated likelihood optimizes the loadings for each trial set of unique variances, leaving those variances as the optimization coordinates. A unique variance is the part of a standardized residual’s variance not represented by the common factors. If $R_s$ is the matrix of standardized residuals, $C$ their correlation matrix and $G$ a rotated loading matrix, the regression factor scores are the rows of $R_s C^{-1}G$. They provide a pair of starting scores for each person. These scores are estimates used to initialize the variational means; they are not observed factor values. The function mixed_residual_factors() computes the loadings and scores.

1
2
3
4
5
6
7
8
9
10
11
mixed_residual_factors <- function(R, q) {
  covariance <- cov.wt(R)$cov
  fit <- fa_concentrated(covariance, q)
  load <- fit$loadings
  if (q > 1) load <- rotate_varimax(load)$loadings
  load <- load[, order(-colSums(load^2)), drop = FALSE]  # decreasing sums of squares
  signs <- ifelse(colSums(load) < 0, -1, 1)              # then positive column sums
  load <- sweep(load, 2L, signs, "*")
  scores <- scale(R, TRUE, TRUE) %*% solve(fit$correlation, load)
  list(loadings = load, scores = scores, fit = fit)
}

The call fa <- mixed_residual_factors(R, q) in the starting routine obtains these estimates. The concentrated maximum likelihood calculation converts the residual covariance to a correlation matrix, optimizes the uniquenesses and obtains loadings by eigendecomposition at each trial set of uniquenesses. Varimax rotates the two loading columns. The function then orders them by decreasing sums of squared loadings and changes signs to give positive column sums.

The residual loadings and scores must be put into the orientation used to fit the model. The call qr(t(gamma)) factors the transpose of the residual loading matrix as $G^\top=QT$. Then $GQ=T^\top$ has a lower triangular leading block. Multiplying both the loading matrix and the score matrix on the right by $Q$, and changing the same column signs in both, preserves their fitted products and makes the diagonal entries of the leading loading block positive when those entries are nonzero.

Two subsequent rescalings choose starting values. Each score column is divided by its sample standard deviation, and each loading column is multiplied by $0.8$ divided by its sample standard deviation. The rescaled scores initialize the variational means. For the all-Poisson residual start, the function triangularizes the loadings once more. It takes the factor scales from the diagonal and divides each loading column by its diagonal entry to obtain the unit-diagonal matrix $\theta$.

When a negative binomial column is present, the starting dispersions are clipped to $[0.1,10]$ and the negative binomial inverse sizes are inverted before the log sizes enter the parameter vector. Every standardized variational Cholesky factor starts at $0.3I_2$. The fitted object records the scales and unit-diagonal loadings at this starting point.

Fit the two-factor model using this residual start. The fitting call stores the null fit, the residuals and the factor analysis in its starting object s. Set the seed immediately before the complete call to preserve the sequence used to construct its randomized residuals.

1
2
3
set.seed(1108)
va2 <- mixed_va_fit(Y2,gfam,2L)
s <- va2$start

Inspect the saved null fit, residual factor analysis and starting scales and loadings.

1
2
3
4
5
6
7
print(list(proportional_odds=s$null$zeta_start,
  null_fit=c(iterations=s$null$fit$iterations,
  s$null$fit$evaluations,negative_log_likelihood=s$null$fit$objective),
  residual_factor_analysis=c(s$factors$fit$counts,ML_discrepancy=s$factors$fit$objective,
    uniquenesses=s$factors$fit$uniquenesses),
  start_sigma=s$par[s$layout$index$lv_scale],
  start_loadings=mixed_va_theta(s$par[s$layout$index$lambda],6L,2L)))
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
$proportional_odds
[1] 0.2659697

$null_fit
             iterations                function                gradient 
                 42.000                  52.000                  43.000 
negative_log_likelihood 
               3242.294 

$residual_factor_analysis
      function       gradient ML_discrepancy  uniquenesses1  uniquenesses2 
   13.00000000    13.00000000     0.01494983     0.81865769     0.72142634 
 uniquenesses3  uniquenesses4  uniquenesses5  uniquenesses6 
    0.92800093     0.91522908     0.54063752     0.72459790 

$start_sigma
[1] 1.738365 1.610185

$start_loadings
          [,1]       [,2]
[1,] 1.0000000  0.0000000
[2,] 0.4829675  1.0000000
[3,] 0.5236913 -0.3069786
[4,] 0.3225120  0.5281588
[5,] 1.5822303  0.1509142
[6,] 0.8495137  0.7821217

The fitted ordinal log gap of $0.26597$ enters the null model as a starting parameter. Exponentiating it gives an initial distance of about $1.305$ between cuts. With relative tolerance $10^{-8}$, a limit of 200 iterations and at most 3,000 function evaluations, the double-dogleg method reached a negative log likelihood of $3242.294$ in 42 iterations, with 52 function and 43 gradient evaluations.

The factor fit took 13 function and 13 gradient evaluations. Its ML_discrepancy of $0.01495$ measures the discrepancy on the correlation scale. The fitted unique variances range from $0.541$ for the fifth response to $0.928$ for the third. The two factors therefore account for a larger fraction of the fifth residual’s variance than of the third’s.

The two starting scales are $1.73837$ and $1.61019$. The printed start_loadings are entries of $\theta$. Multiplying $1.58223$ for response five by the first scale gives a loading of about $2.7505$ on the first standardized factor. Multiplying $-0.30698$ for response three by the second scale gives about $-0.4943$ on the second factor. These are inputs to the joint fit. They already incorporate the rotation and rescaling described above; the all-Poisson starting rule also applies the further triangularization.

For the first person’s Poisson zero, $F(-1)=0$ and $F(0)=e^{-\mu}$ for the null mean $\mu$. At $\mu\approx1.47$, the uniform draw selects a probability between zero and about $0.23$. The stored residual s$residuals[1,5] is about $-0.930$. Its normal cumulative probability is about $0.176$, roughly $77\%$ of the way across that interval. Another person with a zero receives a separate draw.

In mixed_ds_residuals(), the normal CDF uses the fitted standard deviation plus $10^{-5}$. For fitted inverse size $\phi$, the negative binomial CDF uses size $1/(\phi+2\times10^{-5})$. The function replaces nonfinite residuals by zero.

Reproducing R <- mixed_ds_residuals(Y, family, eta, phi, null$cuts) requires the same random-number sequence. The starting routine draws factor values before the null fit, the null fit consumes uniform draws, and the residual routine processes families in order of first appearance. Setting seed 1108 immediately before the complete fitting call puts the draws at their intended positions.

The standard-normal reference is exact under the correct response distribution with known parameters before these numerical modifications. Fitted parameters, a misspecified model without factors, and replacement of nonfinite residuals by zero can change that reference. These residuals supply starting values; they do not demonstrate normality or goodness of fit of the final factor model.

The fixed starting rule

The fixed starting rule provides a comparison with the residual construction. Its ordinal cut gaps still come from the observed ratings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mixed_va_zero_start <- function(Y, family, q, Lambda_start = 0.3) {
  n <- nrow(Y)
  p <- ncol(Y)
  Y <- mixed_va_prepare(Y, family)
  invisible(rnorm(q * n))  # factor draws replaced by zeros
  L <- mixed_va_layout(Y, family, q, TRUE)
  zeta <- unlist(lapply(L$ordinal_columns, function(j) {
    cut <- proportional_odds_cuts(Y[, j])$cuts
    row <- c(0, cut[-1L] - cut[1L])
    log(diff(row))
  }))
  par <- numeric(L$length)
  par[L$index$lv_scale] <- 1
  par[L$index$lambda] <- 1
  par[L$index$var_chol] <- log(rep(Lambda_start, q * n))
  par[L$index$zeta] <- zeta
  invisible(runif(p, 0, 0.001))  # Advance the random-number sequence.
  list(par = par, layout = L, Y = Y)
}

The fixed rule also starts the Cholesky diagonals at $0.3$, with all entries below them zero. It sets intercepts and variational means to zero, scales and dispersions to one, and loadings on and below the diagonal to one. In the stored parameter vector, a zero in log_phi means a residual standard deviation of one for a normal response and a size of one for a negative binomial response. The same field name therefore refers to different parameters in the two families. The ordinal cut gaps are an exception to the fixed assignments. Both rules use the proportional-odds fit to the observed ratings. The fixed rule uses its log gap directly, while the residual rule uses it to initialize the null fit and takes the null fit’s cut spacing.

Rotations of the factor loadings and a factor scale approaching zero

Which quantities could agree even if the loadings looked quite different? For an orthogonal matrix $U$, rotate the standardized factors by $U^\top$. The loadings become $\Lambda U$ and the trial moments become $U^\top m$ and $U^\top VU$. Because $UU^\top=I$, the projected mean and covariance satisfy

\[(\Lambda U)(U^\top m)=\Lambda m,\qquad (\Lambda U)(U^\top VU)(\Lambda U)^\top=\Lambda V\Lambda^\top .\]

The squared length of $U^\top m$ is $m^\top UU^\top m=m^\top m$. Cyclic permutation inside the trace gives $\operatorname{tr}(U^\top VU)=\operatorname{tr}(V)$, and $\vert U\vert ^2=1$ preserves the determinant. Substitution into the normal divergence to $N(0,I)$ therefore gives the same value before and after rotation. Unrestricted trial covariances admit every such rotation. Rotating a diagonal matrix with unequal variances can introduce off-diagonal entries. A nonsingular triangular leading loading block with positive diagonal entries selects an orientation for reporting loadings. Arbitrary rotations usually leave this constrained representation, so the invariance calculation describes equivalent unconstrained representations. Under a diagonal variational covariance restriction, such rotations need not remain within the allowed approximation family. Here a rotation of $0.6$ radians acts on the generating loadings and on a specified trial distribution.

1
2
3
4
5
6
7
8
9
10
11
vm <- c(.3,-.2)
vC <- t(chol(matrix(c(.7,.2,.2,.5),2)))
angle <- .6
U <- matrix(c(cos(angle),sin(angle),-sin(angle),cos(angle)),2L)
rotL <- model2$loading%*%U
rotm <- drop(crossprod(U,vm))
rotV <- crossprod(U,tcrossprod(vC)%*%U)
print(c(max_mean_difference=max(abs(model2$loading%*%vm-rotL%*%rotm)),
  max_covariance_difference=max(abs(tcrossprod(model2$loading%*%vC)-
    rotL%*%rotV%*%t(rotL))),
  KL_difference=normal_kl(vm,vC)-normal_kl(rotm,t(chol(rotV)))))
1
2
      max_mean_difference max_covariance_difference             KL_difference 
             3.469447e-17              2.775558e-16              0.000000e+00 

The maximum changes in the projected means and covariances are about $3.47\times10^{-17}$ and $2.78\times10^{-16}$. The divergence difference prints as zero.

Now compare the two starting rules on MIXED6. How small is the second factor’s contribution in the chosen orientation? The reported loading matrices give all six coefficients in that direction.

1
2
3
4
5
set.seed(1108)
va2_zero <- mixed_va_fit(Y2,gfam,2L,starting_val="zero")
print(c(data_start=va2$value, fixed_start=va2_zero$value))
print(mixed_va_model(va2, model2)$loading)
print(mixed_va_model(va2_zero, model2)$loading)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 data_start fixed_start 
   3190.684    3190.684 
          [,1]          [,2]
[1,] 0.6786314  0.000000e+00
[2,] 0.3599894  3.782457e-05
[3,] 0.5988605 -8.452029e-05
[4,] 0.2895501  5.054551e-05
[5,] 0.5073007 -7.121169e-05
[6,] 0.2307776 -2.103077e-06
          [,1]          [,2]
[1,] 0.6786388  0.000000e+00
[2,] 0.3599805  3.243551e-07
[3,] 0.5988657  2.069659e-06
[4,] 0.2895510  3.363910e-06
[5,] 0.5073022  2.747590e-06
[6,] 0.2307787 -1.105205e-06

The second diagonal loadings are positive, about $3.8\times10^{-5}$ and $3.2\times10^{-7}$. The largest absolute entries in the respective second columns are $8.45\times10^{-5}$ and $3.36\times10^{-6}$. In this orientation, the second factor contributes little to any of the six linear predictors. Both triangular leading blocks still have two nonzero diagonal entries and hence rank two.

Attained bounds from the two starts

On the separate count matrix, fit the same two-factor Poisson model from each start. The initial criterion in the table is evaluated at f$start$par, and the reported scales are the absolute values at the returned fit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Yc <- readRDS("data/source/ch11/counts-Poisson.rds")
cfam <- rep("poisson",6L)
set.seed(1108)
va_counts <- mixed_va_fit(Yc,cfam,2L,starting_val="zero")
set.seed(1108)
va_counts_res <- mixed_va_fit(Yc,cfam,2L)
start_rows <- list(MIXED6_res=va2,MIXED6_zero=va2_zero,
  Poisson_res=va_counts_res,Poisson_zero=va_counts)
print(do.call(rbind,lapply(names(start_rows),function(nm) {
  f <- start_rows[[nm]]
  data.frame(fit=nm,
    initial_negative_lower_bound=mixed_va_objective(f$start$par,f$Y,f$start$layout),
    negative_lower_bound=f$value,
    sigma1=abs(f$par[f$layout$index$lv_scale][1]),
    sigma2=abs(f$par[f$layout$index$lv_scale][2]),
    function_evaluations=sum(vapply(f$stages,function(x) x$evaluations[["objective"]],0)))
})))
1
2
3
4
5
6
7
8
9
10
           fit initial_negative_lower_bound negative_lower_bound       sigma1
1   MIXED6_res                   105566.364             3190.684 6.786314e-01
2  MIXED6_zero                     4163.123             3190.684 6.786388e-01
3  Poisson_res                 17504354.715             3679.797 2.690258e-06
4 Poisson_zero                     5307.398             3552.586 8.146630e-01
        sigma2 function_evaluations
1 3.782457e-05                  187
2 3.243551e-07                  159
3 7.997442e-01                  217
4 7.855722e-01                  457

The four rows compare the two starting rules within each dataset. For the mixed responses, the initial negative bounds are $105566.364$ from residuals and $4163.123$ from the fixed rule. Both fits reach $3190.684$ to the printed precision.

On the counts, the residual start moves from $17504354.715$ to $3679.797$. Its first diagonal loading is about $2.7\times10^{-6}$, which specifies only one entry of its first column. The fixed start moves from $5307.398$ to $3552.586$ with scales $0.81466$ and $0.78557$. The function evaluations summed over both stages are 187 and 159 for the mixed responses, then 217 and 457 for the counts.

On the Poisson counts, the fixed start attained a bound about $127.211$ higher than the residual start. A joint rotation preserves the bound algebraically, so a rotation alone cannot account for this difference on the same counts. The two starts give a comparison of attained values. Establishing a global optimum would require an argument about the criterion over its full parameter space.

Each row of the four-fit comparison combines a diagonal and an unrestricted stage. Inspecting the eight individual stopping records gives the meaning of a completed run.

1
2
3
4
5
print(do.call(rbind,lapply(names(start_rows),function(nm)
  do.call(rbind,lapply(names(start_rows[[nm]]$stages),function(stage) {
    run <- start_rows[[nm]]$stages[[stage]]
    data.frame(start=nm,stage=stage,reason=run$reason,converged=run$converged)
  })))))
1
2
3
4
5
6
7
8
9
         start        stage    reason converged
1   MIXED6_res     diagonal converged      TRUE
2   MIXED6_res unstructured converged      TRUE
3  MIXED6_zero     diagonal converged      TRUE
4  MIXED6_zero unstructured converged      TRUE
5  Poisson_res     diagonal converged      TRUE
6  Poisson_res unstructured converged      TRUE
7 Poisson_zero     diagonal converged      TRUE
8 Poisson_zero unstructured converged      TRUE

All eight flags record termination before the iteration limit under the implemented BFGS rule. These flags describe the numerical stopping tests; they do not establish that the number of factors is correctly estimated.

The starting values of the supplied mixed_va_start() follow the gllvm package, and the starting cut points of proportional_odds_cuts() follow polr() of MASS (code/NOTICE.md); gllvm provides these starting rules for variational estimation. Source adaptation records identify where code came from; the statistical definitions and algebra above determine what its quantities mean.

11.8 Comparing adaptive quadrature, Laplace, and variational estimates

A one-factor model gives each person’s six responses a marginal likelihood contribution, which integrates over the factor the product of conditional densities for the continuous responses and conditional probabilities for the discrete ones. How much does the choice of approximation change the estimated model? Adaptive Gauss-Hermite quadrature (AGQ) with 11 nodes and the second-order Laplace approximation seek maxima of their approximate sample marginal log likelihoods. Variational approximation (VA) seeks to maximize a lower bound. With one factor, each person’s normal trial distribution has one mean and one standard deviation.

Comparing the criteria while varying one intercept

First allow only the intercept of the first normal response to vary. Use the first 20 people in the separate one-factor sample generated with seed 1104. At a trial intercept $a$, all the other population parameters have their generating values. The intercept changes the conditional mean of the first measurement at every factor value, so changing it also changes the integral for each person. For VA, a fair evaluation at $a$ requires fitting the trial distributions for that value of $a$. BFGS therefore reoptimizes the 20 means and 20 log standard deviations (SDs) at each trial. The precision of the outer comparison depends on this 40-coordinate inner optimization.

The following calculation carries out this comparison. From the book directory, source("code/practice/11.8.R") loads the fitting functions and runs the following calculation, including the supplied Brent minimizer brent_min(), defined in code/ch11.R and shown after the description of the search below. The function restricted_value() puts all three criteria on the scale to be maximized.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
model1 <- mixed6_model(1L)
Y1 <- readRDS("data/source/ch11/MIXED6-one-factor.rds")
restricted <- Y1[1:20,,drop=FALSE]
gfam1 <- mixed_va_families(model1$family)
restricted_va_history <- list()
restricted_value <- function(a, method) {
  fixed <- model1
  fixed$intercept[1] <- a
  if (method=="VA") {
    local_fit <- mixed_va_local_fit(restricted,gfam1,1L,fixed)
    restricted_va_history[[length(restricted_va_history)+1L]] <<- data.frame(
      intercept=a, lower_bound=-local_fit$value, converged=local_fit$fit$converged,
      reason=local_fit$fit$reason, max_abs_gradient=max(abs(local_fit$fit$gradient)))
    return(-local_fit$value)
  }
  sum(laplace_values(restricted,model1$family,fixed,
    if (method=="AGQ") "AGQ" else "Laplace",if (method=="AGQ") 11L else 2L))
}

mixed_va_local_fit() returns the negative bound in value, so the VA branch changes its sign.

1
2
3
4
5
6
7
8
9
10
11
mixed_va_local_fit <- function(Y, family, q, model, diagonal = TRUE, rel_tol = 1e-10, maxit = 6000L) {
  Y <- mixed_va_prepare(Y, family)
  L <- mixed_va_layout(Y, family, q, diagonal, rep(length(model$cuts) + 1, sum(family == "ordinal")))
  par <- mixed_va_coordinates(model, L)
  local <- c(L$index$u, L$index$var_chol)
  value <- function(x) { par[local] <- x; mixed_va_objective(par, Y, L) }
  gradient <- function(x) { par[local] <- x; mixed_va_objective(par, Y, L, TRUE)$gradient[local] }
  fit <- bfgs(value, gradient, par[local], list(rel_tol = rel_tol, maxit = maxit))
  par[local] <- fit$par
  list(par = par, value = fit$value, fit = fit, layout = L)
}

It places the fixed model in the coordinates of mixed_va_layout() and lets bfgs() (Section 3.3) change only the trial means u and covariance factors var_chol, with the negative bound of mixed_va_objective() and the corresponding part of its gradient.

1
2
3
4
5
6
7
8
laplace_values <- function(Y, families, model, method = "AGQ", accuracy = 31L) {
  K <- ifelse(families == "Bernoulli", 2L, ifelse(families == "ordinal", length(model$cuts) + 1L, 1L))
  items <- laplace_items(Y, families, K)
  par <- laplace_coordinates(model, items)$par
  modes <- laplace_modes(rep(0, nrow(items$Y)), items, par)$mode
  rule <- if (method == "AGQ") hermite_rule(accuracy) else NULL
  laplace_terms(modes, items, par, method, accuracy, rule)$loglik
}

For the other methods, laplace_values() takes the response matrix, family labels and fixed model and returns one approximate log marginal likelihood per person. It converts the model coordinates and finds the conditional modes internally. Its accuracy argument specifies the number of nodes for AGQ or the expansion order for Laplace. Summing the returned vector gives the sample criterion at the trial intercept.

For each method, the call minimizes the negative of its criterion on $[-1.5,1.5]$. Brent’s method tries a parabolic interpolation using function values already available. It accepts the trial only if it lies strictly inside the current bracket and the proposed movement is smaller than half the relevant previous movement in absolute value. Otherwise it takes a golden-section step into the bracket. Here bracket means the current search interval. The interval excludes estimates outside $[-1.5,1.5]$; a result within it is not proof of a global maximum over all real intercepts. Finite function values and sufficiently accurate inner optimizations are needed for the search comparisons to be meaningful. Let $[a,b]$ be the current bracket and $x$ its best point. With machine precision $\epsilon_{\rm mach}$ and tolerance $\tau=\epsilon_{\rm mach}^{1/4}$, the search stops when

\[\left|x-\frac{a+b}{2}\right|+\frac{b-a}{2} \leq 2\left(\sqrt{\epsilon_{\rm mach}}\,|x|+\frac{\tau}{3}\right).\]
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
brent_min <- function(f, lower, upper, tol = .Machine$double.eps^.25) {
  golden <- (3 - sqrt(5)) * .5
  eps <- sqrt(.Machine$double.eps)
  a <- lower
  b <- upper
  v <- w <- x <- a + golden * (b - a)
  d <- e <- 0
  fv <- fw <- fx <- f(x)
  evaluations <- 1L
  tol3 <- tol / 3
  repeat {
    xm <- (a + b) * .5
    tol1 <- eps * abs(x) + tol3
    t2 <- tol1 * 2
    if (abs(x - xm) <= t2 - (b - a) * .5) break
    p <- q <- r <- 0
    if (abs(e) > tol1) {
      r <- (x - w) * (fx - fv)
      q <- (x - v) * (fx - fw)
      p <- (x - v) * q - (x - w) * r
      q <- (q - r) * 2
      if (q > 0) p <- -p else q <- -q
      r <- e
      e <- d
    }
    if (abs(p) >= abs(q * .5 * r) || p <= q * (a - x) || p >= q * (b - x)) {
      e <- if (x < xm) b - x else a - x
      d <- golden * e
    } else {
      d <- p / q
      u <- x + d
      if (u - a < t2 || b - u < t2) d <- if (x >= xm) -tol1 else tol1
    }
    u <- if (abs(d) >= tol1) x + d else if (d > 0) x + tol1 else x - tol1
    fu <- f(u)
    evaluations <- evaluations + 1L
    if (fu <= fx) {
      if (u < x) b <- x else a <- x
      v <- w; fv <- fw
      w <- x; fw <- fx
      x <- u; fx <- fu
    } else {
      if (u < x) a <- u else b <- u
      if (fu <= fw || w == x) {
        v <- w; fv <- fw
        w <- u; fw <- fu
      } else if (fu <= fv || v == x || v == w) {
        v <- u; fv <- fu
      }
    }
  }
  # The value is evaluated once more at the result.
  list(minimum = x, objective = f(x), evaluations = evaluations + 1L)
}

In brent_min(), a and b are the ends of the bracket, x is its best point, w the second best and v the previous value of w. The parabola through these three points has its minimum at x + p/q; that move is taken only if it lies inside the bracket and is shorter than half of r, the move before the last one. Otherwise d is a golden-section step, the fraction golden, $(3-\sqrt5)/2$, of the longer part of the bracket. With eps equal to $\sqrt{\epsilon_{\rm mach}}$ and tol equal to $\tau$, tol1 is $\sqrt{\epsilon_{\rm mach}}\,\vert x\vert +\tau/3$, the shortest move, and the break test is the inequality above. The returned objective evaluates f() once more at the minimum, and evaluations includes that evaluation.

1
2
3
4
5
6
7
8
9
10
restricted_rows <- lapply(c("AGQ","Laplace","VA"),function(method) {
  method_log_criterion <- function(a) restricted_value(a,method)
  a <- brent_min(function(a) -method_log_criterion(a),-1.5,1.5)$minimum
  data.frame(method=method,estimate=a,method_log_criterion=method_log_criterion(a),
    marginal_loglik_AGQ11=restricted_value(a,"AGQ"))
})
print(do.call(rbind,restricted_rows))
restricted_va_evaluations <- do.call(rbind,restricted_va_history)
print(restricted_va_evaluations)
write.csv(restricted_va_evaluations,"results/ch11/11.8-restricted-va-evaluations.csv",row.names=FALSE)
1
2
3
4
   method   estimate method_log_criterion marginal_loglik_AGQ11
1     AGQ -0.7757164            -153.8366             -153.8366
2 Laplace -0.7757053            -153.8365             -153.8366
3      VA -0.7827559            -155.1168             -153.8370

The display shows the three summary rows. The same code also prints the VA inner-optimization records and saves them in 11.8-restricted-va-evaluations.csv for inspection.

The first two intercept estimates agree to four decimal places. The AGQ estimate is $-0.775716$, the Laplace estimate is $-0.775705$, and VA gives $-0.782756$. Reading across the VA row answers two different questions. The fitted criterion in method_log_criterion is $-155.1168$. Quadrature at exactly this intercept gives $-153.8370$, about 1.28 log likelihood units above the bound.

To see what changing the intercept costs under quadrature, read down marginal_loglik_AGQ11. The value is $-153.8366$ at each of the first two estimates and $-153.8370$ at the third, a loss of about 0.0004 for the VA intercept. The Laplace criterion of $-153.8365$ even lies slightly above the AGQ criterion of $-153.8366$ at their respective estimates. That ordering compares two approximations to the integral. The common column compares intercepts with the integration rule fixed. Here a visible gap between criteria at one intercept accompanies little change in the marginal log likelihood across the fitted intercepts.

Estimating the full model on 400 people

Now use all 400 people in Y1 and estimate the population parameters together. For AGQ and Laplace, laplace_fit() seeks a maximum of the corresponding approximate sample marginal log likelihood. The binary and ordinal loadings start at 0.8 and the other loadings at 0.5. The ordinal intercepts start symmetrically about zero at intervals of two. For each normal response, the intercept starts at its sample mean and the residual variance at its sample variance. A count intercept starts at the log of its sample mean, and the inverse negative binomial size starts at one.

Let $g_0$ be the score vector of that approximation at the starting coordinates. The BFGS approximation to the inverse negative Hessian starts at $I/\Vert g_0\Vert _2$. If the largest absolute component of a direction exceeds 0.25, the routine rescales the whole direction to bring that component to 0.25. It takes half the resulting step on iterations 1 through 25 and the full step thereafter, without a line search.

Each evaluation starts the search for each person’s mode at the preceding mode. The one-factor routine laplace_modes() uses BFGS for people whose Newton iterations fail to settle. Since the modes change with the model coordinates, the score vector includes their movement when differentiating the approximation. The outer iteration stops when its largest absolute coordinate change falls below $10^{-4}$, with a limit of 500 iterations. It evaluates the approximate log likelihood and its score vector at the returned coordinates. The function is laplace_fit() in code/lib/mixed_laplace.R.

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
laplace_fit <- function(Y, families, method = "Laplace", accuracy = if (method == "Laplace") 2L else 11L,
                        tol = 1e-4, maxit = 500L, maxdiff = 0.25, step_length = c(0.5, 1),
                        first_step = 25L, start = NULL) {
  items <- laplace_items(Y, families)
  rule <- if (method == "AGQ") hermite_rule(accuracy) else NULL
  evaluate <- function(par, modes) {
    found <- laplace_modes(modes, items, par)
    terms <- laplace_terms(found$mode, items, par, method, accuracy, rule)
    c(terms, list(mode = found$mode, persons_requiring_bfgs = found$persons_requiring_bfgs))
  }
  x <- if (is.null(start)) laplace_start(items) else start
  modes <- rep(0, nrow(items$Y))
  checked <- function(par,modes) tryCatch({
    out <- evaluate(par,modes)
    if (!all(is.finite(c(par,out$mode,out$loglik,out$gradient)))) stop("nonfinite evaluation")
    out
  },error=identity)
  failed <- function(last,attempt,message,iter,trace) {
    list(par=last,failed_par=attempt,loglik=NA_real_,gradient=if(length(trace)) tail(trace,1)[[1]]$gradient
      else rep(NA_real_,length(x)),last_loglik=if(length(trace)) tail(trace,1)[[1]]$loglik else NA_real_,
      iterations=iter,converged=FALSE,reason=message,trace=trace,items=items,method=method,accuracy=accuracy)
  }
  current <- checked(x, modes)
  if(inherits(current,"error")) return(failed(rep(NA_real_,length(x)),x,conditionMessage(current),0L,list()))
  alpha <- step_length[1]
  g0 <- rowSums(current$gradient)
  g <- g0
  Id <- diag(length(x))
  if (all(g0 == 0)) return(list(par = x, loglik = sum(current$loglik), gradient = g0,
    logliki = current$loglik, mode = current$mode, iterations = 0L, converged = TRUE,
    reason = "zero_initial_gradient", trace = list(), items = items, method = method, accuracy = accuracy))
  Hk <- Id / sqrt(sum(g0^2))
  trace <- list()
  success <- FALSE
  for (iter in 1:maxit) {
    xk <- x
    pk <- -Hk %*% g
    if (!all(is.finite(pk))) {
      trace[[iter]] <- list(par=xk,loglik=sum(current$loglik),gradient=g)
      return(failed(xk,xk-as.numeric(alpha*pk),"nonfinite quasi-Newton direction",iter,trace))
    }
    if (max(abs(pk)) > maxdiff) pk <- maxdiff * pk / max(abs(pk))
    sk <- as.numeric(alpha * pk)
    x <- xk - sk
    trace[[iter]] <- list(par = xk, loglik = sum(current$loglik), gradient = g)
    if (max(abs(x - xk)) < tol) {
      success <- TRUE
      break
    }
    current <- checked(x, current$mode)
    if(inherits(current,"error")) return(failed(xk,x,conditionMessage(current),iter,trace))
    g <- rowSums(current$gradient)
    yk <- as.numeric(g - g0)
    rhok <- as.numeric(1 / (t(yk) %*% sk))
    Hk <- (Id - rhok * sk %*% t(yk)) %*% Hk %*% (Id - rhok * yk %*% t(sk)) + rhok * sk %*% t(sk)
    g0 <- g
    if (iter == first_step) alpha <- step_length[2]
  }
  final <- checked(x, current$mode)
  if(inherits(final,"error")) return(failed(xk,x,conditionMessage(final),iter,trace))
  list(par = x, loglik = sum(final$loglik), gradient = rowSums(final$gradient),
    logliki = final$loglik, mode = final$mode, iterations = iter, converged = success,
    reason=if(success) "small_coordinate_change" else "iteration_limit",
    trace = trace, items = items, method = method, accuracy = accuracy)
}

In evaluate(), laplace_modes() finds each person’s mode from the previous modes and laplace_terms() returns each person’s log likelihood contribution under the Laplace or adaptive quadrature approximation, with accuracy nodes for the latter, and its score vector as one column of gradient; rowSums() adds the columns to give the score $g$. The function laplace_start() supplies the starting coordinates described above. The matrix Hk starts at $I/\Vert g_0\Vert _2$, the direction is Hk times the score, its largest component is limited to maxdiff, and alpha is the step fraction, one half until iteration first_step and one afterwards. The update of Hk is the BFGS formula for the inverse negative Hessian with sk and yk, the changes in coordinates and in score. An evaluation that fails or gives nonfinite values ends the fit with the last valid coordinates and the message in reason.

VA fits this one-factor model from the fixed start in one BFGS stage. The wrapper fit_one_factor() returns each method’s fitted model and its stopping diagnostics. For AGQ and Laplace it converts the fitted coordinates with laplace_model().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
laplace_model <- function(par, items, template) {
  model <- template
  for (j in seq_along(items$type)) {
    i <- items$index[[j]]
    model$loading[j, 1] <- par[i[1]]
    if (items$type[j] == "GRM" && items$K[j] > 2) {
      model$intercept[j] <- 0
      model$cuts <- -par[i[-1]]
      next
    }
    model$intercept[j] <- par[i[2]]
    if (items$type[j] == "normal") model$sd[j] <- sqrt(par[i[3]])
    if (items$type[j] == "negbin") model$size[j] <- 1 / par[i[3]]
  }
  model
}

This reverses laplace_coordinates(): for an ordinal response the cuts are the negated intercepts and the intercept is zero, a residual variance becomes a standard deviation, and an inverse size becomes a size. The following calls produce the full-sample table. To work with the saved fits, use fits1 <- readRDS("data/derived/ch11/fits.rds")$one_factor in place of the assignment that fits the three models.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fit_one_factor <- function(Y,method) {
  if (method=="VA") {
    set.seed(1108)
    f <- mixed_va_fit(Y,gfam1,1L,starting_val="zero")
    return(list(method="VA",model=mixed_va_model(f,model1),method_log_criterion=f$lower_bound,
      converged=f$stages$diagonal$converged,iterations=f$stages$diagonal$iterations,
      reason=f$stages$diagonal$reason,
        max_abs_gradient_component=max(abs(f$stages$diagonal$gradient)),fit=f))
  }
  f <- laplace_fit(Y,model1$family,method)
  list(method=method,model=laplace_model(f$par,f$items,model1),
    method_log_criterion=f$loglik,converged=f$converged,
    reason=f$reason,iterations=f$iterations,
      max_abs_gradient_component=max(abs(f$gradient)),fit=f)
}
common <- function(Y,model,nodes) sum(laplace_values(Y,model1$family,model,"AGQ",nodes))

In the VA branch, starting_val="zero" selects the fixed starting rule and seed 1108 is the fitting seed. The returned model includes loadings on the factor scale and negative binomial size on the response scale. common() evaluates that model’s sample marginal log likelihood at a specified quadrature order. Only the model parameters pass from the variational fit into this calculation. The quadrature weights and nodes adapt to each person’s responses under that model.

1
2
3
4
5
6
7
fits1 <- lapply(c(AGQ="AGQ",Laplace="Laplace",VA="VA"),function(m) fit_one_factor(Y1,m))
print(do.call(rbind,lapply(fits1,function(f) data.frame(method=f$method,
  method_log_criterion=f$method_log_criterion,
  iterations=f$iterations,max_abs_gradient_component=f$max_abs_gradient_component,
    converged=f$converged,
  marginal_loglik_AGQ31=common(Y1,f$model,31L),marginal_loglik_AGQ45=common(Y1,f$model,
    45L)))))
1
2
3
4
5
6
7
8
         method method_log_criterion iterations max_abs_gradient_component
AGQ         AGQ            -3079.020         19                0.003523156
Laplace Laplace            -3079.031         19                0.003570558
VA           VA            -3087.201         89                0.003827192
        converged marginal_loglik_AGQ31 marginal_loglik_AGQ45
AGQ          TRUE             -3079.020             -3079.020
Laplace      TRUE             -3079.020             -3079.020
VA           TRUE             -3084.061             -3084.061

The fitted criteria were $-3079.020$, $-3079.031$ and $-3087.201$ after 19, 19 and 89 iterations. All three fits met their implemented stopping rules. For AGQ and Laplace, the largest absolute components of the score vectors were 0.0035 and 0.0036 when the coordinate changes satisfied the tolerance. For VA the value 0.0038 is the maximum absolute component of the gradient of the negative bound over the model coordinates and the variational coordinates of all 400 people. A numerical tolerance on changes in model coordinates and a BFGS stop in this joint problem test different quantities. These derivative magnitudes use different parameter vectors and units, so they are not directly comparable measures of estimation error.

The final two columns put the estimates on a common scale. Increasing the quadrature order from 31 to 45 gave the same printed value within each row, $-3079.020$, $-3079.020$ and $-3084.061$, respectively. Agreement between quadrature orders at the printed precision is a numerical stability check at the returned models, not proof of exact integration or global maximization.

The 400-person fit separates the approximation gap from the effect of changing parameter estimates. Subtracting the computed bound from the common quadrature log likelihood gives $-3084.061-(-3087.201)=3.140$. This gap includes the choice of a normal trial distribution for each person’s latent factor and the additional bounds on response expectations. To measure the loss from using the VA parameter estimates, evaluate both those estimates and the AGQ estimates by the same quadrature rule. The difference is $-3079.020-(-3084.061)=5.041$ log likelihood units. The Laplace estimates attained the same common value as the AGQ estimates at the displayed precision.

The interpretation of 3.140 uses quadrature as an approximation to the marginal log likelihood; it is not an exactly known gap. Both this gap and the comparison of 5.041 use the returned parameter estimates and the returned normal approximation distributions, without establishing their global optimality.

Eligibility and stopping records in repeated samples

Would the same methods finish on another sample of 400 people? The repeated-sample calculation generated 200 datasets from the one-factor model and called fit_one_factor() three times on each dataset. For each returned model it computed ll, the two common evaluations at orders 31 and 45. The condition isTRUE(f$converged)&&all(is.finite(ll)) defined a usable fit. From the book directory, source("code/practice/11.8-study.R") reads data/derived/ch11/study-records.rds and computes the comparisons from the saved attempts. The following block reads those saved attempts and counts the usable fits and their intersection.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/lib/mixed_factor.R", local = TRUE)
source("code/examples/ch11-study-fields.R", local = TRUE)
records <- lapply(readRDS("data/derived/ch11/study-records.rds"), function(record) {
  record$methods <- lapply(record$methods, mixed_study_fields)
  record
})
model <- mixed6_model(1L)
methods <- c("AGQ", "Laplace", "VA")
usable <- t(vapply(records, function(r) {
  vapply(r$methods, function(fit) isTRUE(fit$valid), logical(1))
}, logical(3)))
colnames(usable) <- methods
matched <- apply(usable, 1L, all)
membership <- data.frame(id = seq_along(records), usable, all_three = matched)
print(c(colSums(usable), matched = sum(matched)))
1
2
    AGQ Laplace      VA matched 
    197     197     200     197 

The function mixed_study_fields() renames four fields used in the saved files: native to method_log_criterion, common to quadrature_loglik, score to max_abs_gradient_component, and last_native to last_method_log_criterion. It changes field names without recomputing their values or altering eligibility. The matrix usable has one row per dataset and a column per method. Applying all across a row identifies a sample usable for every method.

All 600 attempts have finite common evaluations at their retained parameters. To see why some still failed, consider dataset 78. In its AGQ record, the third element of raw_last is the inverse size at the last finite iterate, 0.045884. In records[[78L]]$methods[[1L]], the same element of raw_attempt is $-0.029351$. The proposed update crossed zero, outside the model’s positive inverse sizes. The routine returned the last parameters and recorded a missing method_log_criterion for the failed fit. Evaluating those last parameters by quadrature gives finite values at both orders.

AGQ and Laplace both failed in this way on datasets 78, 180 and 196. Their respective usable counts are 197 and 197. VA finished on all 200. These are numerical failures of the proposed update, not estimates at the Poisson limit $\phi=0$. A finite value at the last retained parameters does not turn a failed update into a completed maximum likelihood fit.

A fit that met its stopping rule can also warrant inspection. The section script code/practice/11.8-study.R constructs endpoints from failed fits and usable fits with a maximum absolute derivative greater than 0.1. After running that script, print this table to see both the reason for stopping and the proposed change in inverse size. In the second part of the printed table, the inverse sizes follow the same row order as the reasons in the first part. The value 0.1 is a descriptive threshold in the stored parameter coordinates. It is neither a formal test nor invariant to rescaling those coordinates.

1
print(endpoints, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  id  method               reason last_max_abs_gradient_component
  78     AGQ nonfinite evaluation                      11.9932911
  78 Laplace nonfinite evaluation                      11.9935603
  93      VA            converged                       0.6126563
 170      VA            converged                       0.4782296
 180     AGQ nonfinite evaluation                       8.2971487
 180 Laplace nonfinite evaluation                       8.3021610
 196     AGQ nonfinite evaluation                       6.3762272
 196 Laplace nonfinite evaluation                       6.3481632
 199      VA            converged                       1.0121194
 last_inverse_size6 attempt_inverse_size6
        0.045884004          -0.029351418
        0.045938085          -0.029278435
        0.384094058                    NA
        0.103286323                    NA
        0.028926921          -0.023049277
        0.028957618          -0.022826388
        0.003702600          -0.002044898
        0.003745304          -0.001979683
        0.156177424                    NA

The VA rows for datasets 93, 170 and 199 have maximum absolute derivatives of 0.613, 0.478 and 1.012. All three fits met the BFGS stopping rule and gave finite common log likelihoods. The first residual standard deviation is stored in end[1L] on the scale of the first measurement. Extract it from the third method of those same records.

1
vapply(records[c(93L,170L,199L)], function(r) unname(r$methods[[3L]]$end[1L]), numeric(1))

The three SD estimates are approximately 0.01501, 0.00592 and 0.00888, respectively, against a generating SD of one. Thus the large derivatives occurred at fits with a small first residual SD. The derivative threshold selects fits to inspect and makes no change to eligibility. All three enter the VA calculation of estimation bias. They also enter the paired comparison, since AGQ and Laplace finished on these three samples. The intersection still has 197 datasets.

Parameter recovery and differences between methods

To estimate bias for method $j$, let $n_j$ be the number of samples in usable[, j] and $\theta_0$ the generating value. Subtract $\theta_0$ from the average of the $n_j$ estimates. The Monte Carlo standard error (MCSE) of this estimated bias is their sample SD divided by $\sqrt{n_j}$. To compare methods $j$ and $k$, subtract their estimates within each dataset selected by matched. The mean of these 197 differences estimates the average change between methods on the matched samples. Its MCSE uses the sample SD of the differences divided by $\sqrt{197}$. Subtracting first allows sampling variation shared by both fits to cancel. These bias estimates describe the samples with usable fits, so the failed AGQ and Laplace fits do not enter their averages.

The named vector truth stores the generating values for five intercepts, six loadings, two residual SDs, one size, two cuts and three probabilities. Each full table has 19 rows per method or per method pair. Each print call produces 57 rows. The displays excerpt the quantities discussed below.

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
eta <- model$intercept[3L] + model$loading[3L, 1L] * c(-1, 0, 1)
truth <- c(setNames(model$intercept[-4], paste0("intercept", c(1:3, 5:6))),
           setNames(model$loading[, 1L], paste0("loading", 1:6)),
           sd1 = model$sd[1], sd2 = model$sd[2], size6 = model$size[6],
           cut1 = model$cuts[1], cut2 = model$cuts[2],
           setNames(plogis(eta), c("P3_at_minus_one", "P3_at_zero", "P3_at_one")))

recovery <- paired <- list()
for (j in seq_along(methods)) {
  sample_ids <- which(usable[, j])
  estimates <- t(vapply(sample_ids, function(i) records[[i]]$methods[[j]]$estimates,
    truth))
  recovery[[j]] <- data.frame(method = methods[j], parameter = names(truth),
    truth = truth,
    assigned = length(records), eligible = length(sample_ids),
      bias = colMeans(estimates) - truth,
    MCSE = apply(estimates, 2L, sd) / sqrt(length(sample_ids)))
  for (k in seq_len(j - 1L)) {
    differences <- t(vapply(which(matched), function(i) {
      records[[i]]$methods[[j]]$estimates - records[[i]]$methods[[k]]$estimates
    }, truth))
    paired[[length(paired) + 1L]] <- data.frame(first = methods[j], second = methods[k],
      parameter = names(truth), matched = nrow(differences),
        mean_difference = colMeans(differences),
      MCSE = apply(differences, 2L, sd) / sqrt(nrow(differences)))
  }
}
recovery <- do.call(rbind, recovery)
paired <- do.call(rbind, paired)
1
print(recovery, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
  method       parameter      truth assigned eligible          bias        MCSE
     AGQ        loading1  0.8000000      200      197  0.0021927071 0.006590109
     AGQ        loading6  0.3000000      200      197 -0.0099795137 0.005964585
     AGQ           size6  4.0000000      200      197  1.8822617099 0.705680149
 Laplace        loading1  0.8000000      200      197  0.0018068443 0.006600453
 Laplace        loading6  0.3000000      200      197 -0.0099986667 0.005963050
 Laplace           size6  4.0000000      200      197  1.8443049969 0.675560181
      VA        loading1  0.8000000      200      200  0.0244342838 0.011381747
      VA        loading6  0.3000000      200      200 -0.2023640449 0.003204622
      VA           size6  4.0000000      200      200 -1.1243984054 0.074232746
      VA P3_at_minus_one  0.2689414      200      200  0.0221870950 0.003056470

For the first loading, the estimated biases in AGQ, Laplace and VA order were 0.0022, 0.0018 and 0.0244, with MCSEs of 0.0066, 0.0066 and 0.0114. For the negative binomial loading, they were $-0.0100$, $-0.0100$ and $-0.2024$, with MCSEs of 0.0060, 0.0060 and 0.0032. Among the six VA loadings this last loading had the largest absolute estimated bias. Size measures dispersion on a different scale. At a generating size of four its estimated biases were $+1.88$, $+1.84$ and $-1.12$, with MCSEs of 0.71, 0.68 and 0.074. A fitted probability can also change. At factor value $-1$, VA overestimated the probability of success on response three by 0.0222 on average, with MCSE 0.0031. The binary probabilities are conditional at specified factor values, rather than probabilities averaged over the population factor distribution.

1
print(paired, row.names = FALSE)
1
2
3
4
   first  second       parameter matched mean_difference         MCSE
 Laplace     AGQ        loading1     197   -3.858628e-04 6.625816e-05
      VA     AGQ        loading6     197   -1.919956e-01 4.215341e-03
      VA     AGQ           size6     197   -3.047396e+00 6.880098e-01

The paired table subtracts second from first within each sample. For the first loading, Laplace minus AGQ averaged $-0.000386$ with MCSE 0.0000663. For the sixth loading, VA minus AGQ averaged $-0.191996$ with MCSE 0.004215. For negative binomial size, VA minus AGQ averaged about $-3.05$, with MCSE 0.69. These parameter differences describe the 197 matched datasets. The loss of 5.041 above compares the complete fitted models on the original 400 people.

In the earlier calculation for one person with a zero negative binomial count, the gap in that response expectation was about 0.43. The next largest of the six gaps was about 0.0023. This calculation concerns one response vector at specified trial moments. The study estimates biases across fitted samples and does not isolate their causes. The reported MCSEs quantify simulation variability in these averages; they do not measure numerical integration error or optimization error.

In R, gllvm provides variational estimation for mixed responses, and lamle provides adaptive quadrature and the second-order Laplace approximation.

A mixed categorical application: responses about survey participation

An empirical example can combine response types without requiring every family in MIXED6. The gss82 extract in poLCA contains four survey-participation indicators for 1,202 white respondents in the 1982 General Social Survey. Two indicators are binary and two have three categories. The dataset documentation identifies the extract and its category order. This example concerns that historical subset; it does not estimate attitudes for the entire present-day population.

The proposed factor describes a favorable orientation toward survey participation. Its substantive adequacy is a hypothesis to examine. Beliefs about surveys, understanding the questions and cooperation are related concepts, but they need not be interchangeable measurements of one trait. The three responses to PURPOSE are treated as ordered from unfavorable, through conditional approval, to favorable. This ordering is an explicit modeling choice.

IndicatorResponse familyRecoded values, from low to high
ACCURACYBernoulli0: not true; 1: mostly true
UNDERSTABernoulli0: fair or poor; 1: good
PURPOSEOrdinal0: waste of time; 1: depends; 2: good
COOPERATOrdinal0: impatient; 1: cooperative; 2: interested

The package stores these columns as factors with response labels. First match each label to its explicit category order, then reverse the resulting numerical codes to implement this direction. Converting the entire factor data frame directly to a matrix would produce labels, not numerical responses. No ordinal response is reduced to a binary score. The setup below loads the chapter functions. The application script is code/examples/ch11-application.R; its inputs and fitted objects use data/source/ch11 and data/derived/ch11.

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
# start_application() loads the functions, sets the random-number methods and creates the folders.
# record_check() and record_review() save checks and review flags; neither changes an estimate.
source("code/lib/application_run.R", local = TRUE)
application <- start_application(11L)
record_check <- application$record_check
record_review <- application$record_review

data("gss82", package = "poLCA", envir = environment())
gss_names <- c("ACCURACY", "UNDERSTA", "PURPOSE", "COOPERAT")
gss_codebook <- list(ACCURACY = c("Mostly true", "Not true"),
  UNDERSTA = c("Good", "Fair/Poor"), PURPOSE = c("Good", "Depends", "Waste of time"),
  COOPERAT = c("Interested", "Cooperative", "Impatient"))
gss_raw <- vapply(gss_names, function(name) {
  labels <- as.character(gss82[[name]])
  codes <- match(labels, gss_codebook[[name]])
  if (any(!is.na(labels) & is.na(codes))) stop(paste("Unrecognized response label in", name))
  codes
}, integer(nrow(gss82)))
gss_categories <- c(2L, 2L, 3L, 3L)
for (j in seq_along(gss_names)) stopifnot(
  all(is.na(gss_raw[, j]) | gss_raw[, j] %in% seq_len(gss_categories[j])))
gss_rows <- which(complete.cases(gss_raw))
gss_Y <- sweep(gss_raw[gss_rows, , drop = FALSE], 2L, gss_categories, function(x, K) K - x)
gss_families <- c("Bernoulli", "Bernoulli", "ordinal", "ordinal")
print(c(available = nrow(gss_raw), analyzed = nrow(gss_Y),
        excluded = nrow(gss_raw) - nrow(gss_Y)))
print(do.call(rbind, lapply(seq_along(gss_names), function(j)
  data.frame(indicator = gss_names[j], score = seq_len(gss_categories[j]) - 1L,
             count = tabulate(gss_Y[, j] + 1L, gss_categories[j])))), row.names = FALSE)
saveRDS(list(source = gss82, coding = gss_codebook, raw = gss_raw, rows = gss_rows, Y = gss_Y),
        file.path("data/source/ch11", "ch11-gss82.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
available  analyzed  excluded 
     1202      1202         0 
 indicator score count
  ACCURACY     0   577
  ACCURACY     1   625
  UNDERSTA     0   222
  UNDERSTA     1   980
   PURPOSE     0   179
   PURPOSE     1   104
   PURPOSE     2   919
  COOPERAT     0    35
  COOPERAT     1   159
  COOPERAT     2  1008

The columns of gss_Y follow the order in the table. The lists in gss_codebook specify the supplied category order by its actual labels; match() assigns the corresponding positions independently of the factor’s internal level numbers. An unknown nonmissing label produces an error instead of becoming a missing response. The vector gss_families assigns the response likelihood to each column. The row count and frequency table verify the recoding before a latent model is fitted.

All 1,202 records are retained. The most favorable categories are common for understanding, purpose and cooperation: their counts are 980, 919 and 1,008. Favorable answers about accuracy are less common, with 625 respondents. These differences in response prevalence need not imply corresponding differences in association with the latent factor.

Let $z_i\sim N(0,1)$ be respondent $i$’s factor. Conditional on $z_i$, the four responses are independent. For the binary indicators $j=1,2$, specify

\[\Pr(Y_{ij}=1\mid z_i) =\operatorname{logit}^{-1}(\alpha_j+\lambda_jz_i).\]

For the ordinal indicators $j=3,4$, use

\[\Pr(Y_{ij}\geq k\mid z_i) =\operatorname{logit}^{-1}(\lambda_jz_i-\tau_{jk}), \qquad k=1,2,\quad \tau_{j1}<\tau_{j2}.\]

Each ordinal item has its own pair of thresholds and has intercept zero in this expression. Adding a free intercept as well as unrestricted thresholds would leave their common shift unidentified. The binary intercept is the log odds of the favorable response at $z=0$. A loading changes the binary or cumulative log odds per factor standard deviation. An ordinal threshold is measured on this linear-predictor scale; when its loading is nonzero, the corresponding half-probability location on the factor scale is $\tau_{jk}/\lambda_j$. There are ten free parameters: four loadings, two binary intercepts and four ordinal thresholds.

Compare first- and second-order Laplace approximations with adaptive quadrature. All four fits use the same responses and the same factor distribution. The first adaptive fit supplies initial coefficients for the finer rule; the finer fit then supplies initial coefficients for both Laplace calculations.

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
gss_agq15 <- laplace_fit(gss_Y, gss_families, "AGQ", 15L, tol = 1e-6, maxit = 2500L)
stopifnot(all(is.finite(gss_agq15$par)))
gss_agq31 <- laplace_fit(gss_Y, gss_families, "AGQ", 31L, tol = 1e-6,
                        maxit = 2500L, start = gss_agq15$par)
gss_laplace1 <- laplace_fit(gss_Y, gss_families, "Laplace", 1L, tol = 1e-6,
                           maxit = 2500L, start = gss_agq31$par)
gss_laplace2 <- laplace_fit(gss_Y, gss_families, "Laplace", 2L, tol = 1e-6,
                           maxit = 2500L, start = gss_agq31$par)
gss_fits <- list(AGQ15 = gss_agq15, AGQ31 = gss_agq31,
                 Laplace1 = gss_laplace1, Laplace2 = gss_laplace2)

# Each item has its own intercepts; ordinal thresholds are not shared between items.
gss_category_probabilities <- function(fit, z, log_scale = FALSE) {
  lapply(seq_along(fit$items$index), function(j) {
    index <- fit$items$index[[j]]
    slope <- fit$par[index[1]]
    intercepts <- fit$par[index[-1]]
    stopifnot(all(diff(intercepts) < 0))
    eta <- outer(slope * z, intercepts, "+")
    K <- length(intercepts) + 1L
    log_probabilities <- matrix(0, length(z), K)
    log_probabilities[, 1] <- -log1pexp(eta[, 1])
    log_probabilities[, K] <- -log1pexp(-eta[, K - 1L])
    if (K > 2L) for (k in 2:(K - 1L)) {
      gap <- intercepts[k - 1L] - intercepts[k]
      log_probabilities[, k] <- -log1pexp(-eta[, k - 1L]) - log1pexp(eta[, k]) +
        log(-expm1(-gap))
    }
    stopifnot(all(is.finite(log_probabilities)))
    if (log_scale) log_probabilities else exp(log_probabilities)
  })
}
gss_loglik <- function(fit, Y, n_nodes = 241L) {
  rule <- irt_rule(n_nodes, c(-8, 8))
  log_probabilities <- gss_category_probabilities(fit, rule$nodes, log_scale = TRUE)
  log_kernel <- matrix(0, nrow(Y), length(rule$nodes))
  for (j in seq_len(ncol(Y))) log_kernel <- log_kernel +
    t(log_probabilities[[j]][, Y[, j] + 1L, drop = FALSE])
  sum(apply(sweep(log_kernel, 2L, log(rule$weights), "+"), 1L, logsumexp))
}
gss_comparison <- do.call(rbind, lapply(names(gss_fits), function(name) {
  fit <- gss_fits[[name]]
  data.frame(method = name, converged = fit$converged, reason = fit$reason,
    own_loglik = fit$loglik, common_loglik = gss_loglik(fit, gss_Y),
    max_abs_own_score = max(abs(fit$gradient)))
}))
gss_orientation <- if (gss_agq31$par[gss_agq31$items$index[[1]][1]] < 0) -1 else 1
gss_parameters <- do.call(rbind, lapply(seq_along(gss_names), function(j) {
  index <- gss_agq31$items$index[[j]]
  slope <- gss_orientation * gss_agq31$par[index[1]]
  intercepts <- gss_agq31$par[index[-1]]
  data.frame(indicator = gss_names[j], family = gss_families[j], loading = slope,
    binary_intercept = if (length(intercepts) == 1L) intercepts else NA_real_,
    threshold1 = if (length(intercepts) == 2L) -intercepts[1] else NA_real_,
    threshold2 = if (length(intercepts) == 2L) -intercepts[2] else NA_real_)
}))
print(gss_comparison, row.names = FALSE)
print(gss_parameters, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
   method converged                  reason own_loglik common_loglik max_abs_own_score
    AGQ15      TRUE small_coordinate_change  -2786.487     -2786.485      8.427899e-07
    AGQ31      TRUE small_coordinate_change  -2786.485     -2786.485      1.783196e-06
 Laplace1      TRUE small_coordinate_change  -2528.244     -3002.839      2.547230e-05
 Laplace2      TRUE small_coordinate_change  -2784.636     -2789.174      1.274811e-06
 indicator    family   loading binary_intercept threshold1 threshold2
  ACCURACY Bernoulli 1.3367826        0.1059375         NA         NA
  UNDERSTA Bernoulli 0.2745014        1.5083706         NA         NA
   PURPOSE   ordinal 2.5063868               NA  -3.183084  -2.194230
  COOPERAT   ordinal 0.7797196               NA  -3.783565  -1.832449

The fitted coordinates are grouped by item in items$index. The first entry of each group is its loading. Subsequent entries are cumulative intercepts, so negating the two entries for an ordinal item gives its thresholds. The parameter table orients the first loading positively using gss_orientation. The local probability function preserves a separate pair of thresholds for each ordinal item. It evaluates the logarithms of adjacent cumulative-probability differences in a form that avoids subtracting nearly equal tail probabilities. The log likelihood function multiplies these item probabilities within a respondent and integrates over the shared factor before taking a logarithm.

In the comparison table, own_loglik is each method’s approximation at its returned coefficients. common_loglik evaluates those coefficients on 241 equally spaced standard-normal nodes over $[-8,8]$. Comparing this column separates differences in the attained coefficients from differences in the approximation being reported. The score column still refers to each fit’s own criterion. Outside the displayed code, the application script also evaluates the common integral with 481 nodes and uses record_review() to record whether that value and the adaptive value agree with the common value; the results are reported below.

The two adaptive fits give common log likelihoods of about -2786.485. The first-order Laplace fit instead gives -3002.839 on that same rule, approximately 216.35 log likelihood units lower, even though its own approximation is -2528.244 and its own score is small. Its apparently higher objective value therefore does not indicate a better fit to the marginal likelihood. The second-order Laplace fit is much closer, with common log likelihood -2789.174, but remains about 2.69 units below the adaptive fits. All four routines satisfy their stopping conditions; the approximation and the attained marginal likelihood still matter.

For interpretation, orient the first loading positively by reflecting the factor and all its loadings together when necessary. This preserves the marginal distribution. The following table reports the probability of the most favorable category at three factor values. The pairwise calculation checks associations that may remain poorly represented by one common factor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
gss_oriented <- gss_agq31
gss_loading_indices <- vapply(gss_oriented$items$index, function(index) index[1], 0L)
if (gss_oriented$par[gss_loading_indices[1]] < 0)
  gss_oriented$par[gss_loading_indices] <- -gss_oriented$par[gss_loading_indices]
gss_conditional <- gss_category_probabilities(gss_oriented, c(-1, 0, 1))
gss_probabilities <- do.call(rbind, lapply(seq_along(gss_names), function(j)
  data.frame(indicator = gss_names[j], trait = c(-1, 0, 1),
    highest_category_probability = gss_conditional[[j]][, gss_categories[j]])))
gss_rule <- irt_rule(241L, c(-8, 8))
gss_node_probabilities <- gss_category_probabilities(gss_agq31, gss_rule$nodes)
gss_pairs <- do.call(rbind, lapply(combn(4L, 2L, simplify = FALSE), function(pair) {
  observed <- table(factor(gss_Y[, pair[1]], levels = 0:(gss_categories[pair[1]] - 1L)),
                    factor(gss_Y[, pair[2]], levels = 0:(gss_categories[pair[2]] - 1L))) / nrow(gss_Y)
  fitted <- crossprod(gss_node_probabilities[[pair[1]]],
                      gss_node_probabilities[[pair[2]]] * gss_rule$weights)
  data.frame(first = gss_names[pair[1]], second = gss_names[pair[2]],
             max_cell_probability_gap = max(abs(observed - fitted)))
}))
print(gss_probabilities, row.names = FALSE)
print(gss_pairs, row.names = FALSE)
saveRDS(list(fits = gss_fits, comparison = gss_comparison, parameters = gss_parameters,
  probabilities = gss_probabilities, pair_diagnostics = gss_pairs),
  file.path("data/derived/ch11", "ch11-gss82.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 indicator trait highest_category_probability
  ACCURACY    -1                    0.2260336
  ACCURACY     0                    0.5264596
  ACCURACY     1                    0.8088755
  UNDERSTA    -1                    0.7744951
  UNDERSTA     0                    0.8188196
  UNDERSTA     1                    0.8560511
   PURPOSE    -1                    0.4225884
   PURPOSE     0                    0.8997302
   PURPOSE     1                    0.9909922
  COOPERAT    -1                    0.7412987
  COOPERAT     0                    0.8620532
  COOPERAT     1                    0.9316406
    first   second max_cell_probability_gap
 ACCURACY UNDERSTA              0.007369940
 ACCURACY  PURPOSE              0.004097411
 ACCURACY COOPERAT              0.009741549
 UNDERSTA  PURPOSE              0.006213552
 UNDERSTA COOPERAT              0.033254432
  PURPOSE COOPERAT              0.004141131

The highest category means a favorable binary answer for the first two indicators and the top of the three-category scale for the other two. A negative loading after the first loading has been oriented positively would indicate that the proposed common interpretation needs reconsideration. The pair table compares observed and model-implied cell probabilities after integrating out the factor. A large discrepancy between understanding and cooperation, for example, would motivate examining whether their association requires additional structure. It would not by itself identify the source of the discrepancy.

The fitted PURPOSE loading is about 2.506, while the UNDERSTA loading is about 0.275. Accordingly, the most favorable purpose response rises in probability from 0.423 at $z=-1$ to 0.991 at $z=1$, whereas good understanding rises from 0.774 to 0.856. Good understanding is common across this range and changes relatively little along the fitted factor. The largest pairwise discrepancy, about 0.0333, concerns understanding and cooperation. The remaining pair maxima are below 0.010. This identifies a particular association for substantive review without establishing a second factor or a direct dependence between the indicators.

For the final adaptive fit, increasing the fixed evaluation rule from 241 to 481 nodes changes the log likelihood by less than $10^{-12}$. Its adaptive value differs from the fixed-rule value by about $1.74\times10^{-5}$. These checks support the adaptive calculation for this ten-parameter Bernoulli-ordinal model. The poor first-order Laplace result shows why a converged approximation needs a separate accuracy assessment. The continuous and count examples earlier in the chapter demonstrate other likelihood combinations; the present numerical comparisons do not automatically extend to those response families.

This post is licensed under CC BY-NC 4.0 by the author.