Post

A framework for generalized latent variable models

A test records a person’s answers, while a researcher may be interested in the ability those answers reflect. Even a complete record of correct and incorrect answers leaves a question about interpretation. How would the responses be expected to differ between people with different abilities? Assumptions about this relationship give an ability estimate its meaning. Generalized latent variable models express such assumptions explicitly, making it possible to examine how conclusions about an unobserved characteristic follow from the responses that were actually recorded. The chapter assembles such a model in the order in which its parts enter a likelihood: a distribution for each response, latent variables shared by several responses, a distribution for those latent variables, and the marginal likelihood that combines them. It then shows how the main model families fit this construction, when their parameters are identified, and how a complete model is represented and simulated in R.

A latent variable model first needs a distribution for each recorded response. Suppose ten trials under the same conditions yield two successes. The observed count is 2 and the observed proportion is 0.2. With the number of trials known, either value determines the other. The count takes integer values from 0 to 10, and the proportion increases in steps of one tenth. To see how the choice of units affects the mean and variance, write the distribution of a scalar response $Y$ in exponential-family form. For a possible value $y$,

\[f(y\mid\xi,\phi) =\exp\!\left\{\frac{y\xi-b(\xi)}{a(\phi)}+c(y,\phi)\right\}.\]

The natural parameter $\xi$ multiplies the observation in the exponent. The cumulant function $b$ normalizes the distribution as $\xi$ varies. The dispersion parameter $\phi$ enters through the positive function $a(\phi)$, and $c(y,\phi)$ collects terms independent of $\xi$. For a discrete response, $f$ is a probability mass function, and summing it over all possible values of $y$ gives one. For a continuous response, $f$ is a density and its integral is one.

That total remains one as $\xi$ varies. Fix $\phi$ and assume that the set of possible response values, called the support, does not change with $\xi$. Also assume that the derivatives below can pass through the sum or integral. The derivative of $\log f$ with respect to $\xi$ is $[y-b^{\prime}(\xi)]/a(\phi)$. Multiplying by $f$ gives the derivative of $f$ itself. Its sum or integral is zero, so $E[Y-b^{\prime}(\xi)]=0$ and $E(Y)=b^{\prime}(\xi)$. Differentiating this mean weights the derivative of $f$ by $y$ before summing or integrating. This gives

\[b''(\xi)=\frac{dE(Y)}{d\xi} =\frac{E(Y^2)-b'(\xi)E(Y)}{a(\phi)} =\frac{\operatorname{Var}(Y)}{a(\phi)}.\]

The variance is therefore $a(\phi)b^{\prime\prime}(\xi)$. When the natural parameter depends on covariate values, these are the mean and variance conditional on those values.

For one Bernoulli trial, let $p$ be its success probability, with $0<p<1$. Its log odds $\xi=\log[p/(1-p)]$ give $p=e^\xi/(1+e^\xi)$. Substituting in $y\log p+(1-y)\log(1-p)$ leaves $y\xi-\log(1+e^\xi)$ for either outcome, zero or one. Here $a(\phi)=1$. Differentiating the cumulant function $b(\xi)=\log(1+e^\xi)$ gives $e^\xi/(1+e^\xi)=p$. Its second derivative is $e^\xi/(1+e^\xi)^2=p(1-p)$, the variance of one trial. Now let $Y$ count successes in $m$ conditionally independent trials with the same $p$ and a fixed positive trial count $m$. There are $\binom{m}{y}$ arrangements with $y$ successes for each integer $y$ from 0 to $m$, so the count has log probability

\[\log P(Y=y)=\log\binom{m}{y}+y\xi-mb(\xi).\]

The cumulant function for the count $Y$ is $mb(\xi)$, giving mean $mp$ and variance $mp(1-p)$. Dividing the count by $m$ divides its mean by $m$ and its variance by $m^2$. The proportion therefore has mean $p$ and variance $p(1-p)/m$.

The count formula needs $b(\xi)$ even when the odds are too large to represent. At $\xi=1000$, computing $e^{1000}$ overflows in double precision, although $b(1000)$ exceeds 1000 by only $\log(1+e^{-1000})$. For $x>0$, factoring $e^x$ out of $1+e^x$ gives $x+\log(1+e^{-x})$ after taking the logarithm. For $x\leq0$, the original exponential is already at most one. Combining the two cases gives

\[s(x)=\log(1+e^x)=\max(x,0)+\log\!\left(1+e^{-|x|}\right).\]

In R, the function log1pexp() computes $s$ element by element. Begin a script with it after opening R in the book directory, the companion folder latent-models-r; every code/, data/, figures/ and results/ path in the book starts there. The function log1p() evaluates $\log(1+u)$ accurately for small $u$. Forming $1+u$ first can round the sum to one when $u$ is very small.

1
2
3
4
log1pexp <- function(x) {
  stopifnot(is.numeric(x), !anyNA(x))
  pmax(x, 0) + log1p(exp(-abs(x)))
}

The only exponential evaluated in log1pexp() has a nonpositive argument, so it cannot overflow. At negative and positive infinity, the formula gives zero and positive infinity, respectively. A missing value, NA, supplies no point at which to evaluate the cumulant function, so the function rejects it.

A rare success can have a finite log probability even when its probability rounds to zero. From $p=1/(1+e^{-\xi})$, a success contributes $\log p=-s(-\xi)$. A failure contributes $\log(1-p)=-s(\xi)$. Summing over the successes and failures and including the number of arrangements gives $\log\binom{m}{y}-ys(-\xi)-(m-y)s(\xi)$. In R, lchoose() computes the log binomial coefficient. The two calculations below differ in whether they form $p$ first, using plogis(), or evaluate its logarithm directly.

1
2
3
4
5
6
7
8
xi <- c(0, -1000, 1000, -1000, 1000)
y <- c(2, 0, 10, 1, 9)
m <- 10
p <- plogis(xi)
# Each success adds log(p) = -log1pexp(-xi), each failure log(1 - p) = -log1pexp(xi).
stable <- lchoose(m, y) - y * log1pexp(-xi) - (m - y) * log1pexp(xi)
direct <- lchoose(m, y) + y * log(p) + (m - y) * log1p(-p)
print(data.frame(xi, trials = m, y, stable = round(stable, 6), direct = round(direct, 6)))
1
2
3
4
5
6
     xi trials  y      stable    direct
1     0     10  2   -3.124809 -3.124809
2 -1000     10  0    0.000000       NaN
3  1000     10 10    0.000000       NaN
4 -1000     10  1 -997.697415      -Inf
5  1000     10  9 -997.697415      -Inf

At zero log odds, each sequence of ten outcomes has probability $2^{-10}$. Exactly 45 sequences contain two successes, which explains the common log probability $-3.124809$. At $\xi=-1000$, one success in ten has log probability approximately $\log 10-1000$, or $-997.697415$. Rounding $p$ to zero makes the direct result negative infinity. With zero successes, the direct expression evaluates zero times $\log 0$ and returns NaN. The stable column prints zero for the nearly certain outcome. The cumulant function itself also has well-defined limits.

1
print(log1pexp(c(-Inf, 0, Inf)))
1
[1] 0.0000000 0.6931472       Inf

The middle entry is $\log 2$ at zero. The outer entries confirm $s(-\infty)=0$ and $s(+\infty)=+\infty$.

The same form covers Poisson counts and normal measurements. For a Poisson count $y$, any nonnegative integer is possible. With positive rate $\lambda$, the log probability is $y\log\lambda-\lambda-\log(y!)$. Reading off $\xi=\log\lambda$ gives $b(\xi)=e^\xi$ and $a(\phi)=1$. Its first two derivatives give the same value $e^\xi$ for the mean and the variance. Increasing the rate therefore increases both. For a real-valued normal measurement with mean $\mu$ and variance $\phi=\sigma^2>0$, expand the square in the log density to obtain

\[-\frac{(y-\mu)^2}{2\phi}-\frac12\log(2\pi\phi) =\frac{y\mu-\mu^2/2}{\phi} -\frac{y^2}{2\phi}-\frac12\log(2\pi\phi).\]

Here $\xi=\mu$, $b(\xi)=\xi^2/2$, and $a(\phi)=\phi$. The last two terms form $c(y,\phi)$. The first derivative gives the mean $\mu$. The second derivative is one, so the variance remains equal to $\phi$ as the mean varies.

To specify how the mean depends on explanatory variables, let $\eta$ be their linear predictor, a weighted sum that can include an intercept. A link function $g$ sets $g(\mu)=\eta$, and the inverse link function gives the mean $g^{-1}(\eta)$. A canonical link function makes $\eta=\xi$. For a normal mean, the identity link function gives $\eta=\mu$. For a Bernoulli probability, the logit link function gives the log odds, and for a Poisson mean, the log link function gives the log rate. Each is canonical for its family. For a success count, the logit link function acts on the per-trial mean $p=E(Y)/m$. Another choice for this same probability is the probit link function $\eta=\Phi^{-1}(p)$, where $\Phi$ is the standard normal distribution function. At $\eta=1$, it gives $p=\Phi(1)$ and hence log odds $\xi=\log[\Phi(1)/(1-\Phi(1))]\approx1.668268$. The linear predictor and natural parameter have different values here even though both specify the same Bernoulli probability.

The function resp_family() groups the calculations needed at a given value of the linear predictor: the inverse link function, its derivative, the conditional response variance, the check that an observation lies in the support, and the log probability or log density. Add the three pieces to the same script and evaluate the definition once it is complete. The arguments select the family, the dispersion, and the trial count. For a binomial response, inverse returns the probability for one trial. Its derivative with respect to $\eta$ is $p(1-p)$ because this function uses the logit link function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
resp_family <- function(name, dispersion = 1, trials = 1) {
  stopifnot(length(name) == 1L,
            name %in% c("normal", "binomial", "poisson"),
            length(dispersion) == 1L, is.finite(dispersion), dispersion > 0,
            length(trials) == 1L, is.finite(trials),
            trials >= 0, trials == floor(trials))
  if (name != "normal" && dispersion != 1) {
    stop("Binomial and Poisson dispersion is one", call. = FALSE)
  }
  # Binomial: the inverse link function returns the probability per trial.
  inverse <- switch(name, normal = identity, binomial = plogis, poisson = exp)
  derivative <- switch(name,
    normal = function(eta) rep(1, length(eta)),
    binomial = function(eta) plogis(eta) * plogis(-eta),
    poisson = exp)

The variance calculation uses those means on the response’s own scale. For a normal measurement, the variance function of the normal distribution is $V(\mu)=1$, so the conditional variance $\phi V(\mu)$ is the value of dispersion. For a count of successes at probability $p$, variance returns $mp(1-p)$. The support check enforces the integer limits on possible counts.

1
2
3
4
5
6
7
8
9
  # Binomial: the variance is that of the recorded count of successes.
  variance <- switch(name,
    normal = function(mu) rep(dispersion, length(mu)),
    binomial = function(mu) trials * mu * (1 - mu),
    poisson = identity)
  support <- switch(name,
    normal = function(y) is.finite(y),
    binomial = function(y) is.finite(y) & y == floor(y) & y >= 0 & y <= trials,
    poisson = function(y) is.finite(y) & y == floor(y) & y >= 0)

The function named log_probability_or_density returns a log probability for a binomial or Poisson count and a log density for a normal measurement. Given an observation y and a finite linear predictor value eta, it assigns negative infinity outside the support. Within the support, the binomial calculation uses the two stable log probabilities. The normal calculation passes the square root of the dispersion to dnorm(), which expects a standard deviation. The list at the end makes each calculation available by name.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  log_probability_or_density <- function(y, eta) {
    n <- max(length(y), length(eta))
    stopifnot(is.numeric(y), is.numeric(eta), !anyNA(y),
              all(is.finite(eta)), length(y) %in% c(1L, n),
              length(eta) %in% c(1L, n))
    y <- rep_len(y, n)
    eta <- rep_len(eta, n)
    out <- rep(-Inf, n)
    ok <- support(y)
    out[ok] <- switch(name,
      normal = dnorm(y[ok], eta[ok], sqrt(dispersion), log = TRUE),
      binomial = lchoose(trials, y[ok]) - y[ok] * log1pexp(-eta[ok]) -
        (trials - y[ok]) * log1pexp(eta[ok]),
      poisson = dpois(y[ok], exp(eta[ok]), log = TRUE))
    out
  }
  list(name = name, dispersion = dispersion, trials = trials,
       linkinv = inverse, mu_eta = derivative, variance = variance,
       support = support, log_probability_or_density = log_probability_or_density)
}

The binomial calculation distinguishes the probability per trial from the mean and variance of the recorded count. The standard R binomial family object, stored below as r_family, supplies the per-trial quantities. The two objects built with resp_family() describe a single trial and a count in ten trials.

1
2
3
4
5
6
7
8
eta <- c(-1, 0, 1)
r_family <- binomial("logit")  # the binomial family object gives the per-trial columns
bernoulli <- resp_family("binomial")
grouped <- resp_family("binomial", trials = 10)
mu <- r_family$linkinv(eta)
print(round(data.frame(eta, trials = grouped$trials, p = mu, dp = r_family$mu.eta(eta),
  bernoulli_variance = r_family$variance(mu),
  count_mean = 10 * mu, count_variance = grouped$variance(mu)), 6))
1
2
3
4
  eta trials        p       dp bernoulli_variance count_mean count_variance
1  -1     10 0.268941 0.196612           0.196612   2.689414       1.966119
2   0     10 0.500000 0.250000           0.250000   5.000000       2.500000
3   1     10 0.731059 0.196612           0.196612   7.310586       1.966119

In the middle row, r_family$linkinv(eta) gives $p=0.5$ at $\eta=0$. The inverse link function has derivative 0.25 there, and r_family$variance(mu) gives the single-trial variance of 0.25. Multiplying $p$ by ten gives 5 expected successes. With the same probability as input, grouped$variance(mu) gives a count variance of 2.5. The corresponding proportion has variance $2.5/10^2=0.025$.

At the same values of the linear predictor, a normal measurement with dispersion 2 and a Poisson count with mean $e^\eta$ have different mean-variance relations.

1
2
3
4
5
normal <- resp_family("normal", dispersion = 2)
poisson <- resp_family("poisson")
print(round(data.frame(eta, normal_mean = normal$linkinv(eta),
  normal_variance = normal$variance(eta), poisson_mean = poisson$linkinv(eta),
  poisson_variance = poisson$variance(poisson$linkinv(eta))), 6))
1
2
3
4
  eta normal_mean normal_variance poisson_mean poisson_variance
1  -1          -1               2     0.367879         0.367879
2   0           0               2     1.000000         1.000000
3   1           1               2     2.718282         2.718282

The normal mean follows the linear predictor while the variance remains equal to 2. Moving down the Poisson columns increases the variance along with the mean. At the middle value of the linear predictor, each family also assigns a log probability or log density to a specified observation.

1
2
3
print(round(c(normal = normal$log_probability_or_density(1, 0),
              binomial = grouped$log_probability_or_density(2, 0),
              poisson = poisson$log_probability_or_density(2, 0)), 6))
1
2
   normal  binomial   poisson 
-1.515512 -3.124809 -1.693147 

For the normal measurement, y is 1, the mean is zero, and the variance is 2. Substitution in the log density gives $-\tfrac12\log(4\pi)-\tfrac14\approx-1.515512$. The binomial log probability is $-3.124809$ for two successes in ten trials with $p=0.5$. The Poisson value is the log probability of observing two at rate one, $-1-\log 2\approx-1.693147$. Given an observation and the value of its linear predictor, the same call now evaluates a conditional log probability for a count or a conditional log density for a measurement. These response distributions are available in the stats package.

1.2 Response models and structural models

So far each response has been described on its own. Suppose each person has a continuous score on one task and a correct or incorrect answer to a separate item. How could the same proficiency affect both responses when one is measured in score units and the other takes only the values zero and one? A response model gives each response its own linear predictor while allowing both linear predictors to depend on the same latent variable. For response $j$ of person $i$, write

\[\eta_{ij}=x_{ij}^{\top}\beta_j+\lambda_j^{\top}z_i .\]

The vector $x_{ij}$ contains the observed covariates, with coefficients $\beta_j$. The vector $z_i$ contains the person’s $q$ latent variables, and $\lambda_j$ contains the factor loadings that multiply them for response $j$. Take one common factor and choose parameter values for illustration. The design matrix $X$ has one column of ones, so only an intercept contributes to $x_{ij}^{\top}\beta_j$. The two intercepts are $1$ and $-0.4$, and the respective loadings are $0.8$ and $0.7$. The linear predictor of the score is $1+0.8z_i$. The linear predictor of the item, $\eta_{i2}=1(-0.4)+0.7z_i$, uses the very same factor value for that person.

The response family determines what a change in each linear predictor means. Write $Y_{i1}$ for the score and $Y_{i2}$ for the item response, with one indicating a correct answer. Let the common factor have a standard normal distribution: zero represents average proficiency, and one unit represents one population standard deviation of proficiency. At a specified factor value $z$, the response distributions are

\[\begin{aligned} Y_{i1}\mid z_i=z &\sim N(1+0.8z,\,0.36),\\ Y_{i2}\mid z_i=z &\sim \operatorname{Bernoulli}\!\left(\operatorname{logit}^{-1}(-0.4+0.7z)\right). \end{aligned}\]

For the continuous score, the intercept 1 is the expected score at average proficiency. The loading 0.8 gives the increase in expected score, in score units, for one standard deviation more proficiency. Thus the conditional mean rises from 1 at $z=0$ to 1.8 at $z=1$. The residual variance remains 0.36: it measures variation in scores among people with the same proficiency. The factor variance of one instead describes variation in proficiency across people.

For the binary item, the intercept $-0.4$ is the log odds of a correct answer at average proficiency. The loading 0.7 gives the increase in those log odds for one standard deviation more proficiency. The inverse logit function converts the resulting log odds to a conditional response probability. Equal differences in proficiency therefore give equal differences in log odds, but generally different changes in probability.

The function model_spec() stores the design matrix, regression coefficients, factor loadings, response families, and the mean vector and covariance matrix of the latent variables. Given factor values, the first four components determine the two conditional means; the latent mean and covariance describe how factor values vary across people. For a fresh session in the book directory, load the response-family definitions and construct the one-trial family used for the item.

1
2
3
source("code/lib/stability.R")
source("code/lib/families.R")
bernoulli <- resp_family("binomial")

Build the following two pieces as one function. The dimensions of loadings give the number of responses p and the number of factors q. With two responses and one factor, its two rows each contain one loading. The two columns of beta and the two elements of families follow the same response order. One factor requires a single latent mean and a one-by-one covariance matrix.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
model_spec <- function(X, beta, loadings, families, latent_mean, latent_cov,
                       constraint_description) {
  stopifnot(is.matrix(X), is.matrix(beta), is.matrix(loadings),
            is.matrix(latent_cov), is.list(families),
            is.numeric(X), is.numeric(beta), is.numeric(loadings),
            is.numeric(latent_mean), is.numeric(latent_cov))
  p <- nrow(loadings)
  q <- ncol(loadings)
  stopifnot(nrow(X) > 0, p > 0, q > 0,
            ncol(X) == nrow(beta), ncol(beta) == p,
            length(families) == p, length(latent_mean) == q,
            identical(dim(latent_cov), c(q, q)),
            all(is.finite(X)), all(is.finite(beta)),
            all(is.finite(loadings)), all(is.finite(latent_mean)),
            all(is.finite(latent_cov)), isSymmetric(latent_cov),
            length(constraint_description) == 1L, nzchar(constraint_description))

The covariance matrix of the latent variables must also be positive definite. The call to chol() tests this by attempting its Cholesky factorization. The constraint_description argument records restrictions such as a fixed factor variance or a positive first loading. These restrictions are implemented when specifying the model; this argument stores their description. Compatible dimensions allow the matrix products to be evaluated. Whether the distribution of the observations uniquely determines the parameters is a separate question, taken up in Section 1.6.

1
2
3
4
5
6
7
8
9
  chol(latent_cov)  # an error unless latent_cov is positive definite
  stopifnot(all(vapply(families, function(f) {
    is.list(f) && f$name %in% c("normal", "binomial", "poisson") &&
      is.function(f$log_probability_or_density)
  }, logical(1))))
  list(X = X, beta = beta, loadings = loadings, families = families,
       latent_mean = latent_mean, latent_cov = latent_cov,
       constraint_description = constraint_description)
}

The returned object will be named spec in the example below. Its fields follow the response and factor indices in the linear predictor.

Entry in specQuantity in the model
X[i, ]Observed design row $x_i^\top$, shared by the responses in this example
beta[, j]Coefficient vector $\beta_j$ for response $j$
loadings[j, ]Loading row $\lambda_j^\top$
families[[j]]Conditional distribution and link function for response $j$
latent_mean, latent_covMean and covariance of the common factor, here zero and one

In this construction, X %*% beta gives one row per person and one column per response. The separately supplied Z has one row per person and one column per factor, so entry $(i,j)$ of Z %*% t(loadings) is $\lambda_j^\top z_i$, the part of person $i$’s linear predictor for response $j$ that depends on the factors. The model assumes that these factor values follow the standard normal distribution across people. Applying plogis() to the item column converts log odds to success probabilities.

1
2
3
4
5
6
7
8
9
10
spec <- model_spec(
  X = matrix(1, 3, 1), beta = matrix(c(1, -0.4), 1, 2),
  loadings = matrix(c(0.8, 0.7), 2, 1),
  families = list(resp_family("normal", dispersion = 0.36), bernoulli),
  latent_mean = 0, latent_cov = matrix(1),
  constraint_description = "Standard normal factor and positive first loading")
Z <- matrix(c(-1, 0, 1), 3, 1)
eta_example <- spec$X %*% spec$beta + Z %*% t(spec$loadings)
print(round(cbind(z = Z[, 1], normal_mean = eta_example[, 1],
                  success_probability = plogis(eta_example[, 2])), 6))
1
2
3
4
      z normal_mean success_probability
[1,] -1         0.2            0.249740
[2,]  0         1.0            0.401312
[3,]  1         1.8            0.574443

At $z=-1$, the linear predictor of the item is $-0.4-0.7=-1.1$, giving probability 0.249740. At $z=0$ and $z=1$, this probability rises to 0.401312 and 0.574443. The conditional mean score increases by 0.8 at each step, but the increases in probability differ because the inverse logit function is nonlinear. All three factor values were supplied to illustrate the response model. For an actual respondent, only the score and item answer would be observed.

A structural model describes how the factors themselves vary. Consider a separate example in which an observed covariate enters the equations for two factors and the first factor also enters the equation for the second. In the general linear structural equation $z_i=Bz_i+\Gamma w_i+\zeta_i$, the entry $B_{k\ell}$ is the coefficient of factor $\ell$ in the equation for factor $k$. It expresses the contribution of a one-unit difference in factor $\ell$, with the other terms in that equation fixed. Each entry of $\Gamma$ similarly gives the contribution per unit of an observed covariate in $w_i$.

The disturbance $\zeta_{ik}$ represents variation in factor $k$ not accounted for by the predictors in its structural equation. It is a residual term in the sense of an unexplained random part specified by the model. A residual computed after fitting, such as an observed response minus its fitted value, is a different quantity. Here the disturbances belong to equations for latent factors; the variation of a response at a given factor value belongs to the response model. Assume $\zeta_i$ has conditional mean zero and covariance matrix $\Psi$ at the specified covariate value. The diagonal entries of $\Psi$ are disturbance variances, and its off-diagonal entries describe how these unexplained parts covary.

Subtract $Bz_i$ to obtain $(I-B)z_i=\Gamma w_i+\zeta_i$, where $I$ is the identity matrix. If $I-B$ is invertible, the unique solution is

\[z_i=(I-B)^{-1}(\Gamma w_i+\zeta_i).\]

This reduced form expresses both factors in terms of the covariates and disturbances. If $I-B$ were singular and a solution existed, adding a nonzero vector from its null space would give another solution for the same disturbances.

Set $A=(I-B)^{-1}$. At fixed $w_i$, the term $A\Gamma w_i$ is constant and $A\zeta_i$ has mean zero. Centering $z_i$ therefore leaves $A\zeta_i$. Taking the conditional expectation of its outer product gives the conditional covariance matrix of the factors. The conditional mean vector and covariance matrix are

\[\begin{aligned} E(z_i\mid w_i)&=A\Gamma w_i,\\ \operatorname{Var}(z_i\mid w_i)&=A E(\zeta_i\zeta_i^\top\mid w_i) A^\top =A\Psi A^\top. \end{aligned}\]

In the two-factor example, the equations are $z_{i1}=0.3w_i+\zeta_{i1}$ and $z_{i2}=0.5z_{i1}-0.2w_i+\zeta_{i2}$. Only $B_{21}=0.5$ is nonzero: a one-unit difference in the first factor contributes half a unit to the second factor, with $w_i$ and the second disturbance fixed. The covariate coefficient $-0.2$ describes its direct contribution to the second equation; its contribution through the first factor also enters the second factor’s mean. Set the covariate to 2. In R, latent_mean contains the two conditional factor means. The matrices Psi and latent_cov describe disturbance and factor covariances, respectively, at that same covariate value.

1
2
3
4
5
6
7
8
9
10
B <- matrix(c(0, 0.5, 0, 0), 2, 2)  # filled by column, so B[2, 1] = 0.5
Gamma <- matrix(c(0.3, -0.2), 2, 1)
w <- 2
Psi <- diag(c(1, 0.75))
A <- solve(diag(2) - B)  # row k of A maps the disturbances to latent variable k
latent_mean <- drop(A %*% Gamma * w)
latent_cov <- A %*% Psi %*% t(A)
print(data.frame(factor = 1:2, factor_mean_given_w = latent_mean,
  disturbance_cov_1 = Psi[, 1], disturbance_cov_2 = Psi[, 2],
  latent_cov_1 = latent_cov[, 1], latent_cov_2 = latent_cov[, 2]))
1
2
3
4
5
6
  factor factor_mean_given_w disturbance_cov_1 disturbance_cov_2 latent_cov_1
1      1                 0.6                 1              0.00          1.0
2      2                -0.1                 0              0.75          0.5
  latent_cov_2
1          0.5
2          1.0

The first factor has mean $0.3(2)=0.6$. The second has mean $-0.2(2)+0.5(0.6)=-0.1$. Their centered values are $\zeta_{i1}$ and $0.5\zeta_{i1}+\zeta_{i2}$. The disturbances are uncorrelated and have variances 1 and 0.75. The first disturbance enters both factors, so their covariance is $0.5(1)=0.5$. In row 2, this gives 0.5 under latent_cov_1 even though disturbance_cov_1 is zero. The second factor has variance $0.5^2(1)+0.75=1$. A supplied disturbance pair gives one realization from the same equations.

1
2
3
zeta <- c(0.4, -0.1)
z <- drop(A %*% (Gamma * w + zeta))
print(z)
1
[1] 1 0

The first disturbance raises the first factor to $0.6+0.4=1$. Substituting that value in the second equation gives $-0.4+0.5(1)-0.1=0$. This pair $(1,0)$ describes one realization of the two factors. Averaging over the disturbances at $w=2$ gives the conditional mean vector $(0.6,-0.1)$. The lavaan package fits structural equation models with latent variables.

1.3 Continuous, discrete, and nonparametric latent distributions

A response model alone describes a person whose latent value is known. For a person whose proficiency is unknown, what probability does the item model assign to a correct answer? At factor value $z$, that probability is $p(z)=\operatorname{logit}^{-1}(-0.4+0.7z)$. To average across people, the model must also say how proficiency is distributed. A nonsingular normal distribution for $q$ latent variables is specified by a mean vector of length $q$ and a positive definite covariance matrix of dimension $q$ by $q$. Its mean vector locates the population averages; the diagonal entries of its covariance matrix measure variation in each latent variable, and the off-diagonal entries describe how pairs vary together. For this single factor, retain $Z\sim N(0,1)$ and denote its density by $\varphi$. For an item response $Y$ scored one for a correct answer and zero otherwise, the marginal success probability is

\[P(Y=1)=\int_{-\infty}^{\infty} p(z)\,\varphi(z)\,dz .\]

The value $p(0)$ answers the question for a person at mean proficiency. The integral answers it for a randomly selected person by averaging $p(z)$ over the population distribution of proficiency.

With the intercept and loading fixed, suppose proficiency takes only two values. The two values, $-1$ and $+1$, are its mass points. Their probability masses, meaning the probabilities $P(Z=-1)$ and $P(Z=+1)$, are 0.4 and 0.6, respectively. A success can now arise in two mutually exclusive ways. Its probability is the sum of the joint probabilities $P(Z=z,Y=1)=P(Z=z)p(z)$ at those two values.

These averages can be computed directly in R. Start R with the book directory as the working directory. Load the response functions and construct the Bernoulli family for one item.

1
2
3
source("code/lib/stability.R")
source("code/lib/families.R")
bernoulli <- resp_family("binomial")

To represent such a distribution, write finite_latent() with one row of points for each mass point and one column for each latent variable. The entries of mass correspond to the rows in the same order. The definition pairs each row with its probability and checks that these probabilities are nonnegative and sum to one within numerical tolerance.

1
2
3
4
5
6
7
finite_latent <- function(points, mass) {
  stopifnot(is.matrix(points), is.numeric(points), all(is.finite(points)),
            nrow(points) > 0, ncol(points) > 0, is.numeric(mass),
            length(mass) == nrow(points), all(is.finite(mass)),
            all(mass >= 0), abs(sum(mass) - 1) < 1e-12)
  list(type = "finite", points = points, mass = mass)
}

The returned latent$points[k, ] contains the latent value $z_k$, and latent$mass[k] is its population probability $\pi_k$. When $\pi_k>0$, $z_k$ is a support point of the discrete distribution. The function also permits a listed point with probability zero, which is not part of the support unless another row assigns positive probability to the same value. Here the single column gives two trait values with supplied, fixed masses. At each value, the product of its mass and the conditional success probability is the joint probability of that value and a success.

1
2
3
4
5
6
7
8
latent <- finite_latent(matrix(c(-1, 1), 2, 1), c(0.4, 0.6))
point_eta <- -0.4 + 0.7 * latent$points[, 1]
point_p <- plogis(point_eta)
# Each product gives the joint probability P(Z = z, Y = 1) at one mass point.
marginal_p <- sum(latent$mass * point_p)
print(round(data.frame(z = latent$points[, 1], mass = latent$mass,
                       eta = point_eta, p = point_p,
                       mass_times_p = latent$mass * point_p), 6))
1
2
3
   z mass  eta        p mass_times_p
1 -1  0.4 -1.1 0.249740     0.099896
2  1  0.6  0.3 0.574443     0.344666

The lower proficiency value contributes $0.4(0.249740)\approx0.099896$ to the probability of a correct answer. The higher value contributes $0.6(0.574443)\approx0.344666$. The table rounds the products for display. The sum uses the values before rounding.

1
print(round(marginal_p, 6))
1
[1] 0.444561

The marginal probability 0.444561 lies between the two conditional probabilities. It is closer to the probability at $+1$ because that point carries more than half the population mass.

What do the two rows of the probability table represent? In a latent class model, a row can name a category of people, with its own probability of answering each item correctly. The category label selects those response probabilities. For the proficiency model, the number in each row gives a trait value to insert in the same item response function. For the specified population with masses 0.4 and 0.6, the sum gives its marginal probability exactly, apart from rounding in the calculation. A finite sum can also approximate the integral for a continuous proficiency distribution. In that use the points are chosen as integration nodes and the weights are chosen for the specified distribution. The continuous model assigns probability to ranges between the nodes as well.

In the calculation above, both locations and both masses were given in advance. If the distribution of proficiency is itself to be estimated, nonparametric maximum likelihood chooses a mixing distribution to maximize the marginal likelihood of the observed responses without requiring a particular shape such as a normal density. The estimate can assign all its probability to finitely many points. The latent values at those points and their probabilities are then estimated, with each probability nonnegative and all probabilities summing to one. For independent people answering only this item under identical conditions, however, the data distinguish mixing distributions only through the resulting marginal success probability. Any two distributions giving the same success probability also give the same likelihood for every pattern of correct and incorrect answers.

In the normal model, the density determines how much each range of proficiencies contributes to the integral. With finite support, a mass multiplies the response probability at each point, whether the locations and masses were specified or estimated. To see what happens when the two mass points no longer differ, set both locations to $+1$ without changing their masses. Both terms now use the item probability stored in same_p.

1
2
3
# When the two mass points coincide, both components give the same response probability.
same_p <- plogis(-0.4 + 0.7 * 1)
print(c(two_coincident = sum(latent$mass * same_p), single_point = same_p))
1
2
two_coincident   single_point 
     0.5744425      0.5744425 

The coefficients of that common probability add to one, so its value 0.5744425 is also the marginal success probability.

Return to the original mass points at $-1$ and $+1$. The same averaging applies to either possible answer. Let $\pi_k=P(Z=z_k)$ be the mass at point $k$, and write $f(y\mid z_k)$ for the conditional probability of the answer $y$. The log joint probability is $a_k=\log\pi_k+\log f(y\mid z_k)$. On the probability scale, point $k$ contributes $e^{a_k}$ to the sum. If the answer is sufficiently rare at every point, a computer can round every one of those exponentials to zero even when each $a_k$ is finite. For a nonempty vector with finite maximum $m=\max_k a_k$, write each term as $e^m e^{a_k-m}$. Factoring out the common multiplier gives

\[\log\sum_k e^{a_k} =\log\!\left(e^m\sum_k e^{a_k-m}\right) =m+\log\sum_k e^{a_k-m}.\]

At the point attaining the maximum, the shifted exponent is zero and its exponential is exactly one. All other exponentials lie between zero and one. The entire sum therefore remains positive even if a small term rounds to zero. Adding $m$ after taking the logarithm accounts for the multiplier without computing $e^m$.

The function logsumexp() implements this identity. Its argument a contains the logarithms of the terms being summed, here the joint probabilities of the answer and each value of the latent variable.

1
2
3
4
5
6
7
logsumexp <- function(a) {
  stopifnot(is.numeric(a), is.null(dim(a)), !anyNA(a))
  if (!length(a)) return(-Inf)
  m <- max(a)
  if (is.infinite(m)) return(m)
  m + log(sum(exp(a - m)))
}

An empty vector has no terms to sum, so the total is zero and the function returns negative infinity. A missing value leaves a summand unknown, so the function rejects it. When the maximum is infinite, its sign determines the answer. If every entry is negative infinity, the total on the original scale is zero. If an entry equals positive infinity, the total is infinite. Returning the maximum in either case avoids an undefined subtraction.

For a success at the two linear predictor values stored in point_eta, bernoulli$log_probability_or_density() supplies the conditional log probability at each value. Adding the log masses gives the log joint probabilities in a. For a separate numerical example, rare_a uses the same masses with linear predictor values $-1001$ and $-999$.

1
2
3
4
5
a <- log(latent$mass) + bernoulli$log_probability_or_density(1, point_eta)
rare_a <- log(latent$mass) + bernoulli$log_probability_or_density(1, c(-1001, -999))
print(round(c(direct = log(marginal_p), shifted = logsumexp(a),
              rare_direct = log(sum(exp(rare_a))),
              rare_shifted = logsumexp(rare_a)), 6))
1
2
      direct      shifted  rare_direct rare_shifted 
   -0.810667    -0.810667         -Inf  -999.424443 

For the original item, the two routes agree at $-0.810667$, the logarithm of the unrounded marginal probability. For the rare success, both unshifted exponentials underflow. The direct calculation takes the logarithm of zero, whereas the shifted calculation returns the finite log probability $-999.424443$. The remaining calls check the conventions for an empty sum and infinite arguments.

1
2
print(c(empty = logsumexp(numeric()), zero_total = logsumexp(c(-Inf, -Inf)),
        infinite_total = logsumexp(c(0, Inf))))
1
2
         empty     zero_total infinite_total 
          -Inf           -Inf            Inf 

The empty vector and the pair of negative infinities both give a log total of negative infinity. The positive infinity returned for c(0, Inf) checks the arithmetic rule for an infinite term in a general sum of exponentials.

For a finite latent distribution, logsumexp() combines the log joint probabilities into one log marginal probability for the observed answer. Averaging the same item response function over a normal factor still requires integration against its density. For the finite case, the matrixStats package also computes the logarithm of a sum from the logarithms of its terms.

1.4 Conditional independence and the marginal likelihood

Two answers from one person share the same latent value, so their joint probability cannot be obtained by averaging each answer separately. Suppose the same person answers a timetable question and a fare question. Score each answer one if correct and zero otherwise. The person is the independent sampling unit. Assume that, given the person’s proficiency $z$, knowing the timetable answer leaves the probability of a correct fare answer unchanged. Under this conditional independence assumption, the probability of two correct answers at $z$ is $p_1(z)p_2(z)$, where $p_j(z)$ is the success probability on item $j$. More generally, the conditional joint probability or density of the responses is the product of the conditional probabilities or densities of the individual responses. Taking logs turns this product into a sum. Start R in the book directory. For a longer response vector, multiplying 200 probabilities of 0.01 illustrates the numerical limit of a direct product.

1
2
print(c(product = prod(rep(0.01, 200)),
        log_product = sum(rep(log(0.01), 200))))
1
2
    product log_product 
      0.000    -921.034 

The exact product is $10^{-400}$. It rounds to zero in double precision, but adding the logarithms gives $-921.034$ to three decimals.

The function log_conditional() adds the conditional log probabilities or log densities of the answers in one person’s response vector y. Column j of eta gives the linear predictor values for item j, one row for each value of the latent variables. Its family supplies the corresponding log probabilities or log densities.

1
2
3
4
5
6
7
8
9
10
log_conditional <- function(y, eta, families) {
  stopifnot(is.numeric(y), is.matrix(eta), is.numeric(eta),
            ncol(eta) == length(y), length(families) == length(y),
            all(is.finite(eta)))
  out <- numeric(nrow(eta))
  for (j in which(!is.na(y))) {
    out <- out + families[[j]]$log_probability_or_density(y[j], eta[, j])
  }
  out
}

The loop skips missing answers and returns, for each row of eta, the conditional joint log probability or log density of the observed answers.

Both answers share the same unknown proficiency. Let $y_i$ denote the response vector for person $i$, $y_{ij}$ its entry for item $j$, and $\theta$ the parameters of the response and latent distributions. Given proficiency $z$, write $f_j$ for the conditional probability or density of item $j$. Conditional independence gives their product $h_i(z;\theta)=\prod_j f_j(y_{ij}\mid z;\theta)$. Integrating this product against the density $p(z;\theta)$ of the latent variable gives the contribution $L_i(\theta)$ of person $i$ to the marginal likelihood. For $n$ independently sampled people, the likelihood is the product of these contributions, so its logarithm is

\[L_i(\theta)=\int \left\{\prod_j f_j(y_{ij}\mid z;\theta)\right\}p(z;\theta)\,dz, \qquad \ell(\theta)=\sum_{i=1}^n \log L_i(\theta).\]

For a discrete latent distribution with masses $\pi_k$ at mass points $z_k$, the integral becomes a sum. Each term has logarithm $\log\pi_k+\log h_i(z_k;\theta)$. Applying logsumexp() across points gives $\log L_i(\theta)$ for the entire response vector.

For the timetable and fare items, specify the log odds of success as $-0.4+0.7z$ and $0.3+1.1z$, respectively. Load the functions for the Bernoulli items and assign population masses 0.4 and 0.6 to proficiencies $-1$ and $+1$.

1
2
3
4
5
source("code/lib/stability.R")
source("code/lib/families.R")
source("code/lib/model_spec.R")
bernoulli <- resp_family("binomial")
latent <- finite_latent(matrix(c(-1, 1), 2, 1), c(0.4, 0.6))

Each row of point_eta contains the linear predictors of both items at one proficiency value. For each of the four possible pairs of answers, joint averages the conditional pattern probability over those two rows.

1
2
3
4
5
6
7
8
9
intercept <- c(-0.4, 0.3)
loading <- c(0.7, 1.1)
point_eta <- sweep(latent$points %*% t(loading), 2, intercept, "+")
families <- list(bernoulli, bernoulli)
patterns <- as.matrix(expand.grid(y1 = 0:1, y2 = 0:1))
joint <- apply(patterns, 1, function(y) {
  exp(logsumexp(log(latent$mass) + log_conditional(y, point_eta, families)))
})
print(data.frame(patterns, probability = round(joint, 6)))
1
2
3
4
5
  y1 y2 probability
1  0  0    0.257573
2  1  0    0.137106
3  0  1    0.297865
4  1  1    0.307455

The four patterns exhaust the possibilities and their unrounded probabilities sum to one. Summing the probabilities of the rows with a one in a given column gives that item’s marginal success probability.

1
2
3
4
means <- colSums(patterns * joint)
print(round(c(p1 = means[1], p2 = means[2], joint11 = joint[4],
              product_of_marginals = prod(means),
              covariance = joint[4] - prod(means)), 6))
1
2
3
4
               p1.y1                p2.y2              joint11 product_of_marginals 
            0.444561             0.605321             0.307455             0.269102 
          covariance 
            0.038353 

For two successes, the fourth row averages $p_1(z)p_2(z)$ over proficiency. The two marginal probabilities, 0.444561 and 0.605321, have product 0.269102. Yet the probability of two successes is 0.307455. Since the product of the binary scores is one precisely for two successes, the excess of 0.038353 is their covariance. For both items, the conditional probability of a correct answer is higher at the higher proficiency value. Averaging their conditional products over this shared trait makes two correct answers more frequent than marginal independence would predict.

Given those two correct answers, how likely is each proficiency? At fixed $\theta$, Bayes’ rule expresses this conditional distribution as a ratio. The population distribution of proficiency is called its prior distribution because it applies before this person’s answers are observed. Here $\theta$ is fixed; this calculation does not assign a prior distribution to $\theta$. For a continuous trait, divide the joint density at $z$ and the observed pair by the marginal probability of that pair. The posterior density is $h_i(z;\theta)p(z;\theta)/L_i(\theta)$ when $L_i(\theta)>0$. On finite support, let $a_{ik}=\log\pi_k+\log h_i(z_k;\theta)$. The numerator at point $k$ is now a joint probability, $e^{a_{ik}}$. Dividing by the sum over all possible points gives its posterior probability

\[w_{ik}=P(Z_i=z_k\mid Y_i=y_i;\theta) =\frac{e^{a_{ik}}}{\sum_r e^{a_{ir}}} =\exp\!\left\{a_{ik}-\log\sum_r e^{a_{ir}}\right\}.\]

To compute these posterior probabilities, normalize_logweights() takes the vector of log joint probabilities $a_{ik}$ and subtracts its largest entry. A common shift cancels in the ratio, and subtracting the log total on the shifted scale avoids subtracting two large, nearly equal numbers. Exponentiation returns probabilities that sum to one.

1
2
3
4
5
6
7
8
normalize_logweights <- function(a) {
  stopifnot(is.numeric(a), is.null(dim(a)), !anyNA(a))
  if (!length(a) || any(a == Inf) || all(a == -Inf)) {
    stop("Log weights must exclude NA and positive infinity and include a finite value", call. = FALSE)
  }
  shifted <- a - max(a)
  exp(shifted - logsumexp(shifted))
}

The input consists of logarithms of nonnegative weights. It must contain at least one finite entry and no missing value or positive infinity. The function therefore rejects an empty vector and a vector whose entries are all $-\infty$. An entry of $-\infty$ represents a weight of zero and receives probability zero after normalization, provided at least one other entry is finite. For two successes, the function normalizes the log joint probabilities of that pattern and each proficiency.

1
2
3
4
a11 <- log(latent$mass) + log_conditional(c(1, 1), point_eta, families)
posterior11 <- normalize_logweights(a11)
print(round(cbind(z = latent$points[, 1], prior = latent$mass,
                  posterior11 = posterior11), 6))
1
2
3
      z prior posterior11
[1,] -1   0.4    0.100731
[2,]  1   0.6    0.899269

Two correct answers raise the probability of the higher proficiency from 0.6 to 0.899269. Its numerator is $0.6p_1(+1)p_2(+1)$, and its denominator is the probability of the two-success pattern. A separate calculation uses extreme log weights.

1
print(round(normalize_logweights(c(-1000, -1001, -Inf)), 6))
1
[1] 0.731059 0.268941 0.000000

Subtracting the maximum $-1000$ gives $0$, $-1$ and $-\infty$. Their exponentials are proportional to $1$, $e^{-1}$ and zero, giving probabilities 0.731059, 0.268941 and zero.

The posterior changes with the item parameters and the population probabilities of the latent values because both enter the joint probabilities and their sum. At the specified values, posterior11 supplies the weights for predicting this person’s proficiency and another timetable answer. Assume the new answer is independent of the original two given proficiency, with the same item parameters.

1
2
print(round(c(expected_z = sum(posterior11 * latent$points[, 1]),
              new_item1_success = sum(posterior11 * plogis(point_eta[, 1]))), 6))
1
2
       expected_z new_item1_success 
         0.798538          0.541735 

Weighting $-1$ and $+1$ gives the posterior mean proficiency, 0.798538. Weighting the two first-item success probabilities gives 0.541735 for a correct new answer. Both predictions average over the person’s possible proficiency values. The marginal likelihood sums over those values without fitting a separate proficiency parameter for each person.

The function finite_marginal() applies both calculations to several people. Each row of the response matrix Y belongs to a person. Each row of the matrix eta of linear predictor values belongs to a mass point. Their columns follow the same item order.

1
2
3
4
5
6
7
8
9
10
11
12
finite_marginal <- function(Y, eta, families, latent) {
  stopifnot(is.matrix(Y), is.numeric(Y), is.matrix(eta),
            ncol(Y) == ncol(eta), nrow(eta) == length(latent$mass))
  log_lik <- numeric(nrow(Y))
  posterior <- matrix(NA_real_, nrow(Y), nrow(eta))
  for (i in seq_len(nrow(Y))) {
    a <- log(latent$mass) + log_conditional(Y[i, ], eta, families)
    log_lik[i] <- logsumexp(a)  # sum over points only after combining the responses
    posterior[i, ] <- normalize_logweights(a)
  }
  list(log_lik = log_lik, posterior = posterior)
}

For person i, a contains $a_{ik}$ at each mass point $k$: the conditional joint log probability or log density of the observed responses plus the log mass. Applying logsumexp() across points gives one entry of log_lik, $\log\sum_k e^{a_{ik}}$. Normalizing the same vector gives one row of posterior, the probabilities $w_{ik}$.

Suppose some people leave the fare question blank. For direct likelihood inference on $\theta$, assume the answers are missing at random. Among people with the same recorded answers, the chance of that missingness pattern cannot vary with what the unrecorded answers would have been. Also assume that any allowed value of the parameters governing missingness can be combined with any allowed value of $\theta$: neither set of parameter values restricts the other. This is the distinctness condition for the two sets of parameters in direct likelihood inference. For the posterior calculation, also assume that once the recorded answers are known, the missingness pattern gives no further information about proficiency.

Under these assumptions, an unobserved Bernoulli response sums out because its two conditional probabilities add to one at each proficiency. Only observed items therefore enter the product. With no answers, the empty product equals one at each proficiency, so the person’s contribution to the likelihood is one, its log is zero, and the posterior equals the prior. The same calculation applies to the four complete patterns and two incomplete records.

1
2
3
4
5
6
Y <- rbind(patterns, c(1, NA), c(NA, NA))
units <- finite_marginal(Y, point_eta, families, latent)
print(data.frame(y1 = Y[, 1], y2 = Y[, 2],
                 log_lik = round(units$log_lik, 6),
                 posterior_z_minus1 = round(units$posterior[, 1], 6),
                 posterior_z_plus1 = round(units$posterior[, 2], 6)))
1
2
3
4
5
6
7
  y1 y2   log_lik posterior_z_minus1 posterior_z_plus1
1  0  0 -1.356451           0.803903          0.196097
2  1  0 -1.987001           0.502718          0.497282
3  0  1 -1.211114           0.312356          0.687644
4  1  1 -1.179425           0.100731          0.899269
5  1 NA -0.810667           0.224707          0.775293
6 NA NA  0.000000           0.400000          0.600000

The last three rows show how losing answers changes the likelihood and posterior for one person. Two correct answers give posterior probability 0.899269 at $z=+1$ and log marginal likelihood $-1.179425$. With only the timetable success observed, that probability is 0.775293 and the log marginal likelihood is $-0.810667$. The blank fare answer allows either outcome on that item, so the person’s contribution to the likelihood adds the probabilities of the patterns $(1,0)$ and $(1,1)$. With both answers missing, the probability of the higher proficiency returns to 0.6, and the row contributes zero to the log likelihood for every $\theta$. The poLCA package fits finite latent class models by maximum likelihood.

1.5 Factor models, item response models, mixed models, and latent states

The same marginal-likelihood construction applies to different kinds of responses and latent variables. The five examples below use specified parameter values to show what is averaged over for each independent sampling unit. First, suppose each person provides two continuous scores. How much of their covariance could a single common factor explain? In the linear factor model, let $z$ have a standard normal distribution. For a given person, take the two scores to be $1+0.8z+\varepsilon_1$ and $0.6z+\varepsilon_2$. The factor loadings 0.8 and 0.6 give the increases in the respective expected scores for one standard deviation more of the common factor. Each loading is expressed in that score’s units per factor unit. The intercepts 1 and 0 give the expected scores at $z=0$.

The residuals $\varepsilon_1$ and $\varepsilon_2$ are the random differences between the scores and their conditional means. They are independent of each other and of $z$, with normal distributions of mean zero and variances 0.36 and 0.64. These residual variances are called the unique variances: the parts of each score’s variance that the common factor does not explain. They describe variation around each conditional mean in squared score units. The intercepts also give the population means because the factor and residuals have mean zero. Start R in the book directory. In response_cov, tcrossprod() multiplies the column of loadings by its transpose.

1
2
3
4
5
6
7
factor_model <- list(
  intercept = c(1, 0), loadings = matrix(c(0.8, 0.6), 2, 1),
  factor_cov = matrix(1), residual_cov = diag(c(0.36, 0.64)),
  constraint_description = "Factor mean zero, variance one, first loading positive")
# With unit factor variance, the outer product of the loadings gives the covariance due to the factor.
response_cov <- tcrossprod(factor_model$loadings) + factor_model$residual_cov
print(response_cov)
1
2
3
     [,1] [,2]
[1,] 1.00 0.48
[2,] 0.48 1.00

Only the common factor contributes to the off-diagonal entry, giving $0.8(0.6)\operatorname{Var}(z)=0.48$. Each diagonal entry also includes the score’s unique variance. For the first score, the total is $0.8^2+0.36=1$, and for the second it is $0.6^2+0.64=1$.

With dichotomous item scores, proficiency can instead change the log odds of success. In the two-parameter logistic (2PL) model for dichotomous items, let a person’s latent trait have a standard normal distribution, and let $p_j(z)$ be the probability of a correct answer to item $j$ when the trait equals $z$. At fixed $z$, the two responses are independent Bernoulli trials. The logit link function gives $\log[p_j(z)/(1-p_j(z))]=\beta_j+\lambda_j z$. The item intercept $\beta_j$ is the log odds of a correct answer at zero proficiency, the population mean on this scale. The discrimination $\lambda_j$ gives the change in those log odds for one standard deviation more proficiency. Both discriminations are positive here. The graph of $p_j(z)$ against proficiency is the item characteristic curve. It crosses probability one half where the log odds vanish. Solving $\beta_j+\lambda_j z=0$ gives the item difficulty $\delta_j=-\beta_j/\lambda_j$, expressed on the proficiency scale. The loading field below stores the two item discriminations.

1
2
3
4
item_model <- list(intercept = c(-0.4, 0.3), loading = c(0.7, 1.1),
  latent_mean = 0, latent_variance = 1,
  constraint_description = "Positive item slopes on the standard normal trait")
print(round(-item_model$intercept / item_model$loading, 6))
1
[1]  0.571429 -0.272727

The first item reaches probability one half at 0.571429. The second reaches it at $-0.272727$, so it requires less proficiency for the same chance of success.

When one person supplies a continuous measurement at each of three times, the dependence can arise from a shared trajectory. In a linear mixed model, let the random effects $b_{0i}$ and $b_{1i}$ be jointly normal deviations for person $i$, with mean zero and covariance matrix $G$. The person’s mean trajectory is $(2+b_{0i})+(0.4+b_{1i})t$. Its intercept is the expected measurement at time zero, and its slope is the change in that expectation per unit of time. The fixed effects 2 and 0.4 are the population means of these intercepts and slopes; $b_{0i}$ and $b_{1i}$ describe how an individual’s trajectory differs from them.

The diagonal entries of $G$ are the between-person variances of intercepts and slopes. The intercept variance is measured in squared response units. The slope variance is measured in the square of the slope’s units, response units per unit of time. The off-diagonal entry is their covariance: the positive value 0.15 used here associates higher initial levels with steeper increases. At time $t$, the row $(1,t)$ of random_design multiplies the two random effects. The normal measurement errors describe variation around each person’s trajectory, with mean zero and variance 0.49. They are independent across occasions and independent of the random effects. Thus $G$ describes differences between trajectories, whereas the residual variance describes variation around a given trajectory.

1
2
3
4
5
6
mixed_model <- list(time = c(0, 1, 2), beta = c(2, 0.4),
  G = matrix(c(1, 0.15, 0.15, 0.25), 2, 2), residual_variance = 0.49,
  constraint_description = "Random effects have mean zero; design is fixed")
random_design <- cbind(1, mixed_model$time)
print(random_design %*% mixed_model$G %*% t(random_design) +
        diag(mixed_model$residual_variance, 3))
1
2
3
4
     [,1] [,2] [,3]
[1,] 1.49 1.15 1.30
[2,] 1.15 2.04 1.95
[3,] 1.30 1.95 3.09

Of the two random effects, only the intercept enters at time zero. At time one, the random slope also enters with coefficient one. Thus the covariance across these times is $(1,0)G(1,1)^\top=1+0.15=1.15$. The residual variance adds 0.49 only along the diagonal, giving $1+0.49=1.49$ at time zero.

For the two dichotomous items, suppose a person belongs to class one with probability 0.4 or class two with probability 0.6. These class proportions describe population membership before a person’s answers are observed. In this latent class model, each class also has an item-response probability for each item: the chance of a correct answer among people in that class. Conditional on class, the answers are independent. Increasing an item-response probability makes success more common within that class. Changing the class proportions instead changes the population mixture of the two conditional response distributions, with the proportions still summing to one. Class labels distinguish categories; their numerical difference does not measure a difference in proficiency.

The mass field below stores the class proportions, and response_probability has one row per class and one column per item. To choose numerical probabilities for this example, use the item linear predictors at $-1$ and $+1$ and apply the inverse logit function to each entry. This supplies values for the example; the class model itself permits a separate response probability for every class and item. Load finite_latent() and construct the two rows before creating class_model.

1
2
3
4
5
source("code/lib/model_spec.R")
latent <- finite_latent(matrix(c(-1, 1), 2, 1), c(0.4, 0.6))
intercept <- c(-0.4, 0.3)
loading <- c(0.7, 1.1)
point_eta <- sweep(latent$points %*% t(loading), 2, intercept, "+")

Store the class proportions together with these response probabilities.

1
2
3
class_model <- list(mass = c(0.4, 0.6), response_probability = plogis(point_eta),
  constraint_description = "Class 1 has the smaller item-1 success probability")
print(round(class_model$response_probability, 6))
1
2
3
         [,1]     [,2]
[1,] 0.249740 0.310026
[2,] 0.574443 0.802184

In class one, the probabilities are 0.249740 for the first item and 0.310026 for the second. In class two, they are 0.574443 and 0.802184. Conditional independence makes the product of the second-row entries the probability of two successes given class two. Both item answers depend on the same class membership.

For a sequence of counts, suppose instead that the latent state can change between occasions. In this hidden Markov model, the initial probabilities 0.6 and 0.4 describe the chances of starting in states one and two. The current state determines the probabilities for the next state without further dependence on earlier states. The transition matrix uses the current state for its row and the next state for its column. Each row sums to one. Here the same matrix applies at every transition: from state one, the probabilities of staying and moving to state two are 0.8 and 0.2.

Given the path of states, the counts are independent. Each count has a Poisson distribution with its state’s rate. The rates 1 and 4 are the expected counts per observation occasion in states one and two, respectively. They determine the distribution of the observed count within a state; the initial and transition probabilities describe the unobserved state sequence. The fields initial, transition, and rate store these three parts of the model.

1
2
3
4
5
state_model <- list(initial = c(0.6, 0.4),
  transition = matrix(c(0.8, 0.3, 0.2, 0.7), 2, 2), rate = c(1, 4),
  constraint_description = "State 1 has the smaller Poisson rate")
print(list(initial = state_model$initial, transition = state_model$transition,
           rate = state_model$rate))
1
2
3
4
5
6
7
8
9
10
$initial
[1] 0.6 0.4

$transition
     [,1] [,2]
[1,]  0.8  0.2
[2,]  0.3  0.7

$rate
[1] 1 4

A path starting in state one and moving to state two has probability $0.6(0.2)=0.12$ for those two occasions. For counts $y_1$ and $y_2$, let $f_r(y)$ denote the Poisson probability of $y$ at rate $r$. This path then contributes $0.12 f_1(y_1)f_4(y_2)$ to the probability of the observed pair. The likelihood sums such joint probabilities over all possible paths. Mixing the states independently at each occasion would discard the transition probabilities.

The table separates each recorded response, observed_response, from its independent sampling unit, independent_unit. The latter determines which responses share a latent variable in the likelihood.

1
2
3
4
5
6
7
8
9
10
11
print(data.frame(model = c("linear factor model", "2PL item response model",
    "linear mixed model",
    "latent class model", "Poisson hidden Markov model"),
  independent_unit = c("person", "person", "person", "person", "sequence"),
  observed_response = c("continuous measurement", "dichotomous item score",
                        "repeated continuous measurement",
                        "dichotomous item response", "count at each occasion"),
  latent = c("factor", "trait", "random intercept and slope", "class", "state path"),
  operation = c("integrate over factor", "integrate over trait",
                "integrate over random effects",
                "sum over classes", "sum over state paths")))
1
2
3
4
5
6
7
8
9
10
11
12
                        model independent_unit               observed_response
1         linear factor model           person          continuous measurement
2     2PL item response model           person          dichotomous item score
3          linear mixed model           person repeated continuous measurement
4          latent class model           person       dichotomous item response
5 Poisson hidden Markov model         sequence          count at each occasion
                      latent                     operation
1                     factor         integrate over factor
2                      trait          integrate over trait
3 random intercept and slope integrate over random effects
4                      class              sum over classes
5                 state path          sum over state paths

The continuous scores, dichotomous item scores and repeated measurements in the first three rows each belong to a person. Their contributions to the likelihood integrate over a factor, a trait and a pair of random effects, respectively. The scores in the factor model and the repeated measurements in the mixed model are linear functions of normal latent variables plus independent normal errors. These are the two cases here in which integration gives a multivariate normal distribution in closed form. The fourth row sums over classes for one person’s dichotomous responses. For the first item alone, weighting the unrounded class probabilities gives $0.4\operatorname{logit}^{-1}(-1.1)+0.6\operatorname{logit}^{-1}(0.3)\approx0.444561$. In the last row, a single count belongs to one occasion, while a whole sequence contributes one sum over state paths. In table order, the corresponding R packages are lavaan, mirt, lme4, poLCA and depmixS4.

1.6 Identification of location, scale, rotation, and labels

Estimating a parameter requires that different values of it predict different responses. Could two different sets of item intercepts assign the same probability to every answer pattern? Identification asks whether the distribution of the observed responses uniquely determines the model parameters. If distinct allowed parameter values give exactly the same response distribution, observations cannot distinguish them.

Let the latent trait $Z$ have a free mean, and write the log odds for item $j$ at proficiency $z$ as $\beta_j+\lambda_j z$. The intercept remains the log odds at $z=0$, but zero need no longer represent average proficiency. Define a new origin by setting $Z^\ast =Z+c$ for some nonzero constant $c$. A person formerly at $z$ is now at $z+c$. With $\beta_j^\ast =\beta_j-\lambda_j c$, the new log odds are $\beta_j^\ast +\lambda_j(z+c)=\beta_j+\lambda_j z$. The items are conditionally independent given proficiency. Each conditional probability in the product for a person’s observed answers is therefore the same at the two corresponding trait values. The distribution used for averaging must move as well. For instance, a trait with distribution $N(0,1)$ now has distribution $N(c,1)$. Let $h_y(z)$ denote the conditional probability of pattern $y$ and $h_y^\ast $ its expression on the shifted scale. Giving $Z^\ast $ the distribution of $Z+c$ yields

\[E[h_y^*(Z^*)]=E[h_y^*(Z+c)]=E[h_y(Z)].\]

A different latent mean and different item intercepts therefore give the same pattern probabilities. The answers alone cannot locate zero proficiency.

To change the unit of proficiency, set $Z^\ast =dZ$ for $d\ne0$ and divide every loading by $d$. At $z^\ast =dz$, the product $(\lambda_j/d)z^\ast $ equals $\lambda_j z$. Use $d>0$ for an item model with positive discriminations. The rescaled trait has mean $dE[Z]$ and variance $d^2\operatorname{Var}(Z)$. Averaging the paired response probabilities under this rescaled distribution gives the original marginal distribution of the responses. Thus the item responses cannot determine both a free latent variance and the common scale of the discriminations.

A numerical example shows this loss of identification. Start R in the book directory. Begin with a standard normal trait and allow its mean and variance to change.

1
2
3
item_model <- list(intercept = c(-0.4, 0.3), loading = c(0.7, 1.1),
  latent_mean = 0, latent_variance = 1,
  constraint_description = "Positive item slopes on the standard normal trait")

The calculation pairs each original proficiency with its shifted or rescaled value and compares the resulting linear predictors of the items.

1
2
3
4
5
6
7
8
9
10
11
12
z_grid <- c(-1, 0, 1)
original_eta <- outer(z_grid, item_model$loading, "*") +
  matrix(item_model$intercept, 3, 2, byrow = TRUE)
shift <- 2
shifted_intercept <- item_model$intercept - item_model$loading * shift
shifted_eta <- outer(z_grid + shift, item_model$loading, "*") +
  matrix(shifted_intercept, 3, 2, byrow = TRUE)
scale <- 2
scaled_eta <- outer(scale * z_grid, item_model$loading / scale, "*") +
  matrix(item_model$intercept, 3, 2, byrow = TRUE)
print(c(shift_error = max(abs(shifted_eta - original_eta)),
        scale_error = max(abs(scaled_eta - original_eta))))
1
2
 shift_error  scale_error 
2.220446e-16 0.000000e+00 

With $c=2$, the first intercept becomes $-0.4-0.7(2)=-1.8$. At the new value $1$, its linear predictor is $-1.8+0.7=-1.1$, as it was at $-1$. With $d=2$, the second loading becomes $1.1/2=0.55$. At the new value $2$, its linear predictor is $0.3+0.55(2)=1.4$, as it was at $1$. Across both items, the largest discrepancy is about $2.2\times10^{-16}$ for the shift and zero for the rescaling.

With two common factors, the orientation of the axes can also vary. In a linear factor model, take their mean to be zero and their covariance to be the identity matrix. Let $\Lambda$ contain one row of loadings per response. Each loading gives the change in that response’s conditional mean for a one-unit increase in the corresponding factor with the other factor fixed. For an orthogonal matrix $Q$, set $z^\ast =Q^\top z$ and $\Lambda^\ast =\Lambda Q$. Then $\Lambda^\ast z^\ast =\Lambda z$, and the part of the response covariance matrix due to the factors satisfies $\Lambda^\ast \Lambda^{\ast \top}=\Lambda QQ^\top\Lambda^\top=\Lambda\Lambda^\top$. Leaving the residual covariance unchanged preserves the response covariance. For a multivariate normal factor vector with mean zero and identity covariance matrix, $Q^\top Z$ has the same normal distribution as $Z$. Averaging the conditional distribution of the responses over these factors therefore preserves the entire joint response distribution. To see what happens to individual loadings, rotate through $\pi/6$ radians.

1
2
3
4
5
Lambda <- matrix(c(0.8, 0.2, 0.6, 0, 0.9, 0.4), 3, 2)
angle <- pi / 6
Q <- matrix(c(cos(angle), sin(angle), -sin(angle), cos(angle)), 2, 2)
rotated <- Lambda %*% Q
print(max(abs(tcrossprod(Lambda) - tcrossprod(rotated))))
1
[1] 1.110223e-16

Write $C=\cos(\pi/6)$ and $S=\sin(\pi/6)$. R fills Lambda by columns, so its first two rows are $(0.8,0)$ and $(0.2,0.9)$. Multiplication by Q gives $(0.8C,-0.8S)$ and $(0.2C+0.9S,-0.2S+0.9C)$. The part of the covariance of responses one and two due to the factors is their inner product,

\[(0.8C)(0.2C+0.9S)+(-0.8S)(-0.2S+0.9C)=0.16(C^2+S^2)=0.16.\]

The terms involving $CS$ cancel. With independent residuals, 0.16 is also the covariance of responses one and two. The first loading moves from 0.8 to $0.8C\approx0.6928203$. The maximum difference across all covariance entries, $1.110223\times10^{-16}$, reflects rounding in the matrix products.

In a latent class model, suppose either class can be named first. The marginal probability of a person’s response pattern adds, over the classes, each class proportion times the conditional probability of the pattern in that class. Rebuild the two rows of item probabilities and their proportions in class_model.

1
2
3
4
5
6
7
source("code/lib/model_spec.R")
latent <- finite_latent(matrix(c(-1, 1), 2, 1), c(0.4, 0.6))
intercept <- c(-0.4, 0.3)
loading <- c(0.7, 1.1)
point_eta <- sweep(latent$points %*% t(loading), 2, intercept, "+")
class_model <- list(mass = c(0.4, 0.6), response_probability = plogis(point_eta),
  constraint_description = "Class 1 has the smaller item-1 success probability")

For two successes, the term for each row of P is the product of its two probabilities times its class proportion. Reversing both the rows and their proportions changes only the order of these terms.

1
2
3
4
5
6
7
8
permutation <- c(2, 1)
P <- class_model$response_probability
pi_class <- class_model$mass
prob11 <- sum(pi_class * P[, 1] * P[, 2])
# The same permutation reorders the class proportions and both conditional probabilities.
permuted11 <- sum(pi_class[permutation] *
                 P[permutation, 1] * P[permutation, 2])
print(round(c(original = prob11, permuted = permuted11), 6))
1
2
original permuted 
0.307455 0.307455 

Both sums give 0.307455 to six decimal places. The same reordering preserves the sum for every pattern. The table compares this relabeling with the three continuous transformations.

1
2
3
4
5
6
7
8
9
10
print(data.frame(transformation = c("location", "scale", "rotation", "class permutation"),
  parameter_before = c(item_model$intercept[1],item_model$loading[2],
                       Lambda[1,1],pi_class[1]),
  parameter_after = c(shifted_intercept[1],item_model$loading[2]/scale,
                      rotated[1,1],pi_class[2]),
  quantity = c("linear predictor for item 1 at original trait value -1",
               "linear predictor for item 2 at original trait value +1",
                 "covariance of responses 1 and 2", "probability of two successes"),
  before = c(original_eta[1, 1], original_eta[3, 2], tcrossprod(Lambda)[1, 2], prob11),
  after = c(shifted_eta[1, 1], scaled_eta[3, 2], tcrossprod(rotated)[1, 2], permuted11)))
1
2
3
4
5
6
7
8
9
10
     transformation parameter_before parameter_after
1          location             -0.4      -1.8000000
2             scale              1.1       0.5500000
3          rotation              0.8       0.6928203
4 class permutation              0.4       0.6000000
                                                quantity     before      after
1 linear predictor for item 1 at original trait value -1 -1.1000000 -1.1000000
2 linear predictor for item 2 at original trait value +1  1.4000000  1.4000000
3                        covariance of responses 1 and 2  0.1600000  0.1600000
4                           probability of two successes  0.3074554  0.3074554

The first two rows track the linear predictors of the items for people originally at $-1$ and $+1$, respectively. The third tracks a covariance between observed responses. In the fourth row, exchanging labels puts the mass 0.6 first in place of 0.4. Either order gives 0.3074554 for the joint probability of two successes. The ordering convention in class_model selects the labeling with the lower first-item probability in class one.

Identifying restrictions choose among equivalent representations. A fixed latent mean sets the origin, and a fixed positive variance sets the unit. Alternatively, use the first response to set the factor’s unit by fixing its loading to one. If its original loading $\lambda_1$ is nonzero, setting $Z^\ast =\lambda_1Z$ gives this restriction. The first response is then the marker variable, and its fixed loading is the marker loading. On this scale, the other loadings are the ratios $\lambda_j/\lambda_1$.

For several factors with mean zero and identity covariance matrix, select as many response rows as there are factors to form a square, nonsingular submatrix $T$ of the loading matrix. Require zeros above its diagonal and positive entries on the diagonal. Which orthogonal matrices $U$ give a rotated block $TU$ of the same form? First, the inverse of $T$ is lower triangular with positive diagonal entries, as is its product with $TU$. This product equals $U$. Second, $U^{-1}$ is lower triangular, but it equals the upper triangular matrix $U^\top$. Thus $U$ is diagonal. Orthogonality makes each diagonal entry have absolute value one, and positivity then gives $U=I$.

The linear predictors of a categorical response have a freedom of location of their own. For a categorical response with $K$ possible categories, the multinomial logit model assigns category $k$ probability $p_k=e^{\eta_k}/\sum_{r=1}^K e^{\eta_r}$, where $\eta_k$ is its linear predictor. A difference $\eta_k-\eta_r$ is the log probability ratio $\log(p_k/p_r)$ between categories $k$ and $r$. Thus the predictors determine category probabilities through their differences. Adding $a$ to every linear predictor gives

\[\frac{e^{\eta_k+a}}{\sum_r e^{\eta_r+a}}=\frac{e^a e^{\eta_k}}{e^a\sum_r e^{\eta_r}}=\frac{e^{\eta_k}}{\sum_r e^{\eta_r}}.\]

Fixing the linear predictor of a reference category at zero removes this freedom; each remaining predictor then gives the log probability ratio to that category. In a latent class model, class labels can still be permuted together with the corresponding proportions and item probabilities. The restrictions must suit the model and the available observations. A parameter value is locally identified if some neighborhood contains no distinct admissible value giving the same distribution of the observations. Removing these symmetries alone guarantees neither local nor global identification.

Identification and Fisher information

A continuous symmetry also leaves a mark on the Fisher information. In the unrestricted model, let $\theta(t)$ trace a smooth curve of equivalent parameter values with tangent $v=\theta^{\prime}(0)$ at $\theta_0=\theta(0)$. For instance, choosing $d=e^t$ varies the trait scale smoothly through its original value. Assume that the set of possible observations is the same along this curve. For each observation $y$ in that set, its log probability or log density $\log f(y;\theta(t))$ is constant along the curve. Let $s(y)$ be the gradient of this log probability or log density with respect to $\theta$, evaluated at $\theta_0$. This is the score vector for one person’s observations. The chain rule gives $s(y)^\top v=0$. If the score exists and has finite second moments, the expected Fisher information $I(\theta_0)=E_{\theta_0}[ss^\top]$ satisfies

\[I(\theta_0)v=E_{\theta_0}[s(s^\top v)]=0.\]

A nonzero tangent therefore makes the information singular. Exchanging class labels is discrete and need not give a tangent direction. If one parameter vector maximizes the likelihood, relabeling it to give a distinct admissible vector gives another maximum with the same likelihood. If the log likelihood is twice differentiable and the relabeling permutes parameter coordinates, it permutes the rows and columns of its Hessian, the matrix of second partial derivatives, together. Its eigenvalues are therefore unchanged. In the unrestricted two-item example, four item probabilities and one class proportion give five parameters. The four pattern probabilities sum to one and supply just three independent values. The displayed calculation shows that exchanging class labels leaves the pattern probabilities unchanged; it does not establish identification of this unrestricted two-item model.

Fixing a factor variance chooses the unit of the factor. By contrast, replacing a free positive variance $\sigma^2$ with the parameter $u=\log\sigma^2$ still permits every positive variance through $\sigma^2=e^u$. This change of parameter does not fix the factor’s unit. The lavaan package allows the factor scale to be set by a marker loading or a fixed variance.

1.7 Representing response families and checking simulated data

With the trait distribution and item parameters specified, what answers might the model generate for a new group of people? Run the following code from the book directory. The first three files define the numerical functions, response families, and model specification. The fourth provides the simulator. The object bernoulli describes one trial per response.

1
2
3
4
5
6
source("code/lib/stability.R")
source("code/lib/families.R")
source("code/lib/model_spec.R")
source("code/lib/simulation.R")

bernoulli <- resp_family("binomial")

A response family already evaluates the log probability or log density of an observation. To draw an observation from that same distribution, add_generator() attaches a function called generate. The outer function checks the family name. The inner function takes one finite linear predictor value per draw.

1
2
3
4
5
6
7
8
9
10
add_generator <- function(family) {
  name <- family$name
  dispersion <- family$dispersion
  trials <- family$trials
  if (!name %in% c("normal", "binomial", "poisson")) {
    stop("Unsupported response generator", call. = FALSE)
  }
  family$generate <- function(eta) {
    stopifnot(is.numeric(eta), all(is.finite(eta)))
    n <- length(eta)

For a normal response, the generating distribution has mean equal to the linear predictor and standard deviation equal to the square root of the specified variance. For a binomial response, qbinom() takes a uniform draw and returns a count from the specified number of trials at the given success probability. With one trial, it returns one when the draw exceeds the probability of failure. For a Poisson count, exponentiating the linear predictor gives the rate.

1
2
3
4
5
6
7
8
9
10
11
    switch(name,
      normal = rnorm(n, eta, sqrt(dispersion)),
      binomial = qbinom(runif(n), trials, plogis(eta)),
      poisson = {
        rate <- exp(eta)
        stopifnot(all(is.finite(rate)))
        rpois(n, rate)
      })
  }
  family
}

Attaching a generator to an unsupported family raises an error.

First draw two normal measurements, with means zero and one and a common variance of 0.25. The calls to RNGkind() and set.seed() specify the random number algorithms and their starting state.

1
2
3
4
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(101)
normal_generator <- add_generator(resp_family("normal", dispersion = 0.25))
print(round(normal_generator$generate(c(0, 1)), 6))
1
[1] -0.163018  1.276231

The measurements were $-0.163018$ at mean zero and $1.276231$ at mean one. The same family object can also evaluate their conditional log densities with log_probability_or_density().

The function simulate_latent_model() draws observations from a generalized linear latent variable model, with one independent person per row. It first draws the latent variables. For $n$ people and $q$ factors, E has $n$ rows and $q$ columns of independent standard normal draws. R’s chol() returns the upper triangular Cholesky factor $U$ of the positive definite covariance matrix $\Sigma$ of the latent variables, with $U^\top U=\Sigma$. A row multiplied on the right by $U$ has covariance $U^\top I U=\Sigma$. Adding the latent means shifts the columns without changing that covariance.

1
2
3
4
5
6
7
8
9
simulate_latent_model <- function(spec) {
  n <- nrow(spec$X)
  q <- ncol(spec$loadings)
  p <- nrow(spec$loadings)
  families <- lapply(spec$families, add_generator)
  E <- matrix(rnorm(n * q), nrow = n)
  # One row of simulated latent variable values per person.
  Z <- sweep(E %*% chol(spec$latent_cov), 2, spec$latent_mean, "+")
  eta <- spec$X %*% spec$beta + Z %*% t(spec$loadings)

The matrix eta of linear predictor values combines each person’s covariates and simulated latent variable values. For each of the $p$ responses, the loop passes one column of linear predictor values to the corresponding family. Fresh draws in each column make the responses conditionally independent given the covariates and latent variables.

1
2
3
4
5
6
7
8
  Y <- matrix(NA_real_, n, p)
  for (j in seq_len(p)) {
    Y[, j] <- families[[j]]$generate(eta[, j])
  }
  colnames(Y) <- paste0("y", seq_len(p))
  colnames(Z) <- paste0("z", seq_len(q))
  list(observed = Y, simulated_values = list(latent = Z, eta = eta))
}

The result stores the response matrix in observed. The simulated_values component stores the simulated values Z and the linear predictor values eta used to generate those responses. These values vary from person to person; the model parameters are stored in spec.

Before applying the latent-variable simulator, check the covariance transformation and sampling variation in a separate multivariate normal example. Consider three continuous measurements on 240 people. The population means are 0, 1 and $-1$, and the marginal variances are 1, 2 and 1.5. The off-diagonal entries of normal_cov give the covariances in the order of the measurement columns. Generating NORMAL3 uses 720 independent standard normal draws. R fills the first column with the first 240 draws. Multiplication by the Cholesky factor of the covariance matrix and addition of the means then determine every measurement.

1
2
3
4
5
6
7
8
normal_mean <- c(0, 1, -1)
normal_cov <- matrix(c(1, 0.4, 0.2, 0.4, 2, 0.3, 0.2, 0.3, 1.5), 3, 3)
R <- chol(normal_cov)
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(101)
E <- matrix(rnorm(240 * 3), nrow = 240)
NORMAL3 <- sweep(E %*% R, 2, normal_mean, "+")
colnames(NORMAL3) <- c("y1", "y2", "y3")

Resetting the algorithms and seed 101 reproduces the start of the sequence. The next three draws match the first three rows of the original first column before transformation.

1
2
3
4
5
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(101)
# The first three normals fill successive rows of the first column.
prefix <- rnorm(3)
print(data.frame(row = 1:3, first_draw = E[1:3, 1], replay = prefix))
1
2
3
4
  row first_draw     replay
1   1 -0.3260365 -0.3260365
2   2  0.5524619  0.5524619
3   3 -0.6749438 -0.6749438

The replay gives $-0.3260365$, $0.5524619$ and $-0.6749438$ to the displayed precision. The equality check uses the underlying values.

1
stopifnot(identical(prefix, E[1:3, 1]))

Replaying the draws gives a fixed dataset. How far might its means fall from the specified means? For independent people, the standard error of the sample mean in column $j$ is $\sqrt{\Sigma_{jj}/n}$. It measures how much that mean varies across samples of the same size.

1
2
print(round(data.frame(theory = normal_mean, sample = colMeans(NORMAL3),
                       se = sqrt(diag(normal_cov) / 240)), 6))
1
2
3
4
   theory    sample       se
y1      0  0.008553 0.064550
y2      1  0.833609 0.091287
y3     -1 -1.049091 0.079057

The second mean, 0.833609, lies about 1.82 standard errors below one. For the sample covariance $S_{jk}$, cov() centers both columns at their sample means and divides the sum of cross-products by $n-1$. With independent normal rows, its standard error is $\sqrt{(\Sigma_{jj}\Sigma_{kk}+\Sigma_{jk}^2)/(n-1)}$. Taking $j=k$ gives the standard error of a sample variance.

1
2
3
4
5
6
indices <- which(upper.tri(normal_cov, diag = TRUE), arr.ind = TRUE)
covariance_se <- sqrt((outer(diag(normal_cov), diag(normal_cov)) +
                         normal_cov^2) / 239)
print(data.frame(row = indices[, 1], column = indices[, 2],
  theory = normal_cov[indices], sample = round(cov(NORMAL3)[indices], 6),
  se = round(covariance_se[indices], 6)))
1
2
3
4
5
6
7
  row column theory   sample       se
1   1      1    1.0 0.892685 0.091478
2   1      2    0.4 0.268063 0.095067
3   2      2    2.0 1.858714 0.182956
4   1      3    0.2 0.160969 0.080272
5   2      3    0.3 0.140615 0.113705
6   3      3    1.5 1.087187 0.137217

The upper triangle lists all six distinct entries. The third sample variance is 1.087187, about three standard errors below 1.5. This difference concerns sampling variation. Exact checks instead concern the stated sample dimensions, response support and equality of replayed draws.

Now apply simulate_latent_model() to the timetable and fare items. Each of 400 people has an independent standard normal trait $z_i$. The two log odds are $-0.4+0.7z_i$ and $0.3+1.1z_i$. Both success probabilities rise with proficiency, so a group containing people of differing proficiency can show positive association even with independent answers at each given proficiency.

1
2
3
4
5
6
binary_spec <- model_spec(
  X = matrix(1, 400, 1), beta = matrix(c(-0.4, 0.3), 1, 2),
  loadings = matrix(c(0.7, 1.1), 2, 1),
  families = list(bernoulli, bernoulli),
  latent_mean = 0, latent_cov = matrix(1),
  constraint_description = "Standard normal trait and positive item slopes")

For this example, the L’Ecuyer-CMRG generator with seed 100107 supplies 201 starting states. A substream is a segment of the generator’s random number sequence. The call to nextRNGSubStream() advances to the starting state of the next such segment, and the list substream_states stores these starting states. The first supplies the displayed dataset, and the next 200 supply the replications.

1
2
3
4
5
6
7
8
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(100107)
substream_states <- vector("list", 201)
substream_states[[1]] <- .Random.seed
for (r in 2:201) {
  substream_states[[r]] <- parallel::nextRNGSubStream(substream_states[[r - 1]])
}
names(substream_states) <- c("display", paste0("replication_", 1:200))

Starting from the first state, the simulator draws all 400 traits, then 400 draws from the uniform distribution for the first item and 400 for the second. The two column means give the fractions of successes.

1
2
3
4
5
6
.Random.seed <- substream_states[[1]]
binary <- simulate_latent_model(binary_spec)
binary_stats <- function(Y) {
  c(mean_y1 = mean(Y[, 1]), mean_y2 = mean(Y[, 2]), covariance = cov(Y)[1, 2])
}
print(round(binary_stats(binary$observed), 6))
1
2
   mean_y1    mean_y2 covariance 
  0.397500   0.552500   0.045495 

In this group, the fractions are 0.3975 and 0.5525, with sample covariance 0.045495.

What value should the sample covariances approach on average? Write $p_j(z)$ for item $j$’s conditional success probability. Given $Z=z$, the expected product of the two responses is $p_1(z)p_2(z)$ by conditional independence. Integrating over the trait gives the chance of two successes. Subtract the product of the two marginal success probabilities to obtain the population covariance,

\[\operatorname{Cov}(Y_1,Y_2) =E[p_1(Z)p_2(Z)]-E[p_1(Z)]E[p_2(Z)].\]

To study sampling variation, the following loop generates 200 independent groups of 400. Replication $r$ starts at substream $r+1$ and contributes its two means and covariance to a single row. The statistics are also saved in data/derived/ch01/binary-replications.rds. To summarize those saved replications, skip this loop and continue with the summary code immediately after it.

1
2
3
4
5
6
7
recorded <- vector("list", 200)
for (r in 1:200) {
  assign(".Random.seed", substream_states[[r + 1]], envir = .GlobalEnv)
  replication <- simulate_latent_model(binary_spec)
  recorded[[r]] <- binary_stats(replication$observed)
}
replication_stats <- do.call(rbind, recorded)

The summary reads the saved statistics and gives each statistic’s average, standard deviation across datasets and empirical 2.5th and 97.5th percentiles. The Monte Carlo standard error measures the uncertainty of the average due to the finite number of replications.

1
2
3
4
5
6
replication_stats <- readRDS("data/derived/ch01/binary-replications.rds")
replication_sd <- apply(replication_stats, 2, sd)
replication_summary <- cbind(average = colMeans(replication_stats),
  dataset_sd = replication_sd, mcse = replication_sd / sqrt(200),
  t(apply(replication_stats, 2, quantile, probs = c(0.025, 0.975))))
print(round(replication_summary, 6))
1
2
3
4
            average dataset_sd     mcse     2.5%    97.5%
mean_y1    0.409950   0.023033 0.001629 0.364937 0.457500
mean_y2    0.561388   0.026264 0.001857 0.509812 0.612562
covariance 0.032634   0.012076 0.000854 0.011151 0.056795

For example, the middle 95 percent of the observed sample covariances runs from about 0.011 to 0.057. Comparing these summaries with the model requires the population values. To obtain them, integrate() averages each probability and their product against the standard normal density.

1
2
3
4
5
6
7
8
9
# Conditional independence gives E(Y1 Y2 | z) = p1(z) p2(z).
p1 <- function(z) plogis(-0.4 + 0.7 * z)
p2 <- function(z) plogis(0.3 + 1.1 * z)
normal_expectation <- function(f) {
  integrate(function(z) dnorm(z) * f(z), -Inf, Inf)$value
}
mu1 <- normal_expectation(p1)
mu2 <- normal_expectation(p2)
population_moments <- c(mu1, mu2, normal_expectation(function(z) p1(z) * p2(z)) - mu1 * mu2)

The object population_moments contains the response means and covariance. Each table row compares a replication average with its population value, dividing their difference by the Monte Carlo standard error of that average.

1
2
3
4
5
6
7
8
moments <- data.frame(statistic = colnames(replication_stats), people_per_dataset = 400L,
  datasets = nrow(replication_stats), population = population_moments,
    average = colMeans(replication_stats),
  dataset_sd = replication_sd,
    mcse_average = replication_sd / sqrt(nrow(replication_stats)))
moments$standardized_difference <- (moments$average - moments$population) /
  moments$mcse_average
print(moments, row.names = FALSE)
1
2
3
4
5
6
7
8
  statistic people_per_dataset datasets population    average dataset_sd mcse_average
    mean_y1                400      200 0.41087065 0.40995000 0.02303313 0.0016286883
    mean_y2                400      200 0.55986862 0.56138750 0.02626414 0.0018571552
 covariance                400      200 0.03343259 0.03263352 0.01207616 0.0008539137
 standardized_difference
              -0.5652715
               0.8178546
              -0.9357780

The population covariance is 0.03343259. The standard deviation of the 200 sample covariances, 0.01207616, describes the spread for a single group of 400. Dividing that spread by $\sqrt{200}$ gives 0.0008539, the estimated standard error of the average over 200 groups. The average covariance, 0.03263352, falls short of the population value by 0.94 Monte Carlo standard errors. For the first item, the average proportion is 0.409950 against a population probability of 0.410871, or 0.57 standard errors below it. For the second item, the average is 0.561388 against 0.559869, or 0.82 standard errors above it. Each comparison uses the standard error for its own column.

Exact reproduction requires each generated response matrix to equal its saved copy. The moment table includes numerical integrals, so the last check allows for numerical precision.

1
2
3
4
stopifnot(identical(NORMAL3, readRDS("data/simulated/ch01/NORMAL3.rds")),
  identical(binary$observed, readRDS("data/simulated/ch01/binary-observed.rds")),
  isTRUE(all.equal(moments,
    readRDS("data/derived/ch01/population-and-sample-moments.rds"))))

The observations and the generating specification are stored in separate files. Each observation row gives one person’s two answers.

1
2
3
observed <- readRDS("data/simulated/ch01/binary-observed.rds")
generating_model <- readRDS("data/simulated/ch01/binary-model.rds")
print(head(observed, 4))
1
2
3
4
5
     y1 y2
[1,]  1  1
[2,]  1  0
[3,]  0  0
[4,]  0  0

The first person answered both items correctly, the second only the first item, and the next two neither item.

1
print(generating_model[c("n", "intercept", "loading")])
1
2
3
4
5
6
7
8
$n
[1] 400

$intercept
[1] -0.4  0.3

$loading
[1] 0.7 1.1

The specification records 400 people, intercepts of $-0.4$ and 0.3, and loadings of 0.7 and 1.1. It also records this sample’s generator settings and substream. An estimator of the item model uses the observed response matrix. In a simulation study, parameter estimates can be compared with the parameter values used to generate the data. Predictions of individual latent values can be compared with the separately saved simulated latent values. The stats package provides the response distributions and parallel provides random number substreams.

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