Post

Stochastic estimation with high-dimensional latent variables

Estimating a model with several latent variables can require integration over too many combinations of their values for a direct calculation to be practical. Simulation offers a way to approximate the quantities needed to update the parameters. The updates then vary with the simulated draws as well as with the current estimates. A small change between updates may reflect that variation, and a larger change need not indicate progress toward a better fit. Stochastic estimation requires judging the precision of these simulated quantities alongside the movement of the parameter estimates. The chapter draws each examinee’s traits from their conditional distribution by Metropolis-Hastings updates and uses those draws in three estimation methods, Monte Carlo EM, stochastic EM and the Metropolis-Hastings Robbins-Monro algorithm, applied to simulated two- and three-factor samples.

14.1 Multidimensional item response models, multilevel factors, and crossed random effects

This section compares three ways that latent variables can connect observations: several traits shared by one person’s items, a group effect shared by different people, and crossed effects shared by ratings. The comparison shows which responses must be integrated together. The estimation routines developed in this chapter fit the multidimensional item model for independent examinees. The multilevel and crossed examples establish their likelihood structures; those two structures are not fitted by the supplied item routines.

Several traits for one examinee

The first examinee in the simulated sample IRT12D3 answered the first two items incorrectly and the third correctly. How does that combination enter the likelihood of a three-factor item response model? Let $Y_{ij}$ be the score on item $j$ for person $i$, coded 1 if the answer is correct and 0 otherwise. The person’s three traits form a vector $z_i$ with mean zero and identity covariance under a multivariate normal distribution. For item $j$, the intercept $d_j$ gives the log odds at zero on all traits, and the loading vector $a_j$ gives the change in log odds per unit increase in each trait with the others fixed. The success probability is $p_j(z)=1/\lbrace 1+\exp[-(d_j+a_j^\top z)]\rbrace $. At $z$, the first three answers have conditional probability $(1-p_1(z))(1-p_2(z))p_3(z)$ because the responses are conditionally independent.

The generating loadings for these items are $(0.8,0,0)$, $(0.2,0.9,0)$ and $(0.1,0.2,1)$. Thus only the first trait enters item 1, while a correct answer on item 3 can reflect all three. The nine remaining rows cycle through $(0.8,0.2,0.1)$, $(0.1,0.9,0.2)$ and $(0.2,0.1,1)$. The intercepts increase in equal steps from $-1$ to $1$.

With nonzero diagonal entries, the triangular pattern fixes the axes up to sign. The positive generating diagonal chooses a direction for each axis. In fitting, multidim_design() fixes the same zeros. The diagonal slopes start positive and each can take either sign during estimation. The zeros and sign convention address rotation and reflection of the factor axes; they do not by themselves establish identification of every item parameter from the response distribution.

Write $B_i(z)=\prod_{j=1}^{12}p_j(z)^{y_{ij}}\lbrace 1-p_j(z)\rbrace ^{1-y_{ij}}$ for the probability of person $i$’s twelve observed answers given $z$. With $q$ traits and standard normal density $\phi_q$, this person’s marginal probability is $m_i=\int B_i(z)\phi_q(z)\,dz$. For independent examinees the likelihood for the item parameters is $\prod_i m_i$.

The two-factor sample will make the person-by-person Metropolis-Hastings updates easier to inspect and support comparison with product quadrature. The three-factor sample will show how the estimation methods behave with an additional integration dimension. From the book directory, load the functions, set the random number generators and read the two simulated response matrices. Each has 500 rows and twelve columns. Seed 1401 generated the three-factor sample, IRT12D3, stored in data14$three. Seed 1402 generated new examinees and new responses using the first two loading columns for the two-factor sample.

1
2
3
4
5
6
7
for (file in c("stability","result","line_search","quasi_newton",
  "differentiation","dogleg","factored_secant",
  "simulation","logit","integration","mcmc","stochastic_items","inference","multidim_items"))
  source(paste0("code/lib/",file,".R"))
RNGkind("Mersenne-Twister","Inversion","Rejection")
data14 <- list(two = readRDS("data/source/ch14/IRT12-two.rds"),
  three = readRDS("data/source/ch14/IRT12-three.rds"))

A product quadrature rule for $m_i$ takes every combination of nodes from the one-dimensional standard normal rules. The weight on a combination is the product of its coordinate weights. The following calculation counts the combinations.

1
2
print(data.frame(nodes_per_axis=c(7,15,31),two_factors=c(7,15,31)^2,
  three_factors=c(7,15,31)^3))
1
2
3
4
  nodes_per_axis two_factors three_factors
1              7          49           343
2             15         225          3375
3             31         961         29791

At 15 nodes per axis, a third trait replaces each of the 225 pairs by 15 triples, giving 3,375 evaluations per examinee. The nodes and their weights are common to all examinees. What changes across examinees at a given node is the probability of the answers they actually gave.

Traits shared within groups

Now suppose the examinees belong to groups, such as students in the same classroom. Give person $i$ in group $g$ a scalar trait $z_{ig}=u_g+v_{ig}$. The shared effect $u_g$ is normal with mean zero and variance $\tau^2$. The individual deviations $v_{ig}$ are independent standard normal variables, independent of every group effect, and groups are independent. Fixing the deviation variance at one sets the unit of within-group differences. Choosing a positive slope for one item orients the trait so that higher values increase the chance of success on that item. Two people in the same group have distinct deviations but share the same $u_g$. Their trait covariance is therefore $\tau^2$. Observing one person’s answers can give information about the other person’s trait through the common effect.

For item $j$, the conditional log odds of success are $d_j+a_j(u_g+v_{ig})$. The intercept $d_j$ is the log odds at total trait zero, and the slope $a_j$ is the change in log odds for a one-unit increase in that trait. One unit is one within-group standard deviation. For a nonzero slope, the difficulty $-d_j/a_j$ is the total trait at which the success probability is one half. The variance $\tau^2$ describes between-group variation in the shared trait level, in squared trait units; it is not the conditional variance of a binary answer.

The grouped example generates ten people in each of 40 groups using the eight IRT8 slopes and difficulties. In the code, a contains the slopes, the difficulties are equally spaced from $-1.5$ to $1.5$, and d contains the corresponding intercepts, each equal to minus the slope times the difficulty. With seed 1403, draw one effect per group from a normal distribution with standard deviation 0.5. Adding a separate deviation for each person gives the traits used to draw the eight responses.

1
2
3
4
5
6
7
8
a <- c(.7,.9,1,1.1,1.2,.8,1.3,1)
d <- -a*seq(-1.5,1.5,length.out=8)
set.seed(1403)
group_id <- rep(1:40,each=10)
group_effect <- rnorm(40,sd=.5)
trait <- group_effect[group_id]+rnorm(400)
eta <- sweep(outer(trait,a),2,d,"+")
nested_Y <- matrix(as.numeric(runif(length(eta))<plogis(eta)),400)

Let $B_{ig}(t)$ denote the product of the eight observed response probabilities at trait $t$, and let $\phi$ be the standard normal density. Given $u$, integrating $B_{ig}(u+v)$ over the person’s deviation gives one pattern probability. These probabilities multiply for the ten people conditional on $u$. Writing $u=\tau s$ then gives the group probability as a single outer expectation over $s$,

\[P_g(\tau)=\int_{\mathbb R}\phi(s) \prod_{i=1}^{10}\left[\int_{\mathbb R}B_{ig}(\tau s+v)\phi(v)\,dv\right]ds.\]

The full likelihood multiplies the 40 group probabilities. Dividing the outer integrand by $P_g(\tau)$ gives the density of $s$ conditional on this group’s answers. In one_group(), the 21 nodes and weights from normal_rule() approximate both expectations. The 21-point rule is Gauss-Hermite quadrature for a standard normal expectation. The inner and outer calculations are numerical approximations, not exact group probabilities.

1
2
3
4
5
6
7
8
9
10
11
12
rule <- normal_rule(21L)
one_group <- function(data,group_sd) {
  conditional <- function(u) {
    predictor <- sweep(outer(u+rule$nodes,a),2,d,"+")
    terms <- data%*%t(-log1pexp(-predictor))+(1-data)%*%t(-log1pexp(predictor))
    sum(apply(sweep(terms,2,log(rule$weights),"+"),1,logsumexp))
  }
  logsumexp(log(rule$weights)+vapply(group_sd*rule$nodes,conditional,0.0))
}
print(c(group1_simulated_effect=group_effect[1],
  group1_log_probability=one_group(nested_Y[group_id==1,],.5),
  independent_person_log_probability=one_group(nested_Y[group_id==1,],0)))
1
2
3
4
           group1_simulated_effect             group1_log_probability 
                        -0.7041745                        -48.8962073 
independent_person_log_probability 
                       -48.8924397 

For group 1, $-0.70417$ is the effect drawn when the responses were generated. Both calls to one_group() use the same ten observed patterns. At the generating standard deviation of 0.5, their integrated log probability is $-48.89621$. At standard deviation zero, every outer node corresponds to $u=0$. The log probability is then $-48.89244$, higher by $0.00377$ for this group. Estimating the population standard deviation would use the log probabilities of all the groups.

For a given u, terms has a row per person and a column per deviation node. The two matrix products add the log probabilities for that person’s ones and zeros. Adding the log weights and calling logsumexp() across columns gives the log of each inner integral. Summing over people forms the log of their conditional product. The outer logsumexp() returns the logarithm of the weighted sum over group effects.

Effects shared by crossed ratings

When the same judges assess every performance, ratings can share a judge or a performance. Index judges by $g$ and performances by $h$, with one binary response $Y_{gh}$ per pair and an observed covariate $x_{gh}$. Given both sets of effects and the covariate, the log odds of a positive response are $\beta_0+\beta_1x_{gh}+u_g+v_h$. The intercept $\beta_0$ is the log odds at $x_{gh}=0$ and both effects zero. With the effects fixed, $\beta_1$ is the change in log odds per unit increase in the covariate. The judge effect $u_g$ shifts all ratings by that judge, and the performance effect $v_h$ shifts all ratings of that performance. Their variances describe variation between judges and between performances, respectively, in squared log-odds units.

The two known incidence matrices each have one unit entry per observation, selecting its $g$ and its $h$. Here expand.grid() lists all 20 by 15 pairs. With seed 1404, the covariate values are independent standard normal draws, and the independent centered normal effects have standard deviations 0.5 for $g$ and 0.4 for $h$. The intercept is $-0.4$ and the covariate coefficient is $0.8$. An incidence matrix is a known design matrix recording which effect belongs to each observation; its entries are not parameters to be estimated.

1
2
3
4
5
6
set.seed(1404)
incidence <- expand.grid(g=1:20,h=1:15)
x <- rnorm(nrow(incidence))
effects <- c(rnorm(20,sd=.5),rnorm(15,sd=.4))
eta_cross <- -.4+.8*x+effects[incidence$g]+effects[20+incidence$h]
crossed_y <- as.numeric(runif(length(x))<plogis(eta_cross))

The first 20 positions of effects belong to $g$, so 20+incidence$h selects the second effect. Given the covariate values and all 35 effects, the responses are independent Bernoulli draws. Each observed one enters through its success probability, and each zero through the complementary probability. Their product is the conditional probability of the 300 responses. The first two rows select different judges and the same performance.

1
print(head(data.frame(incidence,x,eta=eta_cross,y=crossed_y)))
1
2
3
4
5
6
7
  g h         x         eta y
1 1 1 0.2934974 -0.04380551 1
2 2 1 1.1657931  0.36138395 1
3 3 1 0.1705177 -0.32346356 0
4 4 1 1.7704730  0.80011637 1
5 5 1 1.9210163  0.69694227 1
6 6 1 1.7585230  0.87029377 1

Judges 1 and 2 both gave performance 1 a positive rating. Their rows therefore share $h=1$. For each row, average its success probability over its own $g$ effect at a fixed $v_1=v$, and call the two resulting probabilities $s_1(v)$ and $s_2(v)$. The marginal probability of two positive ratings at the observed covariate values is $E[s_1(v_1)s_2(v_1)]$. Both probabilities increase with the same nondegenerate $v_1$, giving positive covariance. Multiplying their separate marginal probabilities would lose that dependence. Grouping all rows by $h$ would still leave the same $g$ effects in different groups of rows. Every $g$ occurs with every $h$, so the marginal probability integrates the response product over all 35 effects in one connected design. Given the ratings and covariate values, the joint conditional density of the effects is proportional to that response product times the 35 normal densities.

Conditional trait densities for independent examinees

Return now to the independent examinees whose item parameters will be fitted below. The only latent variables shared by one person’s items are the $q$ coordinates of $z$. With item parameters fixed, conditioning on the observed row $y_i$ gives density $f(z\mid y_i)=B_i(z)\phi_q(z)/m_i$. Taking logs turns the item product into a sum. For the linear predictor $\eta_j(z)=d_j+a_j^\top z$, the log probability of one observed answer is $y_{ij}\eta_j(z)-\log\lbrace 1+\exp(\eta_j(z))\rbrace $. The normal trait density supplies the quadratic term, giving

\[\log f(z\mid y_i)= \sum_{j=1}^{12}\left[y_{ij}\eta_j(z)-\log\{1+\exp(\eta_j(z))\}\right] -\tfrac12 z^\top z+C_i .\]

Here $C_i=-\tfrac{q}{2}\log(2\pi)-\log m_i$ has the same value at any two candidate trait vectors for this person. In the first Metropolis-Hastings sweep, each row of data14$two has its own two-dimensional conditional trait density. The intended transition for that row targets this density with the twelve responses and the item parameters fixed. A conditional distribution for a latent trait does not include uncertainty from estimating those coefficients.

The supplied multidim_* functions of this chapter are translated from parts of mirt (its EM, Monte Carlo EM, stochastic EM and Metropolis-Hastings Robbins-Monro routines; code/NOTICE.md), in which multidimensional item response models are available.

14.2 Metropolis-Hastings updates for conditional latent distributions

Two trait vectors could explain the same examinee’s answers. Markov chain Monte Carlo (MCMC) approximates expectations under a target distribution by averaging functions of states visited by a Markov chain. Here the target is the conditional trait distribution at fixed item coefficients. How often should a simulation move between the two vectors in each direction?

A transition kernel assigns probabilities to possible next states conditional on the present state. Let $\pi(x)$ denote the target density at state $x$. The target is stationary if a current state drawn from it gives a next state with that same distribution. A proposal from $x$ has density $g(w\mid x)$ at candidate $w$. Let $\alpha(x,w)$ be the probability of accepting it. For distinct states, the joint density of starting at $x$ under the target and moving to $w$ is $\pi(x)g(w\mid x)\alpha(x,w)$. Detailed balance requires this flow to equal its reverse. Accept all proposals in the direction with the smaller proposed flow. In the other direction, accept the fraction needed to match it. For a proposal drawn from $x$ with positive forward flow, the resulting Metropolis-Hastings (MH) probability is

\[\alpha(x,w)=\min\!\left\{1,\frac{\pi(w)g(x\mid w)} {\pi(x)g(w\mid x)}\right\}.\]

Multiplying by the forward flow gives $\min\lbrace \pi(x)g(w\mid x),\pi(w)g(x\mid w)\rbrace $, the same in either direction. The remaining probability remains at the starting state. Integrating over pairs of states on opposite sides of any region shows that as much probability enters as leaves. Its total probability is therefore unchanged.

A normal random walk proposes $w=x+\epsilon$, where the increment $\epsilon$ has mean zero and fixed positive definite covariance. The increments $w-x$ and $x-w$ have equal normal density, so the reverse and forward proposal terms cancel. Write $\Delta=\log\pi(w)-\log\pi(x)$ and draw an independent uniform $U$ between zero and one. Accept if $\log U<\min(0,\Delta)$. Since $\log U$ is negative with probability one, comparing it directly with $\Delta$ gives the same decision. A proposal with higher target density is accepted. A proposal with lower density still has probability $\exp(\Delta)$ of acceptance. On rejection, record $x$ as the next draw. Dropping that repeated value would omit the time the chain spends at $x$ while waiting for an accepted move.

For person $i$, let $B_i(z)$ be the product of the twelve probabilities for the observed answers at trait vector $z$ and let $\phi_q$ be the standard normal density in $q$ dimensions. At fixed item slopes and intercepts, the conditional density is $\pi_i(z)=B_i(z)\phi_q(z)/m_i$, where $m_i$ is the marginal probability of those answers. Moving from $x$ to $w$ compares the same examinee twice. The denominator $m_i$ therefore cancels. The symmetric proposal leaves the log ratio

\[\Delta_i=\log B_i(w)-\log B_i(x)-\tfrac12(w^\top w-x^\top x).\]

The quadratic term penalizes a move farther from the population mean. Even if the answers are more probable at $w$, that term can lower the chance of moving there. Multiplying the accepted flow by $m_i$ gives $g(w\mid x)\min\lbrace B_i(x)\phi_q(x),B_i(w)\phi_q(w)\rbrace $. Interchanging the vectors gives the same expression, establishing detailed balance for the stated conditional density.

A trait update for each examinee

To update a matrix of traits, make one decision per examinee. Run the item example from the book directory with the following functions and random number settings.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
source("code/lib/dogleg.R")
source("code/lib/factored_secant.R")
source("code/lib/simulation.R")
source("code/lib/logit.R")
source("code/lib/integration.R")
source("code/lib/mcmc.R")
source("code/lib/stochastic_items.R")
source("code/lib/inference.R")
source("code/lib/multidim_items.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")

The response matrix and restrictions enter the calculation through multidim_design(Y, q). Its Y has one row per examinee and one column per item. The matrix pattern marks the allowed loadings, and is_free identifies the entries of the separate parameter vector that are estimated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
multidim_design <- function(Y, q) {
  Y <- as.matrix(Y)
  stopifnot(nrow(Y) > 0L, ncol(Y) > 0L, !anyNA(Y), all(Y %in% 0:1),
    length(q) == 1L, is.finite(q), q == as.integer(q), q >= 1L, q <= ncol(Y))
  J <- ncol(Y)
  indicators <- matrix(0, nrow(Y), 2L * J)
  for (j in seq_len(J)) {
    indicators[, 2L * j - 1L] <- as.numeric(Y[, j] == 0)
    indicators[, 2L * j] <- as.numeric(Y[, j] == 1)
  }
  pattern <- 1L * (row(matrix(0, J, q)) >= col(matrix(0, J, q)))
  is_free <- unlist(lapply(seq_len(J), function(j) c(pattern[j, ] == 1L, TRUE, FALSE, FALSE)))
  group_est <- rep(FALSE, q + q * (q + 1L) / 2L)
  list(Y = Y, indicators = indicators, N = nrow(Y), J = J, q = q, pattern = pattern,
    is_free = c(is_free, group_est), item_length = q + 3L)
}

The vector par_vec contains one block of q + 3 entries per item, followed by the fixed group parameters. For item $j$, the block has the following correspondence.

Position within the item blockMeaning
1:qSlopes $a_{j1},\ldots,a_{jq}$, with zeros where pattern[j, ] is zero
q + 1Intercept $d_j$
q + 2, q + 3Fixed lower and upper asymptote logits, -999 and 999

The probability helper maps these two extreme logits to zero and one, giving the specified two-parameter logistic (2PL) response model. After the item blocks, the group entries are the zero trait means and the lower triangle of the identity covariance; all are fixed. In indicators, columns 2*j-1 and 2*j mark response zero and response one on item $j$. Binary responses and positive, compatible dimensions are assumed; the design constructor does not provide a general missing-response treatment.

The next two functions evaluate one joint log density per person and use it for an MH update of that person’s entire trait vector. They obtain the response probabilities from multidim_category_probabilities().

1
2
3
4
5
6
7
8
9
multidim_category_probabilities <- function(par_vec, design, Theta) {
  out <- matrix(0, nrow(Theta), 2L * design$J)
  for (j in seq_len(design$J)) {
    P <- multidim_item_probability(multidim_item_par(par_vec, design, j), Theta)
    out[, 2L * j] <- P
    out[, 2L * j - 1L] <- 1 - P
  }
  out
}

For each row of Theta, columns $2j-1$ and $2j$ contain the probabilities of 0 and 1 on item $j$; multidim_item_par() extracts the item’s coefficients and multidim_item_probability() evaluates its success probability at every trait vector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
multidim_complete_loglik <- function(theta, par_vec, design) {
  q <- design$q
  log_den <- multidim_normal_log_density(theta[, seq_len(q), drop = FALSE], rep(0, q), diag(q))
  rowSums(design$indicators * log(multidim_category_probabilities(par_vec, design, theta))) + log_den
}

multidim_draw_traits <- function(theta0, par_vec, design, proposal_variance) {
  unif <- runif(design$N)
  k <- ncol(theta0)
  step_var <- if (k == 1L) matrix(proposal_variance) else diag(rep(proposal_variance, k))
  first_call <- is.null(attr(theta0, "log.lik_full"))
  ll_old <- multidim_complete_loglik(theta0, par_vec, design)
  # The proposal is drawn on every call (the random numbers stay in step); on the first
  # call the traits stay where they are and only their log densities are stored.
  theta1 <- theta0 + multidim_normal_draws(design$N, sigma = step_var)
  if (first_call) theta1 <- theta0
  attributes(theta1) <- attributes(theta1)["dim"]
  ll_new <- multidim_complete_loglik(theta1, par_vec, design)
  if (first_call) return(structure(theta1, log.lik_full = ll_new))
  # Metropolis-Hastings: a person is moved when log(u) < new - stored log density;
  # a rejected person keeps the traits and the stored log density.
  rejected <- !(log(unif) < ll_new - ll_old)
  theta1[rejected, ] <- theta0[rejected, ]
  ll_new[rejected] <- ll_old[rejected]
  # Attributes: the proportion accepted, the summed and the personwise log densities.
  structure(theta1, "Proportion Accepted" = sum(!rejected) / design$N,
    log.lik = sum(ll_new), log.lik_full = ll_new)
}

The function multidim_category_probabilities() returns probabilities in the same column order as indicators. Multiplying their logarithms by the indicators selects the observed log probabilities in multidim_complete_loglik(). multidim_normal_log_density() takes trait vectors in rows, a mean vector and a covariance matrix, and returns one normal log density per row. Summing the selected response log probabilities and adding that normal log density gives $\log B_i(z)+\log\phi_q(z)$. The response calculation bounds each linear predictor between $-35$ and $35$; this is a numerical approximation to the logistic response function. The quadratic normal term continues to decrease in the tails. The displayed sum is thus the bounded implementation of the joint log density, not the exact expression in Section 14.1.

In multidim_draw_traits(), theta0 has one row per examinee, par_vec contains the fixed model parameters, and proposal_variance is the proposal variance $v$ for each coordinate. The function draws all uniforms first. It then calls multidim_normal_draws() to draw an independent normal increment with covariance $vI_q$ for each row. This helper returns an examinee-by-trait matrix, using a symmetric square root of the supplied covariance to transform standard normal draws. If the input has no stored log densities, the call has already consumed both sets of random numbers when it restores the input points. It evaluates those points, stores one log density per person in log.lik_full and returns. On every subsequent call, ll_old is recalculated for the current row at par_vec. The difference ll_new - ll_old compares its proposal with that row under the same item parameters. For a rejected row, the two assignments indexed by rejected restore both the whole trait vector and its corresponding log density. For an accepted row, both values come from the proposal. Dividing the number of accepted rows by the number of people gives the acceptance fraction.

An exact check with three states

A separate finite-state calculation checks the proposal ratio exactly in three states. Set their target probabilities to 0.2, 0.3 and 0.5. From any starting state, propose destinations with probabilities 0.6, 0.3 and 0.1. Row $i$ of P gives the distribution after one step from $i$. The off-diagonal entries multiply proposal probability by acceptance probability. Putting the remaining probability on the diagonal counts every way of staying in place.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
target <- c(.2,.3,.5); proposal <- c(.6,.3,.1)
transition <- function(correct) {
  P <- matrix(0,3,3)
  for(i in 1:3) for(j in setdiff(1:3,i)) {
    ratio <- target[j]/target[i]
    if(correct) ratio <- ratio*proposal[i]/proposal[j]
    P[i,j] <- proposal[j]*min(1,ratio)
  }
  diag(P) <- 1-rowSums(P)
  P
}
print(lapply(c(correct=TRUE,omitted=FALSE),function(correction) {
  P <- transition(correction)
  list(P=P,flow=target*P,stationarity_error=drop(target%*%P)-target)
}))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$correct
$correct$P
     [,1] [,2] [,3]
[1,] 0.60 0.30  0.1
[2,] 0.20 0.70  0.1
[3,] 0.04 0.06  0.9

$correct$flow
     [,1] [,2] [,3]
[1,] 0.12 0.06 0.02
[2,] 0.06 0.21 0.03
[3,] 0.02 0.03 0.45

$correct$stationarity_error
[1] 0.000000e+00 5.551115e-17 0.000000e+00


$omitted
$omitted$P
     [,1] [,2] [,3]
[1,] 0.60 0.30 0.10
[2,] 0.40 0.50 0.10
[3,] 0.24 0.18 0.58

$omitted$flow
     [,1] [,2] [,3]
[1,] 0.12 0.06 0.02
[2,] 0.12 0.15 0.03
[3,] 0.12 0.09 0.29

$omitted$stationarity_error
[1]  0.16  0.00 -0.16

From state 3, the corrected rule accepts a proposal to state 1 with probability $(0.2\times0.1)/(0.5\times0.6)=1/15$. Multiplying by the proposal probability 0.6 gives the transition probability 0.04. The two flows are $0.2(0.10)=0.02$ and $0.5(0.04)=0.02$. The largest absolute stationarity error is below $5.6\times10^{-17}$. Omitting the proposal ratio changes the distribution after one step to $(0.36,0.30,0.34)$, obtained by summing the columns of omitted$flow. The direct net flow from 3 to 1 is $0.12-0.02=0.10$. The additional $0.06$ entering state 1 comes from its net exchange with state 2.

One sweep through the two-factor responses

Return to the observed two-factor item responses to inspect one MH sweep with two coordinates per examinee. The function multidim_start() sets each free slope to $0.5\times1.702$ and each fixed slope to zero. For item $j$, let $p_{0j}$ be its observed proportion of zeros and let $h_{jk}$ be 0.5 where pattern[j,k] is one and zero otherwise. The starting intercept is

\[s_j=\sqrt{\left|1-\sum_k h_{jk}^2\right|},\qquad d_j=-\frac{\Phi^{-1}(p_{0j})}{\max(s_j,0.25)/1.702}.\]

Here $\Phi^{-1}$ is the standard normal quantile function evaluated by qnorm(). Thus start2 contains starting values computed from the observed responses, with the fixed asymptote and group entries appended. Fix these item parameters, set both trait coordinates to zero for all 500 people and use proposal variance $v=1$. At seed 1412 the two calls initialize the densities and perform one sweep. For an item answered identically by every examinee, the observed proportion of zeros is either 0 or 1, producing an infinite normal quantile here. The absolute value and lower bound in this starting-value rule are numerical conventions, not estimates of a residual variance. The rule is multidim_start() in code/lib/multidim_items.R.

1
2
3
4
5
6
7
8
9
10
11
12
multidim_start <- function(design) {
  free <- design$pattern == 1L  # standardized loadings .5 where estimated, else 0
  resid_sd <- sqrt(abs(1 - rowSums(ifelse(free, .5, 0)^2)))
  slope <- ifelse(free, .5 * 1.702, 0)
  one_item <- function(j) {
    p0 <- mean(design$indicators[, 2L * j - 1L])  # proportion of responses 0
    scale <- (if (resid_sd[j] > .25) resid_sd[j] else .25) / 1.702
    c(slope[j, ], -qnorm(p0) / scale, -999, 999)
  }
  group <- diag(design$q)
  c(unlist(lapply(seq_len(design$J), one_item)), rep(0, design$q), group[lower.tri(group, TRUE)])
}

Each estimated loading starts at the standardized value 0.5, which becomes the slope $0.5\times1.702=0.851$ on the logistic scale. For item $j$, the intercept is $-\Phi^{-1}(p_{0j})$ divided by the residual standard deviation $\lbrace 1-\sum0.5^2\rbrace ^{1/2}$ (at least 0.25) over 1.702, where $p_{0j}$ is the proportion of zeros. The values $-999$ and 999 are the fixed asymptote entries, and the group means start at zero with identity covariance.

1
2
3
4
5
6
7
8
9
10
Y <- readRDS("data/source/ch14/IRT12-two.rds")
design2 <- multidim_design(Y, 2L)
start2 <- multidim_start(design2)
set.seed(1412)
theta0 <- multidim_draw_traits(matrix(0,design2$N,2L),start2,design2,1)
theta1 <- multidim_draw_traits(theta0,start2,design2,1)
print(data.frame(person=1:5,before1=theta0[1:5,1],before2=theta0[1:5,2],
  after1=theta1[1:5,1],after2=theta1[1:5,2],
  log_density_before=attr(theta0,"log.lik_full")[1:5],
  log_density_after=attr(theta1,"log.lik_full")[1:5]))
1
2
3
4
5
6
7
8
9
10
11
12
  person before1 before2     after1      after2 log_density_before
1      1       0       0  0.0000000  0.00000000          -9.851583
2      2       0       0  0.0000000  0.00000000          -9.884433
3      3       0       0  0.2518142 -0.87317261          -8.915944
4      4       0       0  0.3078544 -0.38507387          -8.472188
5      5       0       0 -1.1591560 -0.07222615          -8.915944
  log_density_after
1         -9.851583
2         -9.884433
3         -7.760403
4         -8.634081
5         -6.775559

Persons 1 and 2 remained at zero and persons 3 through 5 moved. For person 4 the proposed pair $(0.30785,-0.38507)$ reduced the log density from $-8.472188$ to $-8.634081$. Its acceptance probability was $\exp(-8.634081+8.472188)\approx0.851$. The move was accepted because this person’s uniform fell below that value. How many proposals were accepted across the sample?

1
print(c(proportion_accepted=attr(theta1,"Proportion Accepted")))
1
2
proportion_accepted 
              0.394 

The fraction $0.394$ corresponds to 197 accepted vectors among 500 examinees, each conditional on that person’s own answers. The argument named proposal_variance supplies the variance per coordinate: the proposal code takes its square root before generating normal increments. The name must not be read as a standard deviation.

Chains for two scalar targets

Two scalar target distributions provide independent checks on what a chain estimates. The following calculation runs on its own from the book directory.

The normal target has mean 2 and variance 0.7. For the second target, the six RI1 responses in cy share a random intercept $b$. At the observed covariate values in cx their success probabilities are $\operatorname{logit}^{-1}(-0.4+0.8x+b)$. The coefficient $-0.4$ is the log odds at $x=0$ and $b=0$, and $0.8$ is the change per unit of $x$ at fixed $b$. The shared intercept shifts all six log odds by the same amount. Its prior distribution is $b\sim N(0,0.7^2)$, so 0.7 is its standard deviation in log-odds units. To find its conditional moments, multiply its normal density by the six observed response probabilities and integrate after multiplying by $1$, $b$ or $b^2$.

1
2
3
4
5
6
7
8
9
10
11
12
source("code/lib/mcmc.R")
cx<-c(-1,-.5,0,.5,1,1.5);cy<-c(0,0,1,0,1,1)
targets<-list(normal=function(z)dnorm(z,2,sqrt(.7),log=TRUE),
 RI=function(z)sum(dbinom(cy,1,plogis(-.4+.8*cx+z),log=TRUE))+dnorm(z,0,.7,log=TRUE))
max_log_joint_ri <- optimize(targets$RI,c(-10,10),maximum=TRUE)$objective
moments <- lapply(0:2,function(k) integrate(function(z)
  vapply(z,function(v) v^k*exp(targets$RI(v)-max_log_joint_ri),0.0),-Inf,Inf,rel.tol=1e-10))
raw <- vapply(moments,`[[`,0.0,"value")
first <- raw[2]/raw[1]; second <- raw[3]/raw[1]
reference <- data.frame(target=c("normal","RI"),mean=c(2,first),second=c(.7+2^2,second),
  variance=c(.7,second-first^2))
print(reference)

The optimizer stores the maximum value of the log joint density in max_log_joint_ri. Subtracting that maximum multiplies all three integrals by the same constant, which cancels when the second and third integrals are each divided by the first. Subtracting the squared conditional mean from the second moment gives the variance. The rel.tol argument requests relative integration tolerance.

For these responses, the reference mean, second moment and variance are 0.07699, 0.30750 and 0.30158. The corresponding normal values are 2, 4.7 and 0.7.

To sample either target, mh_step() takes a current state, a function giving the log target density and a function proposing a candidate from the current state. Its optional log_proposal takes the destination first and the origin second. The difference between reverse and forward log proposal densities is zero for the fixed symmetric proposals used here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mh_step <- function(current, log_target, propose, log_proposal = NULL) {
  proposed <- propose(current)
  from <- log_target(current)
  if (!is.finite(from)) stop("The current state is outside the target support")
  to <- log_target(proposed)
  correction <- if (is.null(log_proposal)) 0 else
    log_proposal(current,proposed) - log_proposal(proposed,current)
  log_ratio <- to - from + correction
  if (is.na(log_ratio) || log_ratio == Inf) stop("Invalid proposal or target density")
  uniform <- runif(1)
  accept <- log(uniform) < min(0,log_ratio)
  list(state=if (accept) proposed else current,accepted=accept,proposal=proposed,
    log_target_change=to-from,log_proposal_correction=correction,uniform=uniform)
}

Select the L’Ecuyer-CMRG generator before setting seed 140214. Use a distinct stream for each chain. For each target, start four chains at $-2$, $-0.5$, $0.5$ and $2$. The proposal standard deviation is 1 for the normal target and 0.6 for the random intercept. The 500 pilot draws advance each chain from its starting point. resume_mcmc() continues from the pilot’s last state and random number state; Section 14.3 shows it with mcmc() and batch_means_mcse(). Only its 8,000 new draws enter the summaries.

The Monte Carlo standard error (MCSE) describes simulation uncertainty in an approximate expectation, with the observed data and target fixed. It differs from the conditional spread of the random intercept and from the sampling standard error of an estimated model coefficient. To estimate the MCSE of a chain mean, batch_means_mcse() divides the retained draws into consecutive batches and uses the variation between their means. Batches must be long enough to account for dependence between successive draws; 14.3 gives the calculation and its assumptions. For the variance, apply the same method to squared deviations from the chain mean. This gives an asymptotic assessment of variance estimation, not an exact finite-run standard error. Squaring the draws instead gives the MCSE for the second moment.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
set.seed(140214);stream<-.Random.seed
rows<-list()
for(nm in names(targets))for(i in 1:4){
 assign(".Random.seed",stream,.GlobalEnv);stream<-parallel::nextRNGStream(stream)
 scale<-if(nm=="normal")1 else .6
 transition<-function(z)mh_step(z,targets[[nm]],function(x)x+rnorm(1,sd=scale))
 pilot<-mcmc(c(-2,-.5,.5,2)[i],transition,500L)
 chain<-resume_mcmc(pilot,transition,8000L)
 z<-unlist(chain$draws)
 for(size in c(50L,100L,200L))rows[[length(rows)+1L]]<-data.frame(target=nm,
   chain=i,batch=size,
   mean=mean(z),mean_MCSE=batch_means_mcse(z,size)$mcse,variance=var(z),
   variance_MCSE=batch_means_mcse((z-mean(z))^2,size)$mcse,
   second_moment=mean(z^2),second_MCSE=batch_means_mcse(z^2,size)$mcse,
   exact_mean=reference$mean[reference$target==nm],
   exact_variance=reference$variance[reference$target==nm],
   exact_second=reference$second[reference$target==nm],
   acceptance=mean(vapply(chain$diagnostics,`[[`,TRUE,"accepted")))
}
r<-do.call(rbind,rows)

The first normal chain gave mean 2.01881 and variance 0.67519. The table gives rounded MCSEs for the first normal chain at three batch lengths.

Batch length in drawsMCSE of meanMCSE of variance
500.024420.02367
1000.023640.02322
2000.027500.02182

At length 100, the estimated MCSE of 0.02364 gives a scale for the observed mean difference of 0.01881. The three lengths change the error estimate while leaving the chain mean fixed. For a second check, select just the length-100 row from each of the four chains per target.

1
2
3
4
do.call(rbind,lapply(split(r[r$batch==100,],r$target[r$batch==100]),function(z)
 data.frame(target=z$target[1],SD_chain_means=sd(z$mean),
   mean_batch_MCSE=mean(z$mean_MCSE),
 SD_chain_variances=sd(z$variance),mean_variance_MCSE=mean(z$variance_MCSE))))

For the normal target, the standard deviation of the four chain means was 0.01917, and the average of the four within-chain MCSEs was 0.02483. For the conditional random intercept, the corresponding values were 0.01297 and 0.01677. The first quantity measures variation across four runs. The second estimates how much a single run’s mean varies owing to simulation.

Detailed balance makes the target distribution stationary. Convergence in distribution from a chosen starting point additionally requires conditions such as irreducibility and absence of periodic cycling; an invariant probability distribution must exist. Irreducibility requires a positive chance of reaching every region of positive target probability from any starting state in the support, given enough transitions. This condition must be checked for the target and proposal together. In the scalar examples the target is positive everywhere on the real line and the normal proposal can reach any interval from the current point. For a restricted target, start inside its support and reject candidates with zero target density. Even when all regions are reachable, successive draws can be strongly correlated. Very small proposals can be accepted frequently while taking many steps to traverse a plausible range of traits. For a trait mean, the spread of the chain means and the MCSE for each mean help assess the precision that the acceptance fraction alone cannot measure. Multidimensional item estimation using MH updates is available in mirt.

14.3 Simulating a Markov chain and choosing the proposal scale

Repeated transitions approximate a conditional trait mean by averaging the states visited, starting from a specified point. Each call returns a state that becomes the input to the next call. For an item sweep, the state is a matrix, with both trait coordinates for each examinee. For a single random intercept, the state is one number. The function mcmc() accepts either form, together with the transition kernel and iteration count.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
mcmc <- function(start, kernel, iterations, initial_iteration=0L) {
  stopifnot(iterations>=1L, iterations==as.integer(iterations))
  if (!exists(".Random.seed",envir=.GlobalEnv,
    inherits=FALSE)) stop("Set an initial stream before sampling")
  rng_before <- .Random.seed
  state <- start
  draws <- vector("list",iterations)
  diagnostics <- vector("list",iterations)
  for (j in seq_len(iterations)) {
    move <- kernel(state)
    state <- move$state
    draws[[j]] <- state
    diagnostics[[j]] <- move[setdiff(names(move),"state")]
  }
  list(state=state,draws=draws,diagnostics=diagnostics,
    iteration=initial_iteration+iterations,
    first_iteration=initial_iteration+1L,rng_before=rng_before,rng_after=.Random.seed)
}
resume_mcmc <- function(previous,kernel,additional) {
  assign(".Random.seed",previous$rng_after,envir=.GlobalEnv)
  mcmc(previous$state,kernel,additional,previous$iteration)
}

A run saves .Random.seed on entry and exit. This R object identifies the position in the random number sequence. The last state gives the starting point for another transition, while the saved random number state determines which proposals and uniforms follow. For a warmup of $W$ iterations, make one call from the chosen point. To obtain another $M$ draws, resume_mcmc() restores the stream at the end of warmup and runs the same kernel from the last warmup state. This continuation also requires the same transition function, data, model coefficients and proposal settings; the returned run does not store all of them. Warmup means preliminary transitions omitted from the retained average, not a guarantee that the chain has reached its target distribution.

The list draws begins with the state after the first transition. On rejection, move$state equals the preceding state, so it occupies another position in the list. That repeated position contributes to a mean just as an accepted position does.

For a continuous random walk, let $a(z)$ be the probability of accepting a proposal from $z$. At stationarity, the density of a point immediately before an accepted move is proportional to $\pi(z)a(z)$ because the chain occupies $z$ with target density $\pi(z)$ and leaves with probability $a(z)$. Accepted arrivals have the same distribution as accepted departures over a stationary run. Averaging only the accepted points would therefore give too little weight to regions with low acceptance.

The iteration indices count all decisions. An initial warmup covers iterations 1 through $W$, and its continuation covers $W+1$ through $W+M$. A rejection at the boundary can give identical states on iterations $W$ and $W+1$, each with its own decision.

Choosing the proposal variance for the item sweeps

For the two-factor item data, choose a proposal variance using preliminary sweeps. Run the item calculation from the book directory using the observed responses in IRT12-two.rds. The design fixes the loading zeros and start2 supplies the item parameters for all 500 examinees.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
source("code/lib/dogleg.R")
source("code/lib/factored_secant.R")
source("code/lib/simulation.R")
source("code/lib/logit.R")
source("code/lib/integration.R")
source("code/lib/mcmc.R")
source("code/lib/stochastic_items.R")
source("code/lib/inference.R")
source("code/lib/multidim_items.R")
source("code/lib/lbfgsb.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")

Y <- readRDS("data/source/ch14/IRT12-two.rds")
design2 <- multidim_design(Y, 2L)
start2 <- multidim_start(design2)

The preliminary sweeps fix the item parameters and use acceptance fractions to select a common proposal variance per coordinate. The first function below selects a variance from the recorded history; the second runs the preliminary sweeps and records that history.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
multidim_adapt_proposal_variance <- function(accept_rates, proposal_variances,
                                             target_acceptance = .5) {
  last <- max(seq_along(accept_rates)[!is.na(accept_rates)])
  rate <- accept_rates[last]; sd_last <- proposal_variances[last]
  smallest <- min(proposal_variances, na.rm = TRUE); largest <- max(proposal_variances, na.rm = TRUE)
  if (rate > .3 & rate < .4) return(sd_last)
  if (rate < .01) return(smallest / 10)
  if (rate > .99) return(largest * 5)
  if (length(unique(proposal_variances)) < 4L) return(sd_last * (if (rate > .5) 1.1 else .8))
  fit <- lm(plogis(accept_rates) ~ proposal_variances, data = data.frame(accept_rates, proposal_variances))
  predicted_rate <- function(x) qlogis(predict(fit, data.frame(proposal_variances = x)))
  root <- factored_secant_minimize(function(x) (target_acceptance - predicted_rate(x))^2,
    sd_last)$estimate
  if (root < 0) smallest / 2 else root
}

multidim_tune_draws <- function(theta, par_vec, design, proposal_variance, target_acceptance = .5) {
  accept_rates <- proposal_variances <- rep(NA, 25L)
  for (i in 1:31) {
    theta <- multidim_draw_traits(theta, par_vec, design, proposal_variance)
    if (i <= 5L) next
    accept_rates[i - 5L] <- attr(theta, "Proportion Accepted")
    proposal_variances[i - 5L] <- proposal_variance
    proposal_variance <- multidim_adapt_proposal_variance(accept_rates, proposal_variances,
      target_acceptance = target_acceptance)
  }
  list(theta = theta, proposal_variance = proposal_variance, accept_rates = accept_rates,
    proposal_variances = proposal_variances)
}

Inside multidim_tune_draws(), the first of 31 calls initializes the log densities at the zero points. Calls 2 through 5 move the traits at variance 1. Beginning at call 6, each sweep contributes two numbers to the history, the fraction of persons whose proposals were accepted and the variance per coordinate used to propose them. The adaptation function uses that history to select the variance for the next sweep. It leaves the variance as it is for a rate strictly between 0.3 and 0.4. Below 0.01, it divides the smallest variance tried by ten. Above 0.99, it multiplies the largest by five. With fewer than four distinct variance entries, the next multiplier is 1.1 for a rate above 0.5 and 0.8 otherwise. Unfilled entries together count as one distinct value in this test. Calls 6 through 31 supply 26 recorded pairs, although the vectors are initially allocated with length 25. These acceptance fractions average over examinees with different conditional targets.

For the remaining cases, lm() fits a line to the transformed rates plogis(accept_rates) as a function of variance. At a candidate variance, qlogis() applies the logit to the predicted value, undoing the transformation algebraically. The transformed observed rates lie between plogis(0) and plogis(1); an unconstrained fitted value can fall outside this interval, giving a value outside the acceptance-rate range after qlogis(), or an undefined result. The minimizer searches for the variance at which the squared difference from the target acceptance rate is smallest. A negative result is replaced by half the smallest variance tried. The target acceptance rate here is 0.5. In Metropolis-Hastings Robbins-Monro estimation it changes to 0.4 at the end of the first stage.

Start the preliminary calls at variance 1 and seed 1413.

1
2
3
set.seed(1413)
tuning <- multidim_tune_draws(matrix(0,design2$N,2L),start2,design2,1)
print(data.frame(sweep=6:31,proposal_variance=tuning$proposal_variances,acceptance=tuning$accept_rates))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
   sweep proposal_variance acceptance
1      6         1.0000000      0.388
2      7         1.0000000      0.370
3      8         1.0000000      0.394
4      9         1.0000000      0.408
5     10         0.8000000      0.420
6     11         0.6400000      0.496
7     12         0.5816495      0.498
8     13         0.5778126      0.500
9     14         0.5778126      0.490
10    15         0.5680371      0.492
11    16         0.5614486      0.462
12    17         0.5328888      0.510
13    18         0.5399116      0.542
14    19         0.5628195      0.490
15    20         0.5584311      0.494
16    21         0.5560061      0.498
17    22         0.5552644      0.508
18    23         0.5579625      0.538
19    24         0.5692399      0.452
20    25         0.5561693      0.506
21    26         0.5577745      0.500
22    27         0.5577745      0.504
23    28         0.5587065      0.516
24    29         0.5621705      0.520
25    30         0.5661620      0.500
26    31         0.5661620      0.526

At variance 1, the first three printed rates are inside the interval for leaving the variance unchanged. Sweep 9 gives 0.408, so the early-history rule gives 0.8 for sweep 10. After 0.8 comes 0.64. The three variances tried and the unfilled entry now give four distinct values, so the regression selects 0.5816495. Later variances cluster near 0.56. Sweep 31 used 0.5661620. Its acceptance fraction of 0.526 selected 0.5707217 for subsequent proposals.

During preliminary sweeps, the distribution of the next proposal depends on the acceptance history as well as the current point. Once the variance is fixed, the next proposal depends on the current traits alone. For a fixed target, the symmetric proposal gives the same MH balance equation for all 2,000 subsequent sweeps. The 500 warmup sweeps run at that variance before averaging starts. The target-density calculation is considered in Section 14.2. The item parameters are also fixed, so the model specifies the same conditional trait distribution at every retained sweep. In an outer estimation step, updating an item slope or intercept changes the response probabilities entering that distribution. A mean computed across such an update would combine draws obtained under different item parameters.

Fix that variance in kernel. Run 500 more sweeps for warmup, then retain 1,500. Extract row 1 from each retained matrix. For a reference mean, multiply each weight of a 61 by 61 standard normal quadrature grid by the probability of this examinee’s answers at that point. Normalize the products and take the weighted mean of each coordinate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
kernel <- function(theta) {
  moved <- multidim_draw_traits(theta,start2,design2,tuning$proposal_variance)
  list(state=moved,accepted=attr(moved,"Proportion Accepted"))
}
first <- mcmc(tuning$theta,kernel,500L)
second <- resume_mcmc(first,kernel,1500L)
person1 <- t(vapply(second$draws,function(theta) theta[1,],numeric(2)))
# The person's conditional mean by a 61 x 61 product rule at the same parameters.
grid61 <- product_rule(61L,2L)
log_kernel <- grid61$log_weights+
  drop(log(multidim_category_probabilities(start2,design2,grid61$nodes))%*%
  design2$indicators[1,])
conditional <- normalize_logweights(log_kernel)
batch_length <- c(30L, 60L, 120L)
batch_mcse <- vapply(batch_length, function(length_per_batch) {
  vapply(seq_len(ncol(person1)), function(k) {
    batch_means_mcse(person1[, k], length_per_batch)$mcse
  }, numeric(1))
}, numeric(ncol(person1)))
print(list(chosen_variance=tuning$proposal_variance,
  acceptance=mean(vapply(second$diagnostics,function(d)d$accepted,0.0)),
  retained_mean=colMeans(person1),reference=drop(crossprod(conditional,grid61$nodes)),
  monte_carlo_standard_errors=data.frame(batch_length=batch_length,
    mcse_factor_1=batch_mcse[1, ], mcse_factor_2=batch_mcse[2, ])))

The first four summary components give the selected variance, acceptance fraction and two pairs of means.

1
2
3
4
5
6
7
8
9
10
11
$chosen_variance
[1] 0.5707217

$acceptance
[1] 0.495048

$retained_mean
[1] 0.07079603 0.35510953

$reference
[1] 0.09112395 0.36205796

The acceptance fraction 0.495048 averages over 500 people in each of 1,500 retained sweeps. The two means use only the first examinee’s draws. They fall below the corresponding quadrature means by 0.02033 and 0.00695. How large are these gaps relative to the Monte Carlo error?

To judge the precision of the first examinee’s trait means, divide the retained sequence for one coordinate into consecutive, nonoverlapping batches. Let $b$ be the batch length and $a=\lfloor n/b\rfloor$ the number of complete batches among $n$ draws. If $Z_t$ is the coordinate at iteration $t$, the mean of batch $j$ and the mean of the complete batch means are

\[H_j=\frac{1}{b}\sum_{t=(j-1)b+1}^{jb}Z_t,\qquad \bar H=\frac{1}{a}\sum_{j=1}^a H_j.\]

A batch mean includes runs of correlated draws. If the chain is sampling its target and batches are long enough that correlations among their means are negligible, the variance of their average is approximately the variance of a batch mean divided by $a$. This is the nonoverlapping batch means method. Its justification requires appropriate Markov chain limit and moment conditions. Having two complete batches merely makes the formula computable; it does not establish adequate precision. Estimating that variance from the $a$ batch means gives the Monte Carlo standard error

\[\widehat{\mathrm{MCSE}}=\frac{1}{\sqrt a} \left\{\frac{1}{a-1}\sum_{j=1}^a(H_j-\bar H)^2\right\}^{1/2}.\]
1
2
3
4
5
6
7
8
batch_means_mcse <- function(values,size=floor(sqrt(length(values)))) {
  stopifnot(size>=1L,all(is.finite(values)))
  batches <- length(values)%/%size
  if (batches<2L) stop("At least two complete batches are required")
  means <- colMeans(matrix(values[seq_len(batches*size)],size,batches))
  list(mean=mean(values),mcse=sd(means)/sqrt(batches),batch_size=size,
    batches=batches,used=batches*size,total=length(values))
}

The columns of the matrix inside batch_means_mcse() are the complete batches. Its returned mean uses every draw. If a remainder is discarded for batching, this error formula pertains directly to the mean of the complete batches. The function pairs it with the all-draw mean, so the two use slightly different sets of draws.

The final component of the printed item-chain summary gives the two standard errors side by side.

1
2
3
4
5
$monte_carlo_standard_errors
  batch_length mcse_factor_1 mcse_factor_2
1           30    0.06529821    0.06764370
2           60    0.06655362    0.06966487
3          120    0.07702298    0.07307341

At lengths 30, 60 and 120 there are 50, 25 and 12 complete batches. At length 120 the error estimate uses 1,440 draws, while both reported trait means still use 1,500. At length 60, for instance, the two standard errors are 0.06655 and 0.06966. The absolute differences from the quadrature means, 0.02033 and 0.00695, are smaller than the corresponding standard errors at all three lengths. On the reported MCSE scale the gaps are small. This finite comparison does not by itself validate the batch approximation or establish adequate exploration of the conditional distribution.

Resuming a chain from its saved state

Can a continuation reproduce the draws that an uninterrupted run would have made? For the item calculation, restore the stream from just before the first retained sweep and apply the fixed item kernel to the last warmup matrix. The check compares the resulting matrix and acceptance fraction with their saved values, then restores the random number state that was in use before the check.

1
2
3
4
5
6
7
checkpoint <- second$rng_before
after <- .Random.seed
assign(".Random.seed",checkpoint,envir=.GlobalEnv)
recovered <- kernel(first$state)
stopifnot(identical(recovered$state,second$draws[[1]]),
  identical(recovered$accepted,second$diagnostics[[1]]$accepted))
assign(".Random.seed",after,envir=.GlobalEnv)

A scalar standard normal target makes it possible to inspect an entire short path. Set the L’Ecuyer-CMRG generator and seed 140312. The proposal adds a standard normal increment to the current point. From zero, run twelve transitions. Restore the original stream, run five, then resume for seven with the same kernel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection");set.seed(140312)
kernel<-function(x) mh_step(x,function(z)dnorm(z,log=TRUE),function(z)z+rnorm(1))
initial_stream<-.Random.seed
whole<-mcmc(0,kernel,12L)
assign(".Random.seed",initial_stream,.GlobalEnv)
prefix<-mcmc(0,kernel,5L);suffix<-resume_mcmc(prefix,kernel,7L)
stopifnot(identical(whole$draws,c(prefix$draws,suffix$draws)),
 identical(whole$diagnostics,c(prefix$diagnostics,suffix$diagnostics)),
   identical(whole$rng_after,suffix$rng_after),
 suffix$first_iteration==6L,suffix$iteration==12L)
data.frame(step=1:12,proposal=vapply(whole$diagnostics,`[[`,0.0,"proposal"),
 accept=vapply(whole$diagnostics,`[[`,TRUE,"accepted"),state=unlist(whole$draws),
 split_state=unlist(c(prefix$draws,suffix$draws)),
   end_rng_identical=identical(whole$rng_after,suffix$rng_after))
TransitionProposed valueAcceptedUninterrupted stateSplit-run state
5-0.36649Yes-0.36649-0.36649
6-0.55073Yes-0.55073-0.55073
8-0.74386Yes-0.74386-0.74386
9-2.19141No-0.74386-0.74386

The table selects four transitions and rounds their values. The five-step prefix ended at $-0.36649$. Its saved state, iteration index and random number state put the continuation at transition 6, where both runs proposed $-0.55073$ and accepted. At transition 9, the proposal was $-2.19141$. Both runs rejected it and recorded $-0.74386$ again. All twelve states, all decisions and the final random number state agree. This equality concerns reproduction of one path. A new stream supplies fresh random numbers for the same target and proposal. Exact replay checks the saved state and execution sequence. Reproducibility also depends on the random-number methods and software version, not just the integer seed.

A target with known mean and variance

For a separate check with known moments, restore the Mersenne-Twister generator before setting seed 14031. The target now has mean 2 and variance 0.7. Start at zero and use the last 5,000 of 6,000 draws.

1
2
3
4
5
6
7
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(14031)
normal_target <- function(x)dnorm(x,2,sqrt(.7),log=TRUE)
normal_chain <- mcmc(0,function(x)mh_step(x,normal_target,function(z)z+rnorm(1)),6000L)
v <- tail(unlist(normal_chain$draws),5000)
print(c(mean=mean(v),variance=var(v),mean_MCSE=batch_means_mcse(v)$mcse,
  lag1=cor(head(v,-1),tail(v,-1))))
1
2
      mean   variance  mean_MCSE       lag1 
2.04950558 0.70957307 0.02739932 0.73317762 

The default batch length is $\lfloor\sqrt{5000}\rfloor=70$. The estimated standard error is 0.02740, so the chain mean of 2.04951 is about 1.81 standard errors above 2. The sample variance is 0.70957, and successive draws have sample correlation 0.73318. This positive correlation makes adjacent draws less informative about the mean than independent draws of the same variance. Batching estimates the precision of the mean from groups of those draws. Multidimensional item estimation with Metropolis-Hastings updates is available in mirt.

14.4 Monte Carlo EM and increasing the simulation size

Estimating an item slope requires relating responses to trait values. An examinee supplies twelve answers, but the trait vector at which those answers arose is unknown. How much should that response pattern contribute at each possible trait vector when the slope is updated? Let $\beta_c$ be the slopes and intercepts at the start of cycle $c$, and let $\beta$ denote a candidate set of coefficients. For a response pattern $y_h$, write $B_h(z;\beta)$ for the product of the twelve observed category probabilities given traits $z$. With standard normal trait density $\phi_q$ in $q$ dimensions, the contribution of one examinee with this pattern to the complete-data log likelihood is $\log B_h(z;\beta)+\log\phi_q(z)$. EM averages this contribution under the conditional distribution of the traits given $y_h$ at $\beta_c$.

The examinees are independent. If $n_h$ give identical answers, their expected contributions are equal and enter the sum $n_h$ times. Given integration points $z_s$ and normalized conditional weights $w_{hs}^{(c)}$, Monte Carlo EM (MCEM) approximates the expected complete-data log likelihood by

\[\widehat Q_c(\beta\mid\beta_c)= \sum_h n_h\sum_{s=1}^{S_c} w_{hs}^{(c)} \left\{\log B_h(z_s;\beta)+\log\phi_q(z_s)\right\}.\]

Here $S_c$ counts the points in this cycle. The E step uses the current coefficients to determine the weights. During the M step, the points and weights remain fixed while the candidate coefficients vary. A trial slope therefore changes the probability of an answer at a given node without reallocating examinees to that node.

At the start of cycle $c$, draw $S_c=500+2(c-1)$ independent vectors from the standard normal prior. For each coordinate, qnorm() transforms a uniform draw into a standard normal draw. The resulting matrix has one row per vector and $q$ columns. Use that one matrix for every examinee. The empirical distribution assigns each sampled point mass $1/S_c$. For pattern $h$, multiply that mass by $B_h(z_s;\beta_c)$ and divide by the sum over the points. The prior here is the population distribution of latent traits, with fixed mean and covariance; no prior distribution is being placed on the item coefficients. Canceling $1/S_c$ in the ratio gives

\[w_{hs}^{(c)}=\frac{B_h(z_s;\beta_c)} {\sum_{t=1}^{S_c} B_h(z_t;\beta_c)}.\]

A node that assigns high probability to one pattern can receive little weight for another. Drawing the points from the prior already accounts for the normal density. The conditional distribution for each pattern is approximated by weighting those shared points with its own response probabilities.

This ratio calculation is self-normalized importance sampling: the normal population distribution supplies the draws and the response probabilities supply the weights. It approximates a conditional expectation using draws from a different distribution. At finite simulation size the resulting ratio is generally biased. Reusing the nodes also makes simulation errors for different patterns dependent.

An MCEM routine for the item model

The following routine implements this approximation for the item model. Run the following setup from the book directory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
source("code/lib/dogleg.R")
source("code/lib/factored_secant.R")
source("code/lib/simulation.R")
source("code/lib/logit.R")
source("code/lib/integration.R")
source("code/lib/mcmc.R")
source("code/lib/stochastic_items.R")
source("code/lib/inference.R")
source("code/lib/multidim_items.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")

The E-step function below computes marginal pattern probabilities on the supplied nodes and accumulates the conditional expected response counts needed by the M step.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
multidim_estep <- function(item_probs, prior, patterns) {
  tiny_value <- .Machine$double.xmin
  tab <- patterns$tab
  freq <- patterns$freq
  r1 <- matrix(0, nrow(item_probs), ncol(tab))
  expected <- numeric(nrow(tab))
  for (pat in seq_len(nrow(tab))) {
    if (freq[pat] < tiny_value) next
    columns <- which(tab[pat, ] == 1)
    posterior <- 1 * prior
    for (item in columns) posterior <- posterior * item_probs[, item]
    maxp <- max(posterior)
    expected_score <- multidim_sum(posterior / maxp) * maxp
    if (expected_score < tiny_value) expected_score <- tiny_value
    expected[pat] <- expected_score
    if (expected_score > tiny_value) posterior <- freq[pat] * posterior / expected_score
    for (item in columns) r1[, item] <- r1[, item] + posterior
  }
  r1[is.nan(r1)] <- 0
  list(r1 = r1, expected = expected, LL = sum(freq * log(expected), na.rm = TRUE))
}

In multidim_estep(), columns selects the observed response categories for one pattern. At each node, the loop multiplies the prior mass by the twelve selected probabilities. Summing these products gives the estimated marginal probability of the pattern. The function divides the products by their maximum, adds them with multidim_sum(), then multiplies by that maximum to restore the scale. The local name expected_score denotes this marginal pattern probability, not an expected test score or a log likelihood derivative.

To see what the M step receives, consider a pattern that starts with a zero on item 1 and a one on item 2. In the matrix r1, node $s$ occupies one row. Columns $2j-1$ and $2j$ contain the expected counts of zeros and ones on item $j$. For a pattern observed $n_h$ times, the assignment to posterior after normalization gives $n_hw_{hs}^{(c)}$ at node $s$. The loop adds that quantity to each column selected by the pattern. For the two answers just specified, those are columns 1 and 4. These are conditional expected response counts, not observed category counts at measured trait values. Their sums over nodes should recover the observed counts when normalization succeeds. More generally, the count at node $s$ for category $k$ of item $j$ is

\[r_{sjk}^{(c)}=\sum_h n_h w_{hs}^{(c)}\,\mathbf{1}\{y_{hj}=k\}.\]

Scaling after multiplication cannot recover products already rounded to zero. If every product is zero, division by the maximum is undefined; replacing a tiny marginal value by a floor also changes the normalization used for expected counts.

Enter the next three code blocks in order as the definition of multidim_em(). The function first groups repeated response patterns, sets starting coefficients and prepares a rule for generating integration points. The random-node branch draws fresh points for MCEM. The alternative branch constructs a fixed grid for ordinary EM. The fixed grid uses equally spaced points on a bounded interval with renormalized normal-density weights; it is not a Gauss-Hermite rule.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
multidim_em <- function(Y, q, method = c("EM", "MCEM"), n_quad = NULL, conv_tol = 1e-4,
                    n_cycles = 500L, accelerate = method == "EM") {
  method <- match.arg(method)
  MC <- method == "MCEM"
  design <- multidim_design(Y, q)
  patterns <- multidim_patterns(design)
  par_vec <- multidim_start(design)
  is_free <- design$is_free
  latent <- c(rep(FALSE, design$J * design$item_length), rep(TRUE, length(par_vec) -
    design$J * design$item_length))
  nodes <- function(cycles) {
    if (MC) {
      # All response patterns share these draws from the trait prior.
      n_points <- 500 + (cycles - 1) * 2
      theta <- qnorm(matrix(runif(n = n_points * q, min = 0, max = 1), n_points, q))
      Theta <- t(t(theta) + rep(0, q)) %*% chol(diag(q))
      list(Theta = Theta, Prior = matrix(rep(1 / n_points, n_points)))
    } else {
      if (is.null(n_quad)) n_quad <- switch(as.character(q),
        `1` = 61, `2` = 31, `3` = 15)
      theta <- seq(-6, 6, length.out = n_quad)
      Theta <- as.matrix(expand.grid(rep(list(theta), q)))
      colnames(Theta) <- NULL
      Prior <- exp(multidim_normal_log_density(Theta, rep(0, q), diag(q)))
      list(Theta = Theta, Prior = Prior / sum(Prior))
    }
  }
  grid <- if (!MC) nodes(1L)
  pre <- pre2 <- par_vec
  mstep_budget_multiplier <- .4
  ll_path <- rep(NA_real_, n_cycles)
  history <- list()
  converged <- FALSE
  em_path <- matrix(NA_real_, n_cycles + 1L, length(par_vec))
  em_path[1L, ] <- par_vec

The call to multidim_patterns() groups identical response rows in order of first appearance, returning their category indicators in tab and their counts in freq. In the random-node branch, Prior gives equal mass to the rows of Theta. Item $j$ can load on the first $\min(j,q)$ factors. When the leading triangular block is nonsingular, the fixed zeros remove continuous rotations. Factor signs still need to be aligned when comparing estimates.

At each cycle, multidim_category_probabilities() computes both category probabilities for every item at every node. The E step returns their expected counts and the random-grid log likelihood $\ell_c=\sum_h n_h\log\lbrace S_c^{-1}\sum_s B_h(z_s;\beta_c)\rbrace $. This log likelihood evaluates the entering coefficients. For the M step, let $P_{jk}(z_s;\beta)$ be the candidate probability of response $k$ on item $j$ at node $s$. The function fn returns $-\sum_{s,j,k}r_{sjk}^{(c)}\log P_{jk}(z_s;\beta)$. Each evaluation of fn pairs the new log probabilities with the same expected counts. The log density of the fixed normal prior adds a constant, which fn omits. BFGS updates all free slopes and intercepts together using the item derivatives in gr. The M step uses a finite BFGS budget, so its attained objective and stopping result describe the numerical update.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
  for (cycles in seq_len(n_cycles)) {
    if (MC) grid <- nodes(cycles)
    e <- multidim_estep(multidim_category_probabilities(par_vec, design, grid$Theta), grid$Prior,
      patterns)
    # The counts belong to the parameters entering this cycle.
    last_r1 <- e$r1
    ll_path[cycles] <- e$LL
    if (cycles > 1L) {
      drop_ll <- ll_path[cycles - 1L] - ll_path[cycles]  # negative after a rise
      mstep_budget_multiplier <- if (drop_ll < 0) exp(drop_ll) else mstep_budget_multiplier
      if (!is.finite(mstep_budget_multiplier)) mstep_budget_multiplier <- 1e-6
    }
    pre2 <- pre
    pre <- par_vec
    # Vary only the free item coefficients during this M step.
    fn <- function(p) {
      lp <- par_vec
      lp[is_free] <- p
      LL <- sum(e$r1 * suppressWarnings(log(multidim_category_probabilities(lp, design, grid$Theta))))
      -ifelse(is.finite(LL), LL, -1e100)
    }
    gr <- function(p) {
      lp <- par_vec
      lp[is_free] <- p
      g <- numeric(length(lp))
      L <- design$item_length
      for (j in seq_len(design$J)) {
        index <- (j - 1L) * L + seq_len(L)
        g[index] <- multidim_item_derivatives(lp[index], grid$Theta,
          e$r1[, 2L * j - 1L:0L, drop = FALSE],
          FALSE)$grad
      }
      -g[is_free]
    }
    opt <- bfgs(fn, gr, par_vec[is_free], list(maxit = max(ceiling(mstep_budget_multiplier * 50), 15)))
    par_vec[is_free] <- opt$par

For one item, multidim_item_derivatives() takes its full parameter block, the trait nodes and two columns of expected counts, for responses zero and one. It returns grad in the same slope, intercept and asymptote-logit order as that block. The final FALSE argument omits the Hessian calculation. The wrapper assembles the item gradients, selects the free coordinates and negates them because BFGS minimizes the negative Q function.

The BFGS iteration limit is $\max(\lceil50r\rceil,15)$ with $r=0.4$ initially. If $\ell_c>\ell_{c-1}$, set $r=\exp(\ell_{c-1}-\ell_c)$ for this M step. Otherwise the previous value is retained. This comparison sets the amount of optimization effort. The next block records the coefficient change, checks the stopping rule and returns the final fit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    history[[cycles]] <- list(cycle = cycles, nodes = nrow(grid$Theta), loglik = e$LL,
      mstep_budget_multiplier = mstep_budget_multiplier, max_change = max(abs(pre - par_vec)),
      mstep_iterations = opt$iterations)
    if (multidim_within_tolerance(pre, par_vec, conv_tol)) {
      converged <- TRUE
      break
    }
    # Only fixed-grid EM uses acceleration with these defaults.
    if (accelerate && cycles %% 3 == 0L && mstep_budget_multiplier > .01) {
      # Ramsay's step: the last change is stretched by a factor from the last two changes
      # (at most 6); the group parameters are not moved.
      step1 <- par_vec - pre
      curve <- step1 - (pre - pre2)
      dot <- function(v) as.vector(v %*% v)
      accel <- 1 - sqrt(dot(step1) / dot(curve))
      if (accel < -5) accel <- -5
      par_vec <- ifelse(latent, par_vec, (1 - accel) * par_vec + accel * pre)
    }
    em_path[cycles + 1L, ] <- par_vec
  }
  # Evaluate the final coefficients on a fresh random grid for MCEM.
  em_path[cycles + 1L, ] <- par_vec
  if (MC) grid <- nodes(cycles)
  final <- multidim_estep(multidim_category_probabilities(par_vec, design, grid$Theta), grid$Prior,
      patterns)
  list(par_vec = par_vec, cycles = cycles, converged = converged, loglik = final$LL,
    history = history, design = design, method = method, grid = grid, patterns = patterns,
    final_expected_counts = final$r1, last_mstep_expected_counts = last_r1,
    ll_path = as.numeric(na.omit(ll_path)),
    em_path = em_path[rowSums(is.na(em_path)) == 0, , drop = FALSE])
}

The start of each M step is saved in pre. Subtracting it from the updated vector gives the coordinate changes whose largest absolute value is recorded as max_change. With method = "MCEM", acceleration is off by default; explicitly passing accelerate = TRUE enables the same extrapolation code. With the default settings, the loop stops when all changes are strictly smaller than $10^{-4}$ or after 500 cycles. Despite its name, mstep_budget_multiplier is this optimization-budget multiplier; MCEM here has no Metropolis-Hastings accept/reject step. A small coefficient change is a stopping rule, not proof that the likelihood equations or an EM increase condition have been satisfied.

Fitting the two-factor sample

Fit the two-factor model to the observed matrix using seed 14041. Inspect the first response row, its pattern count and the total number of distinct patterns.

1
2
3
4
5
6
7
Y <- readRDS("data/source/ch14/IRT12-two.rds")
set.seed(14041)
fit <- multidim_em(Y, 2L, "MCEM")
mcem2 <- fit
fit$design$Y[1, ]
fit$patterns$freq[1]
length(fit$patterns$freq)

Among the 500 examinees, two gave the first pattern, $(0,1,0,0,1,1,1,0,1,1,0,1)$. It is one of 443 distinct patterns. At node $s$, this pattern contributes $2w_{1s}^{(c)}$ to each of columns 1 and 4 in the 24-column count matrix. Summing either contribution over nodes recovers two observed answers. Other patterns that share either response add their own weighted counts to that column.

The last history entry evaluates the entering coefficients on that cycle’s nodes. The returned summary evaluates the updated coefficients on the final grid. The field final_expected_counts stores the E-step counts at those returned coefficients and that same grid. The separate last_mstep_expected_counts preserves the counts used in the last M step. In MCEM, the final grid is a fresh random draw, so the two sets of counts serve different purposes.

1
2
3
last_cycle <- tail(fit$history, 1L)[[1L]]
print(last_cycle)
print(c(cycles=fit$cycles, converged=fit$converged, loglik=fit$loglik))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$cycle
[1] 500

$nodes
[1] 1498

$loglik
[1] -3900.253

$mstep_budget_multiplier
[1] 0.9388564

$max_change
[1] 0.02762129

$mstep_iterations
[1] 8

   cycles converged    loglik 
  500.000     0.000 -3900.838 

Cycle 500 used 1,498 nodes and had a pre-update log likelihood of $-3900.253$. The largest coefficient change in its M step was 0.02762129. On leaving the loop, nodes(cycles) drew a fresh set of 1,498 points. Evaluating the updated coefficients on those points gave the returned $-3900.838$. To put the final update in context, select several cycles from the history and summarize the largest change per cycle over the last 100.

1
2
3
mcem_history <- function(fit,shown=c(1:3,10,50,100,200,300,400,500))
  do.call(rbind,lapply(fit$history[shown[shown<=length(fit$history)]],as.data.frame))
print(mcem_history(mcem2))
1
2
3
4
5
6
7
8
9
10
11
   cycle nodes    loglik      mstep_budget_multiplier max_change mstep_iterations
1      1   500 -4029.950 4.000000e-01 0.46343841               20
2      2   502 -3942.293 8.530510e-39 0.18563255               15
3      3   504 -3920.738 4.355041e-10 0.09829777               14
4     10   518 -3903.513 2.292002e-01 0.03556477               12
5     50   598 -3901.348 9.327693e-01 0.06672038               13
6    100   698 -3900.361 4.466778e-01 0.01237698                8
7    200   898 -3900.702 4.836827e-01 0.02717567               12
8    300  1098 -3900.569 9.821489e-01 0.03459347               16
9    400  1298 -3900.375 8.104930e-01 0.03826439                8
10   500  1498 -3900.253 9.388564e-01 0.02762129                8

The increasing node count does not force coefficient changes to decrease steadily. The first M step used all 20 allowed BFGS iterations and changed a coefficient by 0.46344. The rise in the random-grid log likelihood at cycle 2 made mstep_budget_multiplier so small that the lower limit of 15 iterations determined the BFGS budget for that cycle. By cycle 100 the largest change was 0.01238, but at cycle 500 it was back up to 0.02762.

1
2
3
late_change <- function(fit) summary(vapply(tail(fit$history,100),
    function(h)h$max_change,0.0))
late_change(mcem2)

Over those final 100 cycles, the smallest of the maximum changes was 0.007318, the median was 0.024962 and the largest was 0.072374. Even the smallest was well above the stopping tolerance.

Drawing new points changes the approximation to the likelihood as well as the expected counts used to update the items. An increase or decrease between successive history entries combines a change of coefficients with a change of grid.

For a fixed pattern and fixed coefficients, the estimated pattern probability is an average of $S_c$ independent values of $B_h$. Its standard error is the standard deviation of $B_h$ under the prior divided by $\sqrt{S_c}$. Increasing $S_c$ improves the precision of this integral, but successive cycles also change the coefficients. The largest update need not decrease at every cycle.

Evaluating final coefficients on a common deterministic grid removes the choice of random points from an endpoint comparison. For the two-factor MCEM endpoint, 25 Gauss-Hermite nodes per axis give a log likelihood of $-3900.317394$. This is a deterministic approximation, with integration error still possible. The history of coefficient changes establishes why the fit stopped.

For fixed coefficients the untransformed probability average is unbiased in exact arithmetic. Taking its logarithm generally introduces bias, and normalizing it in conditional weights gives another ratio. The stated standard error for a probability average is not the standard error of either transformed quantity.

Fitting the three-factor sample

For a three-factor fit, use the separate sample of 500 examinees answering twelve items. The following assignment makes both observed matrices available in data14, including when the session began with only the two-factor matrix Y.

1
data14 <- list(two = Y, three = readRDS("data/source/ch14/IRT12-three.rds"))

Fit the three-factor model at seed 14043. Use the same cycle schedule and read the changes for this sample alongside its returned log likelihood estimate.

1
2
3
set.seed(14043)
mcem3 <- multidim_em(data14$three,3L,"MCEM")
print(mcem_history(mcem3))
1
2
3
4
5
6
7
8
9
10
11
   cycle nodes    loglik      mstep_budget_multiplier max_change mstep_iterations
1      1   500 -4086.881 4.000000e-01 0.65264556               20
2      2   502 -3926.127 1.532281e-70 0.21343163               15
3      3   504 -3889.969 1.981678e-16 0.13286292               15
4     10   518 -3842.391 1.322287e-01 0.07979391               15
5     50   598 -3837.341 6.830519e-02 0.04119786               12
6    100   698 -3837.334 2.285571e-02 0.05089820               14
7    200   898 -3837.504 7.475727e-01 0.03430109               15
8    300  1098 -3836.002 2.199377e-01 0.03586146               15
9    400  1298 -3838.325 1.813945e-01 0.08973054               14
10   500  1498 -3836.816 2.921869e-01 0.02449442               14

At cycle 500, the largest three-factor change was 0.02449. The joint summary places this last change beside the range over the last 100 cycles and the stopping flag for each fit.

1
2
3
4
print(list(two=c(cycles=mcem2$cycles,converged=mcem2$converged,MC_loglik=mcem2$loglik),
  three=c(cycles=mcem3$cycles,converged=mcem3$converged,MC_loglik=mcem3$loglik),
  last_100_max_change_two=late_change(mcem2),
  last_100_max_change_three=late_change(mcem3)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$two
   cycles converged MC_loglik 
  500.000     0.000 -3900.838 

$three
   cycles converged MC_loglik 
   500.00      0.00  -3835.68 

$last_100_max_change_two
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max. 
0.007318 0.016347 0.024962 0.027096 0.034387 0.072374 

$last_100_max_change_three
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
0.01372 0.02745 0.03281 0.03619 0.04537 0.07106 

The three-factor run ended at the 500-cycle limit with a returned Monte Carlo log likelihood of $-3835.68$. Over its last 100 cycles, the maximum coefficient changes ranged from 0.01372 to 0.07106. Both runs reached their cycle limits before satisfying the $10^{-4}$ criterion. The two estimated log likelihoods summarize different response samples, so their difference cannot establish how much a third factor improves fit to the same examinees. Multidimensional item estimation by Monte Carlo EM is available in mirt.

14.5 Stochastic EM: preliminary updates and coefficient averaging

Each examinee supplies twelve binary answers, with two unobserved traits in the linear predictors of the items. A simulated trait vector for each person allows the complete-data derivatives to guide an item-intercept update. Write $z_i$ for the traits of examinee $i$, $y_{ij}$ for the response to item $j$, and $\eta_{ij}=d_j+a_j^\top z_i$ for its linear predictor. Conditional on $z_i$, the probability of a one is $p_{ij}=\exp(\eta_{ij})/(1+\exp(\eta_{ij}))$. The contribution of this response to the complete-data log likelihood is $y_{ij}\eta_{ij}-\log(1+\exp(\eta_{ij}))$. The normal trait density has no item parameters. Differentiating the response contribution with respect to $d_j$ gives $y_{ij}-p_{ij}$, since the derivative of the logarithmic term is $p_{ij}$. The derivative of $p_{ij}$ is $p_{ij}(1-p_{ij})$, so summing over examinees gives the score component for the intercept and the corresponding diagonal entry of the negative Hessian

\[S_{d_j}=\sum_i(y_{ij}-p_{ij}),\qquad J_{d_jd_j}=\sum_i p_{ij}(1-p_{ij}).\]

An excess of observed ones over predicted ones makes the score component for the intercept positive. If the traits were observed and the slopes fixed, dividing this score by the curvature would give the Newton correction. With unobserved traits, EM averages each response contribution over the trait distribution given the answers at the current item coefficients. At a candidate slope, the expectation of the linear term uses the conditional mean of $z_i$. The expectation of $\log(1+\exp(d_j+a_j^\top z_i))$ also depends on the shape of that distribution. Knowing its mean and covariance does not determine the expectation of this nonlinear function.

The procedure called stochastic EM in this chapter uses simulated traits to evaluate the complete-data derivatives, solves jointly for the free slopes and intercepts, and takes a fraction of the resulting correction.

In mirt, this name denotes the first two stages of Metropolis-Hastings Robbins-Monro (MH-RM) estimation. The textbook stochastic EM algorithm instead simulates a completed dataset and maximizes its complete-data likelihood; a damped, clipped Newton correction is not that exact maximization. In this chapter SEM abbreviates this stochastic EM; it must be distinguished from supplemented EM, an information-matrix method for standard errors, and from structural equation models.

Burn-in and averaging on the two-factor sample

Fit the model to the twelve items answered by the 500 examinees in the two-factor sample. Run the following from the book directory. The argument "SEM" selects the burn-in and averaging stages. Here burn-in names preliminary coefficient updates omitted from the reported coefficient average. It is different from discarding transitions for a fixed-parameter conditional distribution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
source("code/lib/dogleg.R")
source("code/lib/factored_secant.R")
source("code/lib/simulation.R")
source("code/lib/logit.R")
source("code/lib/integration.R")
source("code/lib/mcmc.R")
source("code/lib/stochastic_items.R")
source("code/lib/inference.R")
source("code/lib/multidim_items.R")
source("code/lib/lbfgsb.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")

Y <- readRDS("data/source/ch14/IRT12-two.rds")
sem2 <- multidim_mhrm(Y, 2L, "SEM")

The function sets the seed to 12345 and obtains its initial coefficients from multidim_start(), with free slopes of 0.851 and intercepts determined by the observed zero proportions. Inside multidim_mhrm(), par_vec contains the item and group parameters, and is_free selects the free item coefficients. The traits start at zero. Initial tuning starts with proposal variance 1 and supplies the trait matrix and variance for the first cycle. The fit above uses the supplied definition of multidim_mhrm(). The following excerpt from inside that function shows where it retunes and which traits it passes to the derivative calculation; 14.6 presents the complete fitting function. The derivatives come from multidim_complete_derivatives().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
multidim_complete_derivatives <- function(par_vec, design, Theta, with_hessian = TRUE) {
  L <- design$item_length
  n_par <- length(par_vec)
  grad <- numeric(n_par)
  hess <- matrix(0, n_par, n_par)
  for (j in seq_len(design$J)) {
    index <- (j - 1L) * L + seq_len(L)
    dd <- multidim_item_derivatives(par_vec[index], Theta, design$indicators[, 2L * j - 1L:0L, drop = FALSE],
      with_hessian)
    grad[index] <- dd$grad
    if (with_hessian) hess[index, index] <- dd$hess
  }
  list(grad = grad[design$is_free], complete_negative_hessian = -hess[design$is_free, design$is_free, drop = FALSE])
}

For each item, multidim_item_derivatives() (Section 14.4) is called at the supplied traits Theta with the observed indicator columns in place of expected counts, and the Hessian only when with_hessian is true. The function places the item gradient and Hessian in the item’s block and returns the gradient for the free coordinates and the complete-data negative Hessian.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Retune before the final burn-in update.
if (cycles == burn_in) {
  # A fresh start of the traits and two tuning runs aimed at acceptance 0.4.
  first <- multidim_tune_draws(matrix(0, N, q), par_vec, design, .5, target_acceptance = .4)
  second <- multidim_tune_draws(first$theta, par_vec, design, .5, target_acceptance = .4)
  theta <- second$theta; proposal_variance <- second$proposal_variance
}
# Only the traits retained on the last sweep enter the item derivatives.
for (i in seq_len(mh_draws))
  theta <- multidim_draw_traits(theta, par_vec, design, proposal_variance)
if (is.na(attr(theta, "log.lik"))) stop("Estimation halted. Model did not converge.")
# Complete-data gradient and negative Hessian at the current draws.
par_vec0 <- par_vec
deriv <- multidim_complete_derivatives(par_vec, design, theta)
grad <- deriv$grad; complete_negative_hessian <- deriv$complete_negative_hessian

At cycle 150, the last burn-in cycle, the routine resets the traits to zero. Each of the two tuning calls starts from variance 0.5 and targets acceptance 0.4. The second starts with the traits returned by the first.

Every estimation cycle takes five Metropolis-Hastings sweeps at its chosen variance. Only the fifth sweep’s retained matrix enters multidim_complete_derivatives(), one two-dimensional row per examinee. Five sweeps therefore provide one retained joint trait matrix for the derivative calculation, not an average of derivatives over five matrices.

To follow one such row, write $h_i(z;b)=\log f(y_i,z;b)$ for its joint log density at item vector $b$. At the current item vector $b_t$, evaluate both the retained row $z$ and the proposal $z^{\prime}$. For that row, ll_new - ll_old gives

\[h_i(z';b_t)-h_i(z;b_t).\]

If the log uniform draw is at least this large, the proposal is rejected. The routine restores $z$ and its log density evaluated at $b_t$. Acceptance retains the proposal and its density at the same $b_t$. Reusing a trait as a starting point therefore does not reuse a density from earlier item parameters.

In the fitting function, grad is the complete-data score vector and complete_negative_hessian is the negative Hessian on the free coordinates, both summed over examinees. Writing these as $S$ and $J$, the routine solves $J\Delta=S$ for the joint Newton correction $\Delta$ and uses a pseudoinverse if the direct solve fails. The next statements record the retained simulation and apply this correction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
record <- list(cycle = cycles, stage = stage_now, gamma = gamma,
  acceptance = attr(theta, "Proportion Accepted"), proposal_variance = proposal_variance,
  stored_log_density_sum = attr(theta, "log.lik"))
if (stage_now < 3L) {
  # Limit each free coordinate of the correction to [-1, 1], then take the gain times it.
  step <- gamma * pmin(pmax(corrected(complete_negative_hessian, grad), -1), 1)
  par_vec[is_free] <- par_vec[is_free] + step
  if (stage_now == 2L) {
    # Store the updated parameters for the stage-two average.
    row <- cycles - burn_in
    sem_store[row, ] <- par_vec
    if (!skip_stage3) sem_store2[[row]] <- complete_negative_hessian
  }
  record$max_change <- max(abs(step))
  history[[cycles]] <- record
  next
}

In both stages gamma is 0.2. Clipping each correction to $[-1,1]$ limits the absolute change in any one coefficient to 0.2. After the update, stage two stores the entire parameter vector in row cycles - burn_in.

At the start of the pass following cycle 250, the function assigns par_vec <- colMeans(sem_store) and exits the loop before another sweep. It returns those coefficients in sem2$par_vec and the free columns of the stored matrix in sem2$stage2. The converged value for this two-stage option reports completion of the prescribed stages, rather than satisfaction of a small-change or likelihood-score test.

Why average the coefficients once the starting values have had 150 cycles to change? Two sets of plausible traits can give different scores at exactly the same item coefficients. An examinee who answered one contributes $1-p_{ij}$ to the score component for the intercept. When a different trait draw raises that examinee’s predicted probability, the same answer contributes a smaller positive residual. The curvature changes with the draws as well. Even near a solution, a score evaluated on one retained matrix can point toward an increase and the next toward a decrease.

A constant gain passes the same fraction of each clipped correction to the coefficients throughout the averaging stage. A late update can therefore be appreciable even if several preceding updates were small. The column mean gives each updated value equal weight. A long excursion in one direction affects several successive rows because the next cycle starts from the coefficients and traits it inherits. The 100 rows thus give 100 observations of coefficient movement along one path.

Independent repeated fits and their last iterates are needed to measure variance reduction across runs. Assessing distance from a solution also requires a reference value.

Coefficient changes across the two stages

The cycle history locates coefficient changes relative to the retuning step. Each row below gives the fraction of examinees whose proposal was accepted on the fifth sweep and the largest absolute item-coefficient change made immediately afterward.

1
2
3
cycle_table <- function(fit, shown)
  do.call(rbind, lapply(fit$history[shown], as.data.frame))
print(cycle_table(sem2, c(1, 2, 5, 10, 50, 100, 149, 150, 151, 200, 250)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
   cycle stage gamma acceptance proposal_variance stored_log_density_sum
1      1     1   0.2      0.486         0.5558502              -5063.816
2      2     1   0.2      0.512         0.5558502              -5093.862
3      5     1   0.2      0.556         0.5558502              -5066.542
4     10     1   0.2      0.580         0.5558502              -5122.917
5     50     1   0.2      0.582         0.5558502              -5136.480
6    100     1   0.2      0.566         0.5558502              -5087.209
7    149     1   0.2      0.548         0.5558502              -5097.607
8    150     1   0.2      0.428         1.4377431              -5124.931
9    151     2   0.2      0.414         1.4377431              -5138.068
10   200     2   0.2      0.408         1.4377431              -5142.231
11   250     2   0.2      0.386         1.4377431              -5084.256
   max_change
1  0.14236762
2  0.10712642
3  0.08079865
4  0.05634735
5  0.03366539
6  0.02913363
7  0.03890544
8  0.04358894
9  0.03902945
10 0.04040757
11 0.03784223

Before retuning, the seven displayed rows use proposal variance 0.55585. Acceptance ranges from 0.486 to 0.582. For example, 0.486 in cycle 1 means that 243 of the 500 proposals on its fifth sweep were accepted. Each row uses that same denominator. The largest coefficient change is 0.14237 in cycle 1 and about 0.034, 0.029 and 0.039 at cycles 50, 100 and 149.

Across those seven displayed rows stored_log_density_sum ranges from $-5136.480$ to $-5063.816$. It adds the joint log densities of answers and retained traits, all evaluated at the item vector entering that cycle. A marginal log likelihood would instead integrate out each examinee’s traits.

At cycle 150 the retuned variance is 1.43774 and 214 of 500 proposals are accepted, a fraction of 0.428. For the three displayed averaging cycles, 151, 200 and 250, acceptance ranges from 0.386 to 0.414 and the maximum changes from 0.03784 to 0.04041. At cycle 250 at least one coefficient still moves by 0.03784.

The returned estimate is the average of the second-stage coefficient vectors. Row 1 of sem2$stage2 contains the update from cycle 151 and row 100 contains the update from cycle 250. Item 1 has one free slope and an intercept. Each of the other eleven items has two free slopes and an intercept, giving $2+11\times3=35$ columns. For each column, compare its standard deviation over the 100 rows with the signed difference between its last value and its mean.

1
2
print(rbind(stage2_sd = apply(sem2$stage2, 2, sd),
  last_minus_average = sem2$stage2[nrow(sem2$stage2), ] - colMeans(sem2$stage2)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
                          [,1]         [,2]       [,3]        [,4]        [,5]
stage2_sd           0.04348905  0.013777608 0.06072732  0.06121761  0.01461250
last_minus_average -0.03024308 -0.000973812 0.09834622 -0.01919447 -0.01917971
                         [,6]        [,7]         [,8]        [,9]      [,10]
stage2_sd          0.07250743  0.06821522  0.003455734 0.044278865 0.04720516
last_minus_average 0.07119913 -0.15200415 -0.001209627 0.008347254 0.02718720
                          [,11]      [,12]       [,13]         [,14]      [,15]
stage2_sd           0.010407329 0.06546391  0.08228508  0.0096317703 0.04096918
last_minus_average -0.004525746 0.09830985 -0.04933518 -0.0003721087 0.08863285
                         [,16]        [,17]     [,18]       [,19]       [,20]
stage2_sd           0.07140118  0.010768965 0.1015596  0.06151018  0.01476334
last_minus_average -0.01772036 -0.007750156 0.2253119 -0.06283619 -0.01412698
                         [,21]      [,22]       [,23]       [,24]       [,25]
stage2_sd           0.04686512 0.06905694  0.01675896  0.07519591  0.03570041
last_minus_average -0.15345616 0.05826412 -0.02235997 -0.10369648 -0.04636045
                         [,26]       [,27]        [,28]       [,29]       [,30]
stage2_sd           0.01226758  0.09208810  0.032493564  0.01166077  0.06291536
last_minus_average -0.01907300 -0.05984715 -0.005368659 -0.00895812 -0.17811436
                          [,31]       [,32]        [,33]       [,34]
stage2_sd           0.034229915  0.01377574  0.050233711  0.05661819
last_minus_average -0.005250807 -0.03331496 -0.006529376 -0.02991163
                          [,35]
stage2_sd           0.007348076
last_minus_average -0.007082108

The first column represents the first item’s slope. Its last entry is about 0.533. Taking mean(sem2$stage2[, 1]) gives 0.563 to three decimals, the same value as the first free coefficient in sem2$par_vec[sem2$design$is_free]. Subtracting the unrounded mean from the last entry gives the displayed $-0.03024$.

Across the 35 columns the standard deviations range from 0.00346 to 0.10156. They describe within-run coefficient spread, not standard errors of the mean of these dependent iterates. The last iterate falls 0.17811 below the mean in column 30 and 0.22531 above it in column 18.

A reported cycle count of 100 for this estimate counts the averaging cycles following burn-in. A decreasing gain would progressively reduce the fraction of each correction applied to the coefficients. Evaluating each item vector with the same marginal likelihood calculation compares their fit to the observed answers. These coefficient iterates are also not draws from a Bayesian posterior distribution for the item parameters.

The mirt package provides stochastic EM estimation for multidimensional item response models.

14.6 Metropolis-Hastings Robbins-Monro updates for scores and information

At the fitted first-item coefficients, supplied trait values allow a complete-data score calculation. Averaging that score under the conditional trait distribution recovers the score for the observed answers. Let $Y$ be the response matrix, $z$ the collection of all examinees’ trait vectors, and $b$ the column vector of free item coefficients. Write $f(Y,z;b)$ for the joint density and $L(b)=\int f(Y,z;b)\,dz$ for the likelihood of the observed responses. The complete-data score vector is $S_c(b;Y,z)=\nabla_b\log f(Y,z;b)$. Assume that $L(b)>0$, that the integration domain is fixed, and that $f$ is differentiable in a neighborhood of $b$ with its first derivatives bounded there by integrable functions of $z$. These conditions permit differentiation under the integral. Wherever the joint density is positive, its derivative equals the density times its score. Dividing by the observed-data likelihood gives the observed-data score

\[U(b)=\nabla_b\log L(b) =\frac{\int S_c(b;Y,z)f(Y,z;b)\,dz}{L(b)} =\int S_c(b;Y,z)f(z\mid Y;b)\,dz =E_b(S_c\mid Y).\]

The conditioning distribution in this equality is specific to the coefficients at which the score vector is evaluated. For the first item’s intercept, the identity averages the sum of the response residuals over the plausible traits of the people who supplied those answers. This gives a way to seek a zero of the observed-data score while drawing traits conditionally on the responses. This equality is Fisher’s identity for the score. Here score always means the derivative of a log likelihood with respect to the stated coefficients, not an examinee’s observed test score.

Consider what one draw contributes to this expectation. In the two-factor example it supplies a pair of traits for each of the 500 examinees. For item 1 the first slope and intercept are free, while the second slope remains fixed at zero. Let $y_{i1}$ be examinee $i$’s answer to item 1, $z_{i1}$ the retained first trait, and $p_{i1}$ the corresponding probability of answering one. That examinee contributes $z_{i1}(y_{i1}-p_{i1})$ to the score component for the free slope and $y_{i1}-p_{i1}$ to the component for the intercept. That examinee’s contribution to the negative Hessian for these two coefficients is $p_{i1}(1-p_{i1})$ times the outer product of $(z_{i1},1)^\top$ with itself. Write $J_c=-\nabla_b^2\log f(Y,z;b)$ for the complete-data negative Hessian.

After an item update, both current and proposed trait densities are evaluated at the new item vector. The score identity calls for a conditional expectation entirely at that vector. It applies to the differentiable response model; where the numerical predictor bounds are active, the coded derivatives require separate assessment.

Metropolis-Hastings Robbins-Monro estimation (MH-RM) takes the first two stages of stochastic EM as its starting calculation. The 100 second-stage updates supply 100 coefficient vectors. Each also supplies a negative Hessian evaluated at the entering coefficients and the traits used for that update. The fits use the mean of the updated vectors as the starting item vector and the mean of the negative Hessians as the starting curvature matrix.

The MH-RM routine and its information calculation

To follow one cycle inside multidim_mhrm(), start from the book directory and load the item routines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
source("code/lib/dogleg.R")
source("code/lib/factored_secant.R")
source("code/lib/simulation.R")
source("code/lib/logit.R")
source("code/lib/integration.R")
source("code/lib/mcmc.R")
source("code/lib/stochastic_items.R")
source("code/lib/inference.R")
source("code/lib/multidim_items.R")
source("code/lib/lbfgsb.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")

The next four blocks form multidim_mhrm(). The same function supports coefficient estimation and an information calculation with the fitted coefficients fixed. Its first block sets the seed, initializes the traits, tunes the proposals, and allocates storage.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
multidim_mhrm <- function(Y, q, method = c("MHRM", "SEM"), start = NULL, seed = 12345L,
                      n_cycles = 2000L, burn_in = 150L, sem_cycles = 100L, mh_draws = 5L,
                      conv_tol = .001, gain = c(.1, .75), information = FALSE) {
  method <- match.arg(method)
  design <- multidim_design(Y, q)
  par_vec <- if (is.null(start)) multidim_start(design) else start
  par_start <- par_vec
  is_free <- design$is_free
  if (!is.null(seed)) set.seed(seed)
  skip_stage3 <- method == "SEM"
  if (skip_stage3) n_cycles <- 1L
  N <- design$N
  # Tune the trait proposals at the starting coefficients.
  initial <- multidim_tune_draws(matrix(0, N, q), par_vec, design, 1)
  theta <- initial$theta
  proposal_variance <- initial$proposal_variance
  # Stage 2 keeps its coefficient vectors and negative Hessians for the start of stage 3.
  sem_store <- matrix(0, sem_cycles, length(par_vec))
  sem_store2 <- vector("list", sem_cycles)
  stage3_start <- burn_in + sem_cycles + 1L
  last_cycle <- n_cycles + burn_in + sem_cycles
  # Robbins-Monro averaging: old + gamma (new - old).
  toward <- function(old, new) old + gamma * (new - old)
  # The Newton-type correction M^{-1} g, by the pseudoinverse when M is singular.
  corrected <- function(M, g) {
    out <- tryCatch(solve(M, g), error = function(e) NULL)
    if (is.null(out)) as.vector(g %*% multidim_pseudoinverse(M)) else out
  }
  stage_now <- 1L; gamma <- .2; conv <- 0L
  history <- list(); Tau <- NULL; phi <- Phi <- 0
  stopping_rule_met <- FALSE

par_vec contains the item parameters together with fixed group parameters, and design$is_free selects the free coordinates. In item 1’s block these are the first slope and intercept. The matrix theta has two columns and one row per examinee in this example. sem_store stores the second-stage coefficient vectors by row and sem_store2 stores the negative Hessians in the same cycle order.

At the start of the cycle loop, burn_in and sem_cycles locate the transition from the preliminary stages to the decreasing gains.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  for (cycles in seq_len(last_cycle)) {
    if (cycles > burn_in && stage_now == 1L) stage_now <- 2L
    if (stage_now == 3L) gamma <- (gain[1L] / (cycles - stage3_start))^gain[2L]
    # Enter stage three at the two second-stage averages; its first gain is zero.
    if (cycles == stage3_start) {
      stage_now <- 3L; gamma <- 0
      par_vec <- colMeans(sem_store)
      if (!skip_stage3)
        Tau <- Reduce(function(s, h) s + h / sem_cycles, sem_store2[-1L],
          sem_store2[[1L]] / sem_cycles)
    }
    # Propose traits at the fitted coefficients throughout the information run.
    if (information) par_vec <- par_start
    if (skip_stage3 && cycles == stage3_start) {
      cycles <- cycles + sem_cycles - 1L
      break
    }
    if (cycles == burn_in) {
      first <- multidim_tune_draws(matrix(0, N, q), par_vec, design, .5,
        target_acceptance = .4)
      second <- multidim_tune_draws(first$theta, par_vec, design, .5, target_acceptance = .4)
      theta <- second$theta; proposal_variance <- second$proposal_variance
    }

Let $S_{c,t}$ and $J_{c,t}$ denote the total complete-data score and negative Hessian computed at the current item vector $b_t$ and the retained traits. Let $G_{t-1}$ be the previous curvature matrix. Giving the new curvature a fraction $\gamma_t$ of the weight and the old curvature the remaining fraction gives $G_t=(1-\gamma_t)G_{t-1}+\gamma_tJ_{c,t}$. With the traits fixed, a coefficient change $\delta$ changes the complete-data score locally by approximately $-J_{c,t}\delta$. Using the smoothed curvature $G_t$ in $G_t\delta=S_{c,t}$ scales the simulated correction. This matrix does not include the missing-information adjustment needed for the curvature of the observed-data log likelihood. Moving a fraction $\gamma_t$ of the way in that direction gives the two recurrences

\[G_t=G_{t-1}+\gamma_t(J_{c,t}-G_{t-1}),\qquad b_{t+1}=b_t+\gamma_tG_t^{-1}S_{c,t}.\]

The first cycle of stage three takes gain zero. It leaves the starting averages unchanged and its zero change counts toward the stopping rule. Number the subsequent cycles $t=1,2,\ldots$. Their gains are $\gamma_t=(0.1/t)^{0.75}$. The sum of the positive gains diverges because the exponent on $t$ is 0.75. The sum of their squares converges because the exponent is 1.5. The first property leaves enough total step size to correct a persistent discrepancy in the score. For example, if successive errors in one score component were uncorrelated with variance $\sigma^2$, their gain-weighted sum through cycle $T$ would have variance $\sigma^2\sum_{t=1}^{T}\gamma_t^2$. Neither property establishes that the coefficients in a finite run have reached a root. The gain sequence controls the weighting; convergence also depends on the conditional simulation and the behavior of the score and curvature near the solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    for (i in seq_len(mh_draws))
      theta <- multidim_draw_traits(theta, par_vec, design, proposal_variance)
    if (is.na(attr(theta, "log.lik"))) stop("Estimation halted. Model did not converge.")
    par_vec0 <- par_vec
    # One retained trait row per examinee contributes to these derivatives.
    deriv <- multidim_complete_derivatives(par_vec, design, theta)
    grad <- deriv$grad; complete_negative_hessian <- deriv$complete_negative_hessian
    record <- list(cycle = cycles, stage = stage_now, gamma = gamma,
      acceptance = attr(theta, "Proportion Accepted"), proposal_variance = proposal_variance,
      stored_log_density_sum = attr(theta, "log.lik"))
    # Both preliminary stages use the clipped correction and skip the update below.
    if (stage_now < 3L) {
      step <- gamma * pmin(pmax(corrected(complete_negative_hessian, grad), -1), 1)
      par_vec[is_free] <- par_vec[is_free] + step
      if (stage_now == 2L) {
        row <- cycles - burn_in
        sem_store[row, ] <- par_vec
        if (!skip_stage3) sem_store2[[row]] <- complete_negative_hessian
      }
      record$max_change <- max(abs(step))
      history[[cycles]] <- record
      next
    }

Inside the loop, par_vec0 saves the entering coefficients. multidim_complete_derivatives() sums the complete-data score and negative Hessian over examinees for each item, returning them in the free coordinates. The derivatives in grad and complete_negative_hessian use the trait matrix retained after the fifth sweep. During the first two stages the function stores the cycle record and advances directly to the next cycle.

An information call needs a different curvature from the one used to scale the updates. With the answers fixed, differentiating $U(b)$ also differentiates the conditional distribution used to average the score. Assume the same local domination for the second derivatives and finite conditional second moments of the score. Since $\log f(z\mid Y;b)=\log f(Y,z;b)-\log L(b)$, its derivative is $S_c-U$. Differentiating the conditional mean of $S_c$ now has two terms. The derivative of the score itself contributes $-E_b(J_c\mid Y)$. Differentiating the conditional density of the traits contributes $E_b[S_c(S_c-U)^\top\mid Y]$. Using $E_b(S_c\mid Y)=U$ and changing sign gives Louis’s identity for the observed information

\[I_{\mathrm{obs}}(b) =E_b(J_c\mid Y)-E_b(S_cS_c^\top\mid Y)+U(b)U(b)^\top =E_b(J_c\mid Y)-\operatorname{Cov}_b(S_c\mid Y).\]

The covariance measures how much the complete-data score can vary over plausible traits for the same answers. Subtracting it accounts for the information lost when the traits are unobserved. The complete-data curvature used to scale the coefficient updates includes no such subtraction.

Observed information measures the curvature of the summed log marginal likelihood. Its inverse supplies an approximate covariance estimate when the model is identified, the likelihood is sufficiently smooth, the estimate is a maximum allowing small changes in every free direction, and the sampling assumptions and positive definite information justify that approximation. The standard errors are the square roots of the diagonal entries of that full inverse. They describe sampling variation of the fitted coefficients across response samples. If the full information matrix fails these conditions, a few positive diagonal entries of its inverse do not justify individual Wald standard errors. When simulation supplies the scores or curvature, its numerical precision also matters.

The remaining lines apply the third-stage recurrence and its stopping test. An information call also accumulates derivatives for the calculation at fixed coefficients.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
    # Update the curvature before solving for the item correction.
    Tau <- toward(Tau, complete_negative_hessian)
    step <- gamma * corrected(Tau, grad)
    par_vec[is_free] <- par_vec0[is_free] + step
    record$max_change <- max(abs(step))
    history[[cycles]] <- record
    # Count consecutive changes below the tolerance.
    conv <- if (multidim_within_tolerance(par_vec0, par_vec, conv_tol)) conv + 1L else 0L
    long_enough <- !information || cycles >= 400L + burn_in + sem_cycles
    if (conv >= 3L && long_enough) {
      stopping_rule_met <- TRUE
      break
    }
    if (information) {
      if (cycles == stage3_start) {
        phi <- grad; Phi <- complete_negative_hessian
      }
      # Accumulate the total score and the negative Hessian minus the score outer product.
      phi <- toward(phi, grad)
      Phi <- toward(Phi, complete_negative_hessian - outer(grad, grad))
    }
  }
  converge <- skip_stage3 || stopping_rule_met
  reason <- if (skip_stage3) "stage_two_completed" else if (stopping_rule_met)
    "small_parameter_change" else "cycle_limit"
  if (information) par_vec <- par_start
  result <- list(par_vec = par_vec, cycles = cycles - burn_in - sem_cycles,
    converged = converge, reason = reason,
    proposal_variance = proposal_variance, history = history, design = design, method = method,
    initial_tuning = initial[c("accept_rates", "proposal_variances")],
    stage2 = sem_store[, is_free, drop = FALSE])
  if (information) {
    info <- Phi + outer(phi, phi)
    # The variance estimates come from the inverse of the full matrix.
    covariance <- vcov_information(info)
    result <- c(result, list(information = info, score = phi, SE = covariance$se,
      information_valid = covariance$valid, information_diagnostics = covariance))
  }
  result
}

The function vcov_information() checks the full information matrix before inversion. If its symmetry or positive definiteness checks fail, the returned standard errors are unavailable and the diagnostic records the reason. The function is in code/lib/inference.R.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
vcov_information <- function(A,J=diag(nrow(A)),tolerance=1e-9) {
  stopifnot(is.matrix(A),nrow(A)==ncol(A),is.matrix(J),ncol(J)==ncol(A))
  unavailable <- function(reason, eigenvalues = rep(NA_real_, nrow(A)))
    list(valid = FALSE, covariance = matrix(NA_real_, nrow(J), nrow(J)),
      se = rep(NA_real_, nrow(J)), inverse = matrix(NA_real_, nrow(A), ncol(A)),
      eigenvalues = eigenvalues, reason = reason)
  if (!all(is.finite(A)) || !all(is.finite(J))) return(unavailable("nonfinite information or Jacobian"))
  eig <- eigen((A+t(A))/2,symmetric=TRUE,only.values=TRUE)$values
  valid <- max(abs(A-t(A)))<=tolerance*max(1,max(abs(A))) && min(eig)>tolerance*max(eig)
  if(!valid) return(unavailable("asymmetric, nonpositive or nearly singular information", eig))
  inverse <- chol2inv(chol((A+t(A))/2))
  V <- J%*%inverse%*%t(J)
  list(valid=TRUE,covariance=V,se=sqrt(diag(V)),inverse=inverse,eigenvalues=eig)
}

The checks require the largest asymmetry to be at most $10^{-9}$ times the largest absolute entry (or $10^{-9}$) and the smallest eigenvalue of the symmetrized matrix to exceed $10^{-9}$ times the largest. The covariance is $JA^{-1}J^\top$, with $J$ the identity unless a Jacobian is supplied, and se contains the square roots of its diagonal.

The estimation run stops when every free coordinate changes by less than 0.001 on three successive cycles. A larger change in even one coordinate resets the count, as does a change exactly at the threshold. The limit is 2,000 third-stage cycles. The initial zero-gain cycle is included in this count. Thus three small changes can include one change imposed to be zero, rather than three informative corrections.

In the third-stage update Tau is $G_t$ after adding gamma * (complete_negative_hessian - Tau) to its old value. grad is $S_{c,t}$, and solve(Tau, grad) gives the direction. If this system cannot be solved directly, the function uses its pseudoinverse. The first two stages clipped each coordinate correction to the interval $[-1,1]$. The third stage multiplies the solved direction directly by the decreasing gain. Discarding small singular directions in the pseudoinverse is a numerical convention; it does not supply the missing-information correction or verify positive definiteness.

Fits and observed information for the two samples

Fit the model to the two-factor responses with this function. Immediately use the resulting coefficients as the start of the information calculation for the same examinees.

1
2
3
4
5
6
Y <- readRDS("data/source/ch14/IRT12-two.rds")
mhrm2 <- multidim_mhrm(Y, 2L)
info2 <- multidim_mhrm(Y, 2L, start = mhrm2$par_vec, seed = NULL,
  burn_in = 1L, information = TRUE)
print(c(cycles = mhrm2$cycles, converged = mhrm2$converged,
  information_cycles = info2$cycles))
1
2
            cycles          converged information_cycles 
               108                  1                400 

The fit starts its random stream at seed 12345. Setting seed = NULL in the information call continues from the state left by that fit. The first count of 108 refers to estimation after 150 burn-in cycles and 100 averaging cycles, giving 358 estimation cycles altogether. The information call reports its own count of 400.

In the information run, par_vec <- par_start restores the fitted coefficients before every cycle’s proposals. Accepted and retained log densities therefore refer to the same coefficients throughout these sweeps. The function still computes the change it would have taken and applies the stopping test to that hypothetical change. Here one burn-in cycle and 100 second-stage cycles precede 400 third-stage cycles. Stopping requires three consecutive small changes and at least 400 third-stage cycles. The break after the change test occurs before either phi or Phi is updated. Thus 399 third-stage derivative records enter the averages. The first initializes phi with the total score and Phi with the negative Hessian at zero gain. Subsequent gains recursively weight the score and complete_negative_hessian - outer(grad, grad). These are gain-weighted recursions, not equal-weight averages.

Each outer product uses the total score for one joint draw of all examinees’ traits, after the individual scores have been summed. The returned matrix is Phi + outer(phi, phi), the estimated observed information. Chapter 15 develops the sampling-covariance interpretation further.

Now read the separate response sample for the three-factor fit, which uses the default seed, and compare the estimation counts.

1
2
3
4
5
Y3 <- readRDS("data/source/ch14/IRT12-three.rds")
mhrm3 <- multidim_mhrm(Y3, 3L)
print(c(two_factor_cycles = mhrm2$cycles, converged = mhrm2$converged,
  three_factor_cycles = mhrm3$cycles, converged = mhrm3$converged,
  information_cycles = info2$cycles))
1
2
3
4
5
  two_factor_cycles           converged three_factor_cycles           converged 
                108                   1                 130                   1 
 information_cycles 
                400

Both estimation flags are one. The three-factor run required 130 third-stage cycles, or 380 including the two preliminary stages. The flags establish that each run met the small-change criterion. For example, the final three entries of mhrm2$history give maximum changes of about 0.00092, 0.00092 and 0.00093. A small gain can produce a small change even when the sampled score is appreciable. Standard errors require the curvature of the observed-data log likelihood at the attained estimate.

Return to the two-factor fit and its information calculation. Use that design to label the 35 free coordinates by item. In the table, a1_2 denotes item 2’s first slope and d_1 denotes item 1’s intercept. The column information gives the diagonal of the estimated observed information matrix before inversion.

1
2
3
4
5
6
design2 <- multidim_design(Y, 2L)
parameter_names <- c(unlist(lapply(1:12, function(j)
  paste0(c("a1", "a2", "d", "g", "u"), "_", j))),
  "MEAN_1", "MEAN_2", "COV_11", "COV_21", "COV_22")[design2$is_free]
print(data.frame(parameter = parameter_names, estimate = mhrm2$par_vec[design2$is_free],
  SE = info2$SE, score = info2$score, information = diag(info2$information)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
   parameter     estimate SE       score information
1       a1_1  0.574472304 NA -0.34161551    28.86562
2        d_1 -0.791430769 NA -0.28414587    97.41263
3       a1_2  0.339325416 NA -0.56091109    34.92070
4       a2_2  0.906247443 NA -0.28027727    25.75911
5        d_2 -0.783365416 NA -0.20042222    84.83330
6       a1_3  0.122156218 NA  0.91811369    38.57294
7       a2_3  0.152114146 NA  0.81283856    42.12151
8        d_3 -0.622030349 NA -0.09643263   112.26036
9       a1_4  0.438936662 NA -2.07303282    22.78587
10      a2_4  0.045198758 NA -0.35816706    43.05159
11       d_4 -0.382596196 NA -0.28472208   112.12940
12      a1_5 -0.217866041 NA  0.22601027    31.88201
13      a2_5  0.756308982 NA -0.56598275    29.36341
14       d_5 -0.413630675 NA  0.09741433    97.16439
15      a1_6  0.523776306 NA  2.10568105    19.77309
16      a2_6 -0.070788898 NA -0.36292597    54.47775
17       d_6 -0.120209719 NA -0.38289559   111.57324
18      a1_7  0.721123821 NA  2.11411383    23.13435
19      a2_7  0.086512607 NA -1.22170001    57.55078
20       d_7  0.012018134 NA -0.54865253   103.07822
21      a1_8  0.388148835 NA -1.19976537    24.75808
22      a2_8  1.061291468 NA -0.91765792    18.50059
23       d_8  0.272643140 NA -0.26882890    84.14793
24      a1_9  0.434805772 NA -0.75804867    43.09117
25      a2_9  0.299058575 NA  0.34318470    45.22943
26       d_9  0.565763364 NA -0.35733985   105.97123
27     a1_10  0.365682419 NA  0.83832736    44.36487
28     a2_10  0.018699463 NA -0.12569878    46.94459
29      d_10  0.502571941 NA -0.31434498   112.08534
30     a1_11  0.423389392 NA  1.79079125    29.67066
31     a2_11  0.617239287 NA  0.80192037    39.21893
32      d_11  0.714060626 NA -0.29695260    94.89508
33     a1_12  0.009215134 NA -1.88429075    38.10105
34     a2_12  0.128540448 NA -2.32737383    48.14768
35      d_12  1.050807491 NA -0.01536899    95.70042

For item 1, the slope is 0.57447 and the intercept is $-0.79143$. The SE column is NA for all 35 coordinates because the full information matrix did not pass the covariance check. Item 2’s first slope has a positive information diagonal of 34.92070, but this entry alone cannot justify a standard error. Positive diagonal entries describe curvature along individual coordinate axes; positive definiteness requires positive curvature along every nonzero direction.

For item 4’s first slope the simulated score is $-2.07303$. Without its Monte Carlo standard error, this value alone does not establish how far the exact observed-data score lies from zero.

The fit still supplies all the item estimates. The first slope of item 2, for example, is 0.33933. With the second trait fixed, a one-unit increase in the first trait raises the predicted log odds of a correct response by 0.33933. The missing standard error precludes a Wald interval from this calculation. A failed full-matrix check prevents the inverse from being reported as a sampling covariance, even when some diagonal entries of a direct inverse are positive.

The size of a difference between two fits’ coefficients alone cannot identify its cause or measure uncertainty in that coefficient. Separate coefficient intervals also require a valid information calculation. The R package mirt provides MH-RM estimation for multidimensional item response models.

14.7 Iterate averaging, stochastic convergence, and sparse design matrices

On the same examinees’ answers, averaging late coefficient updates can change how much a stochastic estimate varies across runs. The comparison is with the last iterate from each run. Let $b_t$ be the coefficient vector after update $t$, in the same identified coordinates throughout the run. Specify in advance a window from update $m$ through update $T$, leaving out the early updates most influenced by the starting values. The resulting estimate is

\[\bar b_{m:T}=\frac{1}{T-m+1}\sum_{t=m}^{T}b_t .\]

Each row being averaged is an estimate of the same item coefficients. In a simulated E step, the item coefficients remain fixed while draws of unobserved traits are used to approximate a conditional expectation. Iterate averaging can improve the precision of stochastic approximation, although the size of the improvement has varied across applications.

The variance over possible runs is available exactly for the quadratic $q(u)=-(u-1)^2/2$. Its maximum is at 1, its negative second derivative is 1, and its derivative at $u$ is $1-u$. Start at $u_0=0$ and add an independent error $e_t$ with mean zero and variance one to the derivative $1-u_{t-1}$ at each update. Taking a step of size 0.12 gives $u_t=u_{t-1}+0.12(1-u_{t-1}+e_t)$. Expanding the recursion gives the contribution of each earlier error to the current iterate.

\[u_t=0.88u_{t-1}+0.12(1+e_t) =\sum_{s=1}^{t}c_{ts}(1+e_s),\qquad c_{ts}=0.12(0.88)^{t-s}.\]

Compute the contribution of each error to the last iterate and to the average of iterates 61 through 120. These weights give an exact variance calculation for the quadratic example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
steps <- 120L
gain <- .12
coefficients <- matrix(0,steps,steps)
# Row i carries the coefficients of errors 1 through i.
for(i in seq_len(steps)) {
  if(i>1L) coefficients[i,] <- (1-gain)*coefficients[i-1L,]
  coefficients[i,i] <- gain
}
last <- coefficients[steps,]
# Average the coefficients of each error before calculating the variance.
average <- colMeans(coefficients[61:steps,,drop=FALSE])
print(data.frame(estimate=c("last iterate","average of iterates 61 through 120"),
  maximizer=1,expected_estimate=c(sum(last),sum(average)),
  algorithmic_variance=c(sum(last^2),sum(average^2))))
1
2
3
4
5
6
                            estimate maximizer expected_estimate
1                       last iterate         1         0.9999998
2 average of iterates 61 through 120         1         0.9999430
  algorithmic_variance
1           0.06382979
2           0.01450062

In coefficients, row $t$ gives these coefficients, with zeros for $s>t$. The update multiplies the previous row by 0.88 and inserts 0.12 for the new error. Row 120 defines the last iterate. Averaging rows 61 through 120 gives one coefficient for each error in the average of those 60 iterates.

For either estimator the sum of its coefficients gives its expectation, and the sum of their squares gives its variance because the errors are independent with unit variance. For example, error $e_{61}$ enters all 60 retained iterates, while $e_{120}$ enters only the last. With $c_{ts}=0$ for $s>t$, the average therefore has variance

\[\operatorname{Var}(\bar u_{61:120})=\sum_{s=1}^{120}\left(\frac{1}{60}\sum_{t=61}^{120}c_{ts}\right)^2.\]

Squaring each error’s combined coefficient retains the covariance between iterates that share it. The last iterate has expectation 0.9999998 and variance 0.06383. The average has expectation 0.9999430 and variance 0.01450. It retains slightly more of the effect of starting at zero but has about 23 percent of the last iterate’s variance across random streams. This is variation over the artificially added errors with the quadratic function fixed. It is neither the sampling covariance of item estimates from new examinees nor posterior variation in item parameters. A variance reduction alone does not settle a comparison of mean squared error, which also includes squared bias.

Comparing stages in one item fit

Return to the two-factor item fit, which supplies one sequence of updates. Its second-stage average and last iterate can be compared with the endpoint of the third stage. Continue with mhrm2 and design2 from the fit. To reproduce those objects in a fresh session, run the following block from the book directory. The fit uses its default seed of 12345.

1
2
3
4
5
6
7
8
for (file in c("stability","result","line_search","quasi_newton",
  "differentiation","dogleg","factored_secant",
  "simulation","logit","integration","mcmc","stochastic_items","inference","multidim_items"))
  source(paste0("code/lib/",file,".R"))
RNGkind("Mersenne-Twister","Inversion","Rejection")
Y <- readRDS("data/source/ch14/IRT12-two.rds")
mhrm2 <- multidim_mhrm(Y,2L)
design2 <- multidim_design(Y, 2L)

Read the first five and last three entries of the third-stage history to see how the gains and coefficient changes evolve along this run.

1
2
stage3 <- Filter(function(h) !is.null(h) && h$stage == 3L,mhrm2$history)
print(do.call(rbind,lapply(stage3[c(1:5,length(stage3)-(2:0))],as.data.frame)))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  cycle stage       gamma acceptance proposal_variance stored_log_density_sum
1   251     3 0.000000000      0.408          1.437743              -5144.833
2   252     3 0.177827941      0.430          1.437743              -5139.477
3   253     3 0.105737126      0.406          1.437743              -5141.329
4   254     3 0.078011577      0.452          1.437743              -5144.435
5   255     3 0.062871671      0.392          1.437743              -5156.647
6   356     3 0.005421357      0.380          1.437743              -5101.866
7   357     3 0.005382953      0.348          1.437743              -5079.354
8   358     3 0.005345178      0.420          1.437743              -5080.551
    max_change
1 0.0000000000
2 0.0340245662
3 0.0243358059
4 0.0127198999
5 0.0105321378
6 0.0009202180
7 0.0009217996
8 0.0009325844

The gain is zero at cycle 251, when the item vector is set to its second-stage average. The next four gains are about 0.178, 0.106, 0.078 and 0.063. By the final three cycles the gain is about 0.0054. The largest absolute coefficient changes in cycles 356, 357 and 358 are 0.00092, 0.00092 and 0.00093. All three are below the stopping tolerance of 0.001.

The next two rows give signed differences. For each free coordinate they subtract the final estimate from the average of the 100 second-stage updates and from the last of those updates, respectively.

1
2
print(rbind(average_to_estimate=colMeans(mhrm2$stage2)-mhrm2$par_vec[design2$is_free],
  last_iterate_to_estimate=mhrm2$stage2[nrow(mhrm2$stage2),]-mhrm2$par_vec[design2$is_free]))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
                                [,1]         [,2]         [,3]        [,4]
average_to_estimate      -0.01153535 -0.004299191 -0.003567131 -0.02935879
last_iterate_to_estimate -0.04177843 -0.005273003  0.094779093 -0.04855326
                                 [,5]        [,6]        [,7]         [,8]
average_to_estimate      -0.002081428 -0.01177131  0.03113415 -0.003901772
last_iterate_to_estimate -0.021261139  0.05942782 -0.12087000 -0.005111399
                                [,9]       [,10]        [,11]       [,12]
average_to_estimate      -0.05499913 -0.04147169 -0.002672650 -0.01909654
last_iterate_to_estimate -0.04665187 -0.01428449 -0.007198396  0.07921331
                               [,13]        [,14]        [,15]       [,16]
average_to_estimate       0.02218470 -0.003480612 -0.005390376 -0.01228989
last_iterate_to_estimate -0.02715048 -0.003852721  0.083242474 -0.03001025
                                [,17]       [,18]        [,19]        [,20]
average_to_estimate      -0.005915849 0.009616184  0.002644246 -0.009351311
last_iterate_to_estimate -0.013666004 0.234928037 -0.060191940 -0.023478288
                               [,21]         [,22]       [,23]        [,24]
average_to_estimate       0.02801871 -0.0003232992 -0.01015667  0.001937924
last_iterate_to_estimate -0.12543745  0.0579408193 -0.03251664 -0.101758558
                               [,25]        [,26]       [,27]        [,28]
average_to_estimate      -0.01578373 -0.008596386  0.01898302  0.004002904
last_iterate_to_estimate -0.06214417 -0.027669386 -0.04086412 -0.001365755
                                [,29]       [,30]       [,31]        [,32]
average_to_estimate      -0.003265232  0.04960787 -0.02279985 -0.007939879
last_iterate_to_estimate -0.012223352 -0.12850649 -0.02805065 -0.041254838
                               [,33]      [,34]        [,35]
average_to_estimate      -0.04385046 0.03647779  0.003171196
last_iterate_to_estimate -0.05037984 0.00656616 -0.003910912

The largest absolute entry in each row identifies its greatest coordinate displacement. Across the 35 free coordinates, the average differs from the endpoint by at most 0.05499913, on the first slope of item 4. The last iterate differs by as much as 0.23492804, on the first slope of item 7. Stage three started at the very average being compared with its endpoint. These distances describe movement along one fitted path. Neither the location of the likelihood maximum nor the variance over random streams is known from this comparison.

Step sizes, dependence between trait draws, and convergence

The acceptance proportions help interpret small coefficient changes. At cycle 252 the fifth sweep accepted a proposal for 43.0 percent of examinees and the largest coefficient change was 0.03402. At cycle 358 the acceptance proportion was 0.420, or 210 of 500 proposals, while the largest change was 0.00093. At the smaller gain, a correction of the same size produces a smaller change in the item coefficients. Acceptance counts record how many trait proposals succeeded. Even frequent acceptances can accompany short moves.

Assessing exploration of a fixed conditional distribution requires individual examinees’ paths at fixed item coefficients, including repeated values after rejection, and their autocorrelations over successive sweeps. Neither a favorable acceptance fraction nor one autocorrelation check establishes adequate exploration of the full distribution.

Changes in slopes and intercepts can be compared through the changes they imply in response probabilities at the same trait values. Investigating different local maxima requires distinct starting vectors under the same identification constraints, followed by likelihood, score and curvature checks at each endpoint.

The stopping rule concerns movement on a single path. An independent check would fix the response matrix and start, repeat the fit with separate random streams, and compare the variability of the second-stage averages with that of the last iterates across those runs. Repeating the score calculation at a fixed endpoint would estimate its Monte Carlo precision. Continuing beyond the stopping cycle could show whether the estimates subsequently move by an appreciable amount. The recorded history ends at cycle 358.

Dense and sparse incidence matrices for crossed ratings

Return to the crossed-rating model to check whether dense and sparse matrices produce the same linear predictors. Its incidence matrix selects one judge effect and one performance effect for each rating. Twenty judges each rate fifteen performances, yielding 300 pairs. The incidence matrix has 35 columns. For judge $g$ rating performance $h$, a one in column $g$ selects the judge effect and a one in column $20+h$ selects the performance effect. The other 33 entries are zero. Use incidence and effects from the crossed design. To recreate them in a fresh session, retain the 300 covariate draws that precede the effects in the random stream.

1
2
3
4
5
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1404)
incidence <- expand.grid(g=1:20,h=1:15)
x <- rnorm(nrow(incidence))
effects <- c(rnorm(20,sd=.5),rnorm(15,sd=.4))

Multiply each matrix by the same vector effects. For the first rating, both products must add the effects in positions 1 and 21.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
dense_time <- system.time({
  incidence_dense <- cbind(model.matrix(~factor(g)-1,incidence),
    model.matrix(~factor(h)-1,incidence))
  dense_product <- drop(incidence_dense%*%effects)
})
sparse_time <- system.time({
  nr <- nrow(incidence)
  # Each rating selects a judge column and a performance column.
  incidence_sparse <- Matrix::sparseMatrix(i=rep(seq_len(nr),2),
    j=c(incidence$g,20+incidence$h),
    x=1,dims=c(nr,35L))
  sparse_product <- as.numeric(incidence_sparse%*%effects)
})
print(data.frame(storage=c("dense","sparse"),
  bytes=c(as.numeric(object.size(incidence_dense)),
    as.numeric(object.size(incidence_sparse))),
  seconds=c(dense_time[["elapsed"]],sparse_time[["elapsed"]]),
  squared_norm=c(sum(dense_product^2),sum(sparse_product^2))))
1
2
3
  storage  bytes seconds squared_norm
1   dense 106208   0.001     132.2841
2  sparse   8840   0.229     132.2841

The squared norms both equal 132.2841 to the displayed precision. Equal norms could hide differences between individual ratings, so compare the products one entry at a time.

1
stopifnot(max(abs(dense_product-sparse_product))<1e-12)

The check requires the largest absolute difference to be below $10^{-12}$. The dense matrix occupies 106,208 bytes and the sparse matrix 8,840 bytes for the same 300 rows and 35 columns. Object size includes representation details such as names and attributes; the dense and sparse constructions do not give every such attribute the same form. The numbers compare these two objects, not a universal storage ratio.

The timer surrounds the construction of each matrix and one multiplication by the effect vector. The calls to measure object size fall outside the timed blocks. The dense block printed 0.001 seconds, at the displayed timer resolution. The sparse block took 0.229 seconds and can include the one-time loading of the sparse-matrix functions. The sparse matrix used about 8.3 percent of the dense matrix’s storage. The two elapsed times describe these dimensions in this session.

Judges 1 and 2 both rated performance 1, so their rows use the same performance effect even in sparse storage. Their response probabilities are multiplied conditional on that effect before it is integrated out. Changing how zeros are stored leaves the shared effects, and hence the coupled integrals in the likelihood, in place.

14.8 Checking reproducibility and agreement with quadrature and existing estimators

When two fits give different slopes for the same item, which set of coefficients assigns greater probability to the examinees’ answers? For independent examinees, the comparison can use the sum of their marginal log probabilities. A deterministic EM fit supplies a numerical reference. Analyze the two response samples separately. Each contains 500 examinees answering twelve items, but the answers in one sample came from a two-factor model and those in the other from a three-factor model. From the book directory, load the two observed response matrices and fit the two-factor model by quadrature EM.

1
2
3
4
5
6
7
8
9
10
.libPaths(c(".R-library", .libPaths()))
for (file in c("stability","result","line_search","quasi_newton",
  "differentiation","dogleg","factored_secant",
  "simulation","logit","integration","mcmc","stochastic_items","inference","multidim_items"))
  source(paste0("code/lib/",file,".R"))
RNGkind("Mersenne-Twister","Inversion","Rejection")
data14 <- list(two = readRDS("data/source/ch14/IRT12-two.rds"),
  three = readRDS("data/source/ch14/IRT12-three.rds"))
design2 <- multidim_design(data14$two,2L)
em2 <- multidim_em(data14$two,2L)

At a grid point, multiply the twelve response probabilities for one observed pattern and weight the product by the prior mass at that point. Summing over points gives the pattern’s marginal probability. Normalizing these products across the grid gives the conditional weights for the E step. Pattern frequencies then determine the expected counts in each item’s response categories. The BFGS M step updates the free slopes and intercepts with those counts fixed.

With its default EM method, multidim_em() places 31 equally spaced points from $-6$ to 6 on each of two axes, or 15 on each of three axes. The mass at a grid point is proportional to the standard normal density there.

After the M step, the function tests whether every coefficient changed by less than $10^{-4}$. If another cycle is needed, every third cycle is eligible for Ramsay acceleration when mstep_budget_multiplier > .01. The stopping test therefore measures the change from the entering coefficients to the ordinary M-step result, before any extrapolation. The fit has a limit of 500 cycles. The extrapolated vector is not accepted or rejected by a separate likelihood-increase check. After leaving the loop, the function saves the returned coefficients as the last row of em_path, including when the stopping test ends the loop.

Comparing two-factor fits on common quadrature rules

The numerical approximation to the log likelihood used during estimation depends on the integration rule and, for MCEM, on the random points drawn that cycle. Evaluate each attained vector on the same fixed nodes within its sample. If $B_i(z;b)$ is the probability of examinee $i$’s observed pattern at trait vector $z$ and coefficients $b$, a rule with nodes $z_s$ and normal probability weights $w_s$ gives

\[\ell_{\mathrm{grid}}(b)=\sum_i\log\!\left\{\sum_s w_s B_i(z_s;b)\right\}.\]

The logarithm comes after integrating one person’s response product. Define the two Gauss-Hermite product rules and the summary for the two-factor observations. At zero on both traits the slopes drop out of the linear predictor, so item 3 has success probability equal to the inverse logit of its intercept. The common evaluator multi_quadrature() computes the original logistic probabilities using stable logarithms, without the predictor clipping used during fitting. Thus this comparison can differ in its probability evaluation as well as its integration rule. Agreement between two finite grids is useful evidence of numerical stability but is not an integration-error bound or proof of a global maximum. The evaluator is in code/lib/stochastic_items.R.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
multi_quadrature <- function(Y,model,rule,gradient=FALSE) {
  eta <- sweep(tcrossprod(rule$nodes,model$loading),2,model$intercept,"+")
  # For each person's response pattern, compute its conditional log probability at each node.
  kernel <- Y%*%t(-log1pexp(-eta))+(1-Y)%*%t(-log1pexp(eta))
  kernel <- sweep(kernel,2,rule$log_weights,"+")
  maximum <- kernel[cbind(seq_len(nrow(kernel)),max.col(kernel,ties.method="first"))]
  mass_at_node <- exp(kernel-maximum)
  total <- rowSums(mass_at_node)
  norm <- maximum+log(total)
  if (!gradient) return(sum(norm))
  w <- mass_at_node/total
  mass <- colSums(w)
  successes <- crossprod(w,Y)
  q <- ncol(model$loading)
  score <- unlist(lapply(seq_len(ncol(Y)),function(j) {
    residual <- successes[,j]-mass*plogis(eta[,j])
    g <- drop(crossprod(rule$nodes[,item_row_coordinates(j,q),drop=FALSE],residual))
    if (j<=q) g[j] <- g[j]*model$loading[j,j]
    c(sum(residual),g)
  }),use.names=FALSE)
  list(loglik=sum(norm),score=score)
}

Here eta contains each item’s linear predictor at every node, and entry $(i,r)$ of kernel is the log probability of person $i$’s answers at node $r$ plus the log node weight. Subtracting each row’s largest entry before exponentiating and adding it back after taking the log of the row sum gives the person’s log marginal probability, and loglik is their sum. With gradient = TRUE, w contains the posterior node weights, mass and successes the expected counts at each node, and each item’s score is its summed residual for the intercept and the residuals weighted by the node coordinates for its free slopes (item_row_coordinates()); a slope on the diagonal of the first $q$ items is estimated as a logarithm, so its component is multiplied by the slope.

1
2
3
4
5
q15 <- product_rule(15L,2L)
q25 <- product_rule(25L,2L)
common_row <- function(model) c(loglik_15=multi_quadrature(data14$two,model,q15),
  loglik_25=multi_quadrature(data14$two,model,q25),
  item3_at_zero=plogis(model$intercept[3]))

Continue with the stochastic fits from the same responses. To recreate them in a fresh session after the setup above, use the following calls. The information call immediately follows the two-factor MH-RM estimate so that it continues that fit’s random stream.

1
2
3
4
5
6
7
8
9
set.seed(14041)
mcem2 <- multidim_em(data14$two,2L,"MCEM")
set.seed(14043)
mcem3 <- multidim_em(data14$three,3L,"MCEM")
sem2 <- multidim_mhrm(data14$two,2L,"SEM")
mhrm2 <- multidim_mhrm(data14$two,2L)
info2 <- multidim_mhrm(data14$two,2L,start=mhrm2$par_vec,seed=NULL,
  burn_in=1L,information=TRUE)
mhrm3 <- multidim_mhrm(data14$three,3L)

For each two-factor fit, multidim_model() extracts the item blocks from par_vec using design2. It returns loading, with items in rows and traits in columns, and the item intercept vector used by multi_quadrature(). The extraction preserves the fitted slope signs and excludes the fixed asymptote and group entries. Evaluate the person probabilities with 15 and then 25 nodes per axis.

1
2
3
4
multidim_model <- function(par_vec, design) {
  pars <- matrix(par_vec[seq_len(design$J * design$item_length)], design$item_length)
  list(loading = t(pars[seq_len(design$q), , drop = FALSE]), intercept = pars[design$q + 1L, ])
}

Each column of pars is one item’s block; its first $q$ entries are the slopes and the next one the intercept.

1
2
3
4
fits14 <- list(EM=em2,MHRM=mhrm2,SEM=sem2,MCEM=mcem2)
comparison <- do.call(rbind,lapply(fits14,function(f) c(cycles=f$cycles,
  common_row(multidim_model(f$par_vec,design2)))))
print(comparison)
1
2
3
4
5
6
     cycles loglik_15 loglik_25 item3_at_zero
EM       67 -3900.171 -3900.172     0.3482152
MHRM    108 -3901.684 -3901.684     0.3493198
SEM     100 -3901.790 -3901.790     0.3484335
MCEM    500 -3900.317 -3900.317     0.3494768

The deterministic fit stopped after 67 full cycles. The two-factor MCEM fit reached its 500-cycle limit. The reported counts refer to each method’s own stages. The EM fit’s two evaluations are $-3900.171$ and $-3900.172$. The vector comparison["EM","loglik_25"] - comparison[,"loglik_25"] subtracts at full precision. For MCEM, the difference is 0.145875 before rounding. MCEM is 0.146 below EM, MH-RM is about 1.512 below, and stochastic EM is about 1.618 below.

For item 3 at zero traits the corresponding probabilities are 0.34822 for EM, 0.34932 for MH-RM, 0.34843 for stochastic EM and 0.34948 for MCEM. That prediction concerns one item at one point. The likelihood includes all twelve answers and integrates over the traits of each examinee.

Comparing coefficients on aligned factor axes

A slope comparison also requires the same factor axes. For item 1 only the first slope is free. Item 2 can load on the first two traits. In three dimensions only items 3 onward can load on the third trait. The remaining slopes of each item precede its intercept in the free vector. In the two-factor fits the diagonal slopes of items 1 and 2 are free entries 1 and 4. Both are positive in all four fits. With the same triangular zeros and nonsingular leading block, these signs align the two-factor axes. The three-factor design adds a diagonal slope at free entry 8, whose sign is checked with that sample’s fits below. Inspect the two-factor vectors in the common order.

The separate multi_pack() representation puts each intercept first and uses the logarithm of a positive diagonal loading. The multidim_* free vector puts slopes first and leaves diagonal signs unrestricted. Coordinate vectors and their derivatives require an explicit transformation before they can be compared.

1
print(round(sapply(fits14,function(f) f$par_vec[design2$is_free]),4))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
           EM    MHRM     SEM    MCEM
 [1,]  0.6174  0.5745  0.5629  0.6201
 [2,] -0.8079 -0.7914 -0.7957 -0.7828
 [3,]  0.2486  0.3393  0.3358  0.2547
 [4,]  0.8154  0.9062  0.8769  0.8203
 [5,] -0.7661 -0.7834 -0.7854 -0.7687
 [6,]  0.1851  0.1222  0.1104  0.1857
 [7,]  0.1366  0.1521  0.1832  0.1417
 [8,] -0.6269 -0.6220 -0.6259 -0.6213
 [9,]  0.2359  0.4389  0.3839  0.2378
[10,]  0.1663  0.0452  0.0037  0.1666
[11,] -0.3798 -0.3826 -0.3853 -0.3723
[12,] -0.0945 -0.2179 -0.2370 -0.0916
[13,]  0.4691  0.7563  0.7785  0.4639
[14,] -0.3837 -0.4136 -0.4171 -0.3946
[15,]  0.7457  0.5238  0.5184  0.7485
[16,] -0.0379 -0.0708 -0.0831 -0.0264
[17,] -0.1354 -0.1202 -0.1261 -0.1049
[18,]  0.9857  0.7211  0.7307  0.9900
[19,]  0.1605  0.0865  0.0892  0.1752
[20,] -0.0007  0.0120  0.0027  0.0359
[21,]  0.0849  0.3881  0.4162  0.0936
[22,]  1.2629  1.0613  1.0610  1.2569
[23,]  0.2729  0.2726  0.2625  0.2571
[24,]  0.2624  0.4348  0.4367  0.2678
[25,]  0.4182  0.2991  0.2833  0.4171
[26,]  0.5532  0.5658  0.5572  0.5579
[27,]  0.3225  0.3657  0.3847  0.3231
[28,]  0.1173  0.0187  0.0227  0.1191
[29,]  0.4946  0.5026  0.4993  0.5058
[30,]  0.1823  0.4234  0.4730  0.1855
[31,]  0.8403  0.6172  0.5944  0.8361
[32,]  0.7262  0.7141  0.7061  0.7216
[33,] -0.0250  0.0092 -0.0346 -0.0267
[34,]  0.1279  0.1285  0.1650  0.1266
[35,]  1.0500  1.0508  1.0540  1.0472

Check the fixed zeros in each loading matrix, then take absolute differences in the free coordinates. Order the stochastic EM differences from largest to smallest.

1
2
3
4
5
6
7
8
9
for (fit in fits14) {
  loading <- multidim_model(fit$par_vec, design2)$loading
  stopifnot(all(loading[design2$pattern == 0] == 0))
}
free2 <- sapply(fits14, function(f) f$par_vec[design2$is_free])
stopifnot(all(free2[c(1, 4), ] > 0))
gaps <- abs(sweep(free2, 1, free2[, "EM"], "-"))
largest <- apply(gaps[, c("MHRM", "SEM", "MCEM")], 2, which.max)
sem_order <- order(gaps[, "SEM"], decreasing = TRUE)

The first two entries of sem_order are 21 and 13. The absolute differences between stochastic EM and EM are about 0.3313 at the first slope of item 8 and 0.3094 at the second slope of item 5. The largest MH-RM difference from EM is 0.30325072 at the first slope of item 8. The largest MCEM difference is 0.03654332 at the intercept of item 7.

The default stochastic EM and MH-RM fits share the same 100 second-stage vectors. Their mean is the stochastic EM estimate and the starting point of the third MH-RM stage. The two endpoints differ by at most 0.05499913. Their proximity reflects this shared path. The three small changes that stopped MH-RM still left its common-grid log likelihood about 1.512 below EM. Standard errors of item coefficients, when available, concern sampling uncertainty on the coefficient scale. They do not measure the size or uncertainty of that likelihood gap.

Replaying the fitted two-factor run

Would the same simulation reproduce the same coefficients? Refit the two-factor MH-RM model with its default seed and compare the complete stored parameter vectors.

1
2
again <- multidim_mhrm(data14$two,2L)
print(c(same_MHRM_estimate=identical(again$par_vec,mhrm2$par_vec)))
1
2
same_MHRM_estimate 
              TRUE 

The exact match tests replay at seed 12345. The same seed only specifies the same run when the random-number methods, data, settings and implementation are also the same; it is not an independent accuracy check.

Comparing fits on the three-factor sample

To compare methods on the separate three-factor sample, fit its deterministic reference and form new Gauss-Hermite rules with three axes. The three-factor EM fitting grid and its 15-point Gauss-Hermite evaluation both use 3,375 points, but their locations and weights differ.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
em3 <- multidim_em(data14$three,3L)
design3 <- multidim_design(data14$three,3L)
three <- list(EM=em3,MHRM=mhrm3,MCEM=mcem3)
rules3 <- lapply(c(15L,25L),function(n)product_rule(n,3L))
three_rows <- do.call(rbind,lapply(names(three),function(method) {
  f <- three[[method]]
  m <- multidim_model(f$par_vec,design3)
  data.frame(method=method,cycles=f$cycles,converged=f$converged,
    loglik15=multi_quadrature(data14$three,m,rules3[[1]]),
    loglik25=multi_quadrature(data14$three,m,rules3[[2]]),
    item3_at_zero=plogis(m$intercept[3]),
    max_coordinate_gap=max(abs(f$par_vec[design3$is_free]-em3$par_vec[design3$is_free])))
}))
print(three_rows)
1
2
3
4
5
  method cycles converged  loglik15  loglik25 item3_at_zero max_coordinate_gap
1     EM     55      TRUE -3836.309 -3836.309     0.3635142          0.0000000
2   MHRM    130      TRUE -3837.518 -3837.518     0.3628773          0.2727856
3   MCEM    500     FALSE -3836.400 -3836.399     0.3655853          0.0313847

Check the fixed zeros in the three-factor loading matrices and the signs of the slopes at free entries 1, 4 and 8.

1
2
3
4
5
6
for (fit in three) {
  loading <- multidim_model(fit$par_vec, design3)$loading
  stopifnot(all(loading[design3$pattern == 0] == 0))
}
free3 <- sapply(three, function(f) f$par_vec[design3$is_free])
stopifnot(all(free3[c(1, 4, 8), ] > 0))

The three diagonal slopes are positive in each fit. On the 25-point rule the three-factor values are $-3836.30925$ for EM after 55 full cycles, $-3837.51751$ for MH-RM after 130 third-stage cycles, and $-3836.39943$ for MCEM at the 500-cycle limit.

Changing random streams with the responses fixed

Return to the two-factor responses to investigate variation between random streams. Include each original fit once and add two runs of each method. For MCEM the original Mersenne-Twister seed was 14041. Start one L’Ecuyer-CMRG stream from seed 14082 and obtain the next with parallel::nextRNGStream(). For MH-RM switch back to Mersenne-Twister and pass the two new integer seeds to the estimator, which sets its own seed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
RNGkind("L'Ecuyer-CMRG","Inversion","Rejection")
set.seed(14082L)
streams <- list(.Random.seed,parallel::nextRNGStream(.Random.seed))
# Each MCEM fit starts at its assigned stream state.
mc_runs <- lapply(streams,function(stream) {
  assign(".Random.seed",stream,envir=.GlobalEnv)
  multidim_em(data14$two,2L,"MCEM")
})
# The stochastic optimizer sets its own integer seed.
RNGkind("Mersenne-Twister","Inversion","Rejection")
mh_seeds <- c(14083L,14084L)
mh_runs <- lapply(mh_seeds,function(seed) multidim_mhrm(data14$two,2L,seed=seed))
stream_fits <- list(MCEM=c(list(mcem2),mc_runs),MHRM=c(list(mhrm2),mh_runs))
stream_rows <- do.call(rbind,lapply(names(stream_fits),function(method)
  do.call(rbind,lapply(seq_along(stream_fits[[method]]),function(i) {
    f <- stream_fits[[method]][[i]]
    data.frame(method=method,run=i,cycles=f$cycles,converged=f$converged,
      stop=if(f$converged)"converged" else "limit",
      t(common_row(multidim_model(f$par_vec,design2))),
      max_coordinate_gap=max(abs(f$par_vec[design2$is_free]-em2$par_vec[design2$is_free])))
  }))))
print(stream_rows)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  method run cycles converged      stop loglik_15 loglik_25 item3_at_zero
1   MCEM   1    500     FALSE     limit -3900.317 -3900.317     0.3494768
2   MCEM   2    500     FALSE     limit -3900.214 -3900.215     0.3473417
3   MCEM   3    500     FALSE     limit -3900.237 -3900.237     0.3492516
4   MHRM   1    108      TRUE converged -3901.684 -3901.684     0.3493198
5   MHRM   2    111      TRUE converged -3900.729 -3900.729     0.3480266
6   MHRM   3    147      TRUE converged -3900.744 -3900.744     0.3485069
  max_coordinate_gap
1         0.03654332
2         0.02014703
3         0.02537580
4         0.30325072
5         0.21983017
6         0.19215297

The three MCEM fits stop at the limit of 500 full cycles, with log likelihoods of $-3900.3174$, $-3900.2145$ and $-3900.2372$ on the 25-point rule. The MH-RM fits at seeds 12345, 14083 and 14084 give $-3901.6835$, $-3900.7288$ and $-3900.7444$. Their reported counts of 108, 111 and 147 cover the third stage following 150 burn-in and 100 averaging cycles. The count of 100 for stochastic EM counts just the averaging stage. Read the range of the three log likelihood values for each method.

1
print(by(stream_rows$loglik_25,stream_rows$method,range))
1
2
3
4
5
6
stream_rows$method: MCEM
[1] -3900.317 -3900.215
------------------------------------------------------------ 
stream_rows$method: MHRM
[1] -3901.684 -3900.729

Each set of three values describes variation in attained fit to fixed answers, not repeated-sample uncertainty or a comparison of computation time. Replaying the first fit contributes no additional independent endpoint.

Comparing the book and package implementations

The book’s multidim_* functions are translated from parts of mirt (code/NOTICE.md), and the comparison uses the same data, starting values and specified fitting rules (Section E.3). The book evaluates both MH densities at the current item vector and retains final E-step counts for inference; differences in these calculations are recorded with the source correspondence.

Run the supplied comparison with mirt::mirt() version 1.45.1. For each response matrix it uses the same triangular two-parameter logistic model with factor means zero and identity covariance. The free slopes start at $0.5\times1.702$, and each intercept starts from the observed proportion of zeros with the same loading adjustment.

EM uses its fixed grid and acceleration. MCEM uses seeds 14041 and 14043 for the two dimensions and the increasing random grid. Both methods use the coefficient-change tolerance of $10^{-4}$ and the 500-cycle limit. Stochastic EM and MH-RM start at internal seed 12345. Stochastic EM returns the average after its two specified stages. MH-RM continues until three consecutive changes smaller than 0.001 in every free coordinate or the limit of 2,000 third-stage cycles.

1
2
RNGkind("Mersenne-Twister","Inversion","Rejection")
source("code/checks/ch14_reference.R")
1
2
3
4
5
6
7
8
9
10
11
                fit book_cycles package_cycles max_parameter_gap
1 EM, three factors          55             55      1.221245e-15
2   EM, two factors          67             67      9.094947e-13
3         MCEM, two         500            500      2.775558e-15
4       MCEM, three         500            500      8.881784e-16
5          SEM, two         100            100      1.058002e-01
6        MH-RM, two         108             98      7.359542e-02
7      MH-RM, three         130            130      1.338450e-01
      SE_gap finite_pairs same_missing 
          NA            0            0

The seven rows compare EM, MCEM and MH-RM in both dimensions and stochastic EM in two. EM and MCEM agree with the package to numerical precision in these examples. SEM and MH-RM differ after the book’s correction to evaluate both MH densities at the current item vector: the largest parameter gaps are about 0.106 for SEM, 0.074 for two-factor MH-RM and 0.134 for three-factor MH-RM. The two-factor MH-RM counts are 108 and 98. There are no finite standard-error pairs to compare, so SE_gap = NA does not establish agreement. Compare cycle counts, item parameters and returned information separately. The likelihood and score must be evaluated at each returned item vector before a difference can be interpreted.

A science assessment with observed item responses

The preceding simulations separate numerical behavior from sampling variation because the generating parameters are known. The SAT12 assessment provides an application in which they are unknown. Despite its name, this dataset contains 32 items, answered by 600 grade-12 examinees. It covers science content and is distributed with mirt. The dataset documentation reports a possible error in the scoring key for item 32. Exclude that item before fitting either model, using the published keys for items 1 through 31. This avoids selecting a key by whichever coding improves the current fit.

The original entries identify selected response options. Code 8 denotes a missing response. Convert it to NA, then retain respondents with complete answers on the 31 analyzed items because the multidimensional routines in this chapter require complete binary vectors. Score each retained response as one when it matches the item key and zero otherwise. A missing answer is therefore not silently scored as incorrect. The resulting analysis concerns this complete-case subset; the row counts make that restriction visible.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# start_application() loads the functions, sets the random-number methods and creates the folders.
# record_check() and record_review() save checks and review flags; neither changes an estimate.
source("code/lib/application_run.R", local = TRUE)
application <- start_application(14L)
record_check <- application$record_check
record_review <- application$record_review

data("SAT12", package = "mirt", envir = environment())
sat_raw <- as.matrix(SAT12)
stopifnot(ncol(sat_raw) == 32L, all(is.na(sat_raw) | sat_raw %in% c(1:5, 8)))
sat_key <- c(1, 4, 5, 2, 3, 1, 2, 1, 3, 1, 2, 4, 2, 1, 5, 3,
             4, 4, 1, 4, 3, 3, 4, 1, 3, 5, 1, 3, 1, 5, 4)
sat_responses <- sat_raw[, 1:31, drop = FALSE]
sat_responses[sat_responses == 8] <- NA
sat_rows <- which(complete.cases(sat_responses))
sat_Y <- 1L * sweep(sat_responses[sat_rows, , drop = FALSE], 2L, sat_key, "==")
stopifnot(all(colMeans(sat_Y) > 0), all(colMeans(sat_Y) < 1))
print(c(available = nrow(sat_raw), analyzed = nrow(sat_Y),
        excluded = nrow(sat_raw) - nrow(sat_Y), analyzed_items = ncol(sat_Y)))
print(data.frame(item = colnames(sat_Y), proportion_correct = colMeans(sat_Y)), row.names = FALSE)
saveRDS(list(raw = sat_raw, key = sat_key, excluded_item = 32L, rows = sat_rows, Y = sat_Y),
        file.path("data/source/ch14", "ch14-sat12.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
     available       analyzed       excluded analyzed_items 
           600            574             26             31 
    item proportion_correct
  Item.1          0.2874564
  Item.2          0.5783972
  Item.3          0.2857143
  Item.4          0.3815331
  Item.5          0.6219512
  Item.6          0.1620209
  Item.7          0.7595819
  Item.8          0.2090592
  Item.9          0.8850174
 Item.10          0.4216028
 Item.11          0.9825784
 Item.12          0.4181185
 Item.13          0.6655052
 Item.14          0.7282230
 Item.15          0.8257840
 Item.16          0.4198606
 Item.17          0.9651568
 Item.18          0.3536585
 Item.19          0.5470383
 Item.20          0.8815331
 Item.21          0.9163763
 Item.22          0.9355401
 Item.23          0.3118467
 Item.24          0.7334495
 Item.25          0.3797909
 Item.26          0.4668990
 Item.27          0.8675958
 Item.28          0.5435540
 Item.29          0.3466899
 Item.30          0.4512195
 Item.31          0.8397213

sat_key has 31 entries in the original item order. sat_rows identifies the retained examinees, and sat_Y contains their scored responses. The observed proportions correct identify items with few errors or few successes. Such items may provide little information about particular loading directions, even when the total sample size appears adequate. The setup above loads the chapter functions. The application script is code/examples/ch14-application.R; its inputs and fitted objects use data/source/ch14 and data/derived/ch14.

The analysis retains 574 examinees and excludes 26. Item 11 is answered correctly by about 98.3 percent of the retained sample, whereas item 6 is answered correctly by about 16.2 percent. These are observed marginal proportions, before introducing any latent dimensions. They do not by themselves determine an item’s discrimination or the number of factors.

For examinee $i$ and item $j$, specify the multidimensional 2PL model

\[\Pr(Y_{ij}=1\mid z_i) =\operatorname{logit}^{-1}(d_j+a_j^\top z_i), \qquad z_i\sim N_q(0,I_q),\]

with responses conditionally independent given $z_i$. Compare $q=2$ and $q=3$. The intercept $d_j$ gives the log odds of a correct response at the latent origin. Entry $a_{jk}$ gives the change in those log odds for a one-unit increase in factor $k$, at fixed values of the other factors. Each factor has unit variance. Fix $a_{jk}=0$ for $k>j$, as in the earlier examples, and orient the diagonal anchor loadings positively when reporting coefficients. The triangular zeros identify the axes, while the sign convention selects their directions. There are $31(q+1)-q(q-1)/2$ free item parameters, giving 92 for two factors and 121 for three.

The factors are exploratory dimensions of response variation. Their order is determined by the anchor items. The dataset’s science content does not justify naming these axes chemistry, biology or physics without item-level content and further measurement evidence. The model also fixes the lower asymptote at zero; multiple-choice scoring does not make that assumption automatically appropriate.

Fit the two-factor model by fixed-grid EM and fit both dimensions by MH-RM under three seeds. The data, item order, starting rule and algorithm settings remain the same across the three runs within each dimension.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sat_em <- multidim_em(sat_Y, 2L, n_quad = 31L, conv_tol = 1e-5, n_cycles = 1500L)
saveRDS(sat_em, file.path("data/derived/ch14", "ch14-em.rds"))
sat_seeds <- c(140401L, 140402L, 140403L)
sat_stochastic <- list()
for (q in 2:3) for (seed in sat_seeds) {
  name <- paste0("MHRM", q, "_", seed)
  message("Fitting ", name)
  sat_stochastic[[name]] <- multidim_mhrm(sat_Y, q, seed = seed,
    n_cycles = 2000L, burn_in = 150L, sem_cycles = 100L, mh_draws = 10L, conv_tol = .0005)
  saveRDS(sat_stochastic[[name]], file.path("data/derived/ch14", paste0("ch14-", name, ".rds")))
}
sat_fits <- c(list(EM2 = sat_em), sat_stochastic)
sat_models <- lapply(sat_fits, function(fit) {
  model <- multidim_model(fit$par_vec, fit$design)
  signs <- ifelse(diag(model$loading) < 0, -1, 1)
  model$loading <- sweep(model$loading, 2L, signs, "*")
  model
})

The returned design records the free loading pattern and fixed latent distribution. The item parameters are converted to loading matrices and intercept vectors before evaluation. Reflecting a whole loading column preserves the marginal model under a symmetric standard-normal factor; it changes only its reported direction. Each stochastic run is saved separately so that a later interrupted run does not erase earlier fits.

Evaluate the attained coefficients using common Gauss-Hermite product rules within each dimension. The two-factor comparison uses 21 and 31 nodes per axis, and the three-factor comparison uses 15 and 21. The finer rules therefore contain 961 and 9,261 points, respectively. They illustrate why adding a latent dimension increases the cost of deterministic integration even though the respondent count is unchanged.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
sat_rules <- list(`2` = list(lower = product_rule(21L, 2L), higher = product_rule(31L, 2L)),
                  `3` = list(lower = product_rule(15L, 3L), higher = product_rule(21L, 3L)))
sat_comparison <- do.call(rbind, lapply(names(sat_fits), function(name) {
  fit <- sat_fits[[name]]
  q <- fit$design$q
  lower <- multi_quadrature(sat_Y, sat_models[[name]], sat_rules[[as.character(q)]]$lower)
  higher <- multi_quadrature(sat_Y, sat_models[[name]], sat_rules[[as.character(q)]]$higher,
                             gradient = TRUE)
  reason <- if (identical(fit$method, "EM")) {
    if (isTRUE(fit$converged)) "small_parameter_change" else "cycle_limit"
  } else fit$reason
  stopifnot(length(reason) == 1L, !is.na(reason))
  data.frame(method = name, factors = q, cycles = fit$cycles,
    converged = fit$converged, reason = reason, loglik_lower = lower,
    loglik_higher = higher$loglik, grid_gap = higher$loglik - lower,
    max_abs_score = max(abs(higher$score)))
}))
print(sat_comparison, row.names = FALSE)
print(do.call(rbind, lapply(2:3, function(q) {
  rows <- startsWith(sat_comparison$method, paste0("MHRM", q))
  likelihood <- sat_comparison$loglik_higher[rows]
  data.frame(factors = q, seeds = sum(rows), loglik_min = min(likelihood),
    loglik_max = max(likelihood), loglik_range = diff(range(likelihood)))
})), row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
       method factors cycles converged                 reason loglik_lower loglik_higher      grid_gap
          EM2       2    385      TRUE small_parameter_change    -8791.949     -8791.949 -9.070507e-05
 MHRM2_140401       2    479      TRUE small_parameter_change    -8793.155     -8793.154  4.439685e-04
 MHRM2_140402       2    476      TRUE small_parameter_change    -8792.941     -8792.940  5.587782e-04
 MHRM2_140403       2    495      TRUE small_parameter_change    -8793.010     -8793.010  4.912781e-04
 MHRM3_140401       3    515      TRUE small_parameter_change    -8769.868     -8769.864  3.166145e-03
 MHRM3_140402       3    565      TRUE small_parameter_change    -8769.843     -8769.838  5.388667e-03
 MHRM3_140403       3    621      TRUE small_parameter_change    -8768.675     -8768.672  3.542894e-03
 max_abs_score
   0.001394548
   1.048578711
   0.817968285
   1.146252941
   1.490100836
   1.808933819
   1.565227268
 factors seeds loglik_min loglik_max loglik_range
       2     3  -8793.154  -8792.940    0.2140649
       3     3  -8769.864  -8768.672    1.1925173

grid_gap measures the change in the evaluated log likelihood when the integration rule is enlarged at fixed coefficients. The EM result supplies a convergence indicator but no textual reason, so its summary labels the parameter-change stopping condition or cycle limit explicitly. MH-RM supplies its own reason. max_abs_score evaluates the common criterion’s score in the chapter’s coordinates, including log coordinates for the positive anchor loadings. It is distinct from the MH-RM stopping test. A small change in recent stochastic iterates can coexist with a material score. The second table reports the range of common log likelihoods across seeds for each dimension. This range describes algorithmic variability on fixed responses; it is not a standard error over new examinees.

The two-factor EM fit attains a common log likelihood of about -8791.949, with maximum absolute score 0.00139. Its 21-to-31-node difference is about 0.000091. The three two-factor MH-RM fits give common log likelihoods from -8793.154 to -8792.940, approximately 0.99 to 1.21 units below EM. Their maximum absolute scores range from 0.818 to 1.146. All three therefore exceed the threshold of 0.1 that the application script applies to this score in its review flags, despite satisfying their parameter-change stopping conditions. Their integration differences are below 0.00056, so enlarging this evaluation grid has little effect on the reported likelihood gap.

For three factors, the seed-specific common log likelihoods range from -8769.864 to -8768.672, a range of about 1.193. The maximum absolute scores range from 1.490 to 1.809, and the largest integration difference is about 0.00539. The score threshold is a numerical diagnostic in the stated coordinates, not a significance test. The six MH-RM outputs illustrate that small recent parameter changes can occur before the marginal score has become adequately small. In this implementation the decreasing Robbins-Monro gain also makes updates smaller over time, so the update criterion alone does not certify proximity to a stationary point.

The reported MH-RM fits do not pass this additional stationarity diagnostic, and the application script records each failure as a review flag with record_review(). They are retained here to examine the stopping criterion and variability across seeds, rather than treated as verified maximum-likelihood solutions. A likelihood-based comparison of two and three factors would require further refinement and assessment of those attained solutions, together with a model-selection argument accounting for their different parameter counts. The higher three-factor likelihood alone does not establish an additional science ability. For the empirical probability summaries below, use the two-factor EM fit, which passes the score and integration checks.

Inspect this two-factor measurement model by comparing each item’s observed correct-response proportion with its marginal fitted probability. Then compare the observed and fitted probabilities that both items in a pair are answered correctly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
sat_primary <- sat_models$EM2
sat_rule <- sat_rules[["2"]]$higher
sat_probability <- plogis(sweep(tcrossprod(sat_rule$nodes, sat_primary$loading),
                                2L, sat_primary$intercept, "+"))
sat_weights <- exp(sat_rule$log_weights)
sat_item_table <- data.frame(item = colnames(sat_Y), loading1 = sat_primary$loading[, 1],
  loading2 = sat_primary$loading[, 2], intercept = sat_primary$intercept,
  observed_correct = colMeans(sat_Y),
  fitted_correct = drop(crossprod(sat_weights, sat_probability)))
sat_pair_table <- do.call(rbind, lapply(combn(ncol(sat_Y), 2L, simplify = FALSE), function(pair) {
  fitted <- sum(sat_weights * sat_probability[, pair[1]] * sat_probability[, pair[2]])
  observed <- mean(sat_Y[, pair[1]] * sat_Y[, pair[2]])
  data.frame(first = colnames(sat_Y)[pair[1]], second = colnames(sat_Y)[pair[2]],
    observed_both_correct = observed, fitted_both_correct = fitted,
    difference = observed - fitted)
}))
sat_pair_table <- sat_pair_table[order(abs(sat_pair_table$difference), decreasing = TRUE), ]
print(sat_item_table, row.names = FALSE)
print(head(sat_pair_table, 10L), row.names = FALSE)
saveRDS(list(fits = sat_fits, models = sat_models, comparison = sat_comparison,
  items = sat_item_table, pair_diagnostics = sat_pair_table),
  file.path("data/derived/ch14", "ch14-sat12.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    item  loading1    loading2  intercept observed_correct fitted_correct
  Item.1 0.9283413  0.00000000 -1.0554521        0.2874564      0.2895983
  Item.2 1.3745084  0.44311102  0.4878499        0.5783972      0.5869947
  Item.3 0.9820591  0.47324469 -1.1123497        0.2857143      0.2887080
  Item.4 0.7103011 -0.12454636 -0.5311673        0.3815331      0.3831508
  Item.5 0.9649944  0.28131020  0.6210325        0.6219512      0.6256889
  Item.6 1.1158280  0.25965291 -2.0314109        0.1620209      0.1614884
  Item.7 0.6615415  1.21845502  1.5506362        0.7595819      0.7602563
  Item.8 0.6420764  0.17392829 -1.4499263        0.2090592      0.2092460
  Item.9 0.2151734  0.72044845  2.2457906        0.8850174      0.8849272
 Item.10 0.8022598  0.69835514 -0.3716605        0.4216028      0.4251768
 Item.11 1.4165320  1.24940362  5.4376098        0.9825784      0.9801252
 Item.12 0.2236962 -0.23129396 -0.3386601        0.4181185      0.4181467
 Item.13 0.7838435  0.85698605  0.8824192        0.6655052      0.6676644
 Item.14 1.2584649 -0.05829530  1.2921707        0.7282230      0.7303434
 Item.15 0.9113507  1.20670018  2.1439317        0.8257840      0.8254021
 Item.16 0.7718480  0.01204654 -0.3541951        0.4198606      0.4223917
 Item.17 1.0580420  1.22021504  4.3392966        0.9651568      0.9630386
 Item.18 1.4962920  0.77439581 -0.8382446        0.3536585      0.3631704
 Item.19 0.7584634  0.24234879  0.2281308        0.5470383      0.5498692
 Item.20 1.4786276  0.56527940  2.7356979        0.8815331      0.8775280
 Item.21 0.3421619  0.79152232  2.6828526        0.9163763      0.9161156
 Item.22 1.1851576  0.94782044  3.4848707        0.9355401      0.9323046
 Item.23 0.8358870 -0.34917622 -0.9190850        0.3118467      0.3131891
 Item.24 0.9300605  0.87199930  1.3282576        0.7334495      0.7349636
 Item.25 0.9955523 -0.21867922 -0.5782942        0.3797909      0.3831465
 Item.26 1.5027120  0.28854895 -0.1256529        0.4668990      0.4780157
 Item.27 1.5554761  1.23127312  2.9087744        0.8675958      0.8642670
 Item.28 1.0021749  0.42326661  0.2438753        0.5435540      0.5489187
 Item.29 0.9184999  0.01386694 -0.7299269        0.3466899      0.3497447
 Item.30 0.2204799  0.32003438 -0.2021346        0.4512195      0.4513930
 Item.31 2.1508861  0.77069598  2.8167203        0.8397213      0.8360456
   first  second observed_both_correct fitted_both_correct  difference
  Item.5 Item.19             0.3519164          0.37844139 -0.02652502
  Item.2 Item.16             0.2630662          0.28852171 -0.02545551
  Item.5 Item.29             0.2282230          0.25215920 -0.02393621
 Item.12 Item.16             0.1620209          0.18535027 -0.02332936
  Item.4 Item.30             0.1567944          0.17888926 -0.02209484
  Item.8 Item.29             0.1132404          0.09159986  0.02164056
  Item.1 Item.30             0.1184669          0.13942382 -0.02095692
  Item.2 Item.26             0.3292683          0.35008374 -0.02081545
  Item.7 Item.16             0.3170732          0.33681137 -0.01973820
 Item.19 Item.28             0.3205575          0.33977723 -0.01921974

The item table separates slopes, intercepts and marginal probabilities. An item can have a high correct-response proportion while providing little discrimination around the latent origin. The pair table lists the ten largest signed discrepancies in joint success probabilities. It checks associations beyond the item margins. These are descriptive discrepancies; with many pairs, the largest one is not automatically evidence of an exceptional item pair. Repeated discrepancies involving a common item can guide a closer review of its content, scoring and relation to the proposed dimensions.

The largest single-item probability discrepancy is about 0.0111 for item 26. For the pair of items 5 and 19, the observed joint success proportion is 0.3519 and the fitted probability is 0.3784, a difference of about -0.0265. This pair illustrates how closely reproduced item margins can coexist with a larger discrepancy in their joint responses. The values describe this complete-case sample and this fitted model; they do not identify the cause of the discrepancy.

For a package comparison, use the identical triangular loading pattern, fixed factor means and identity covariance in mirt. Evaluate its two-factor EM solution with the same probability calculation and 31-by-31 rule used for the book fit.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
sat_pattern <- sat_em$design$pattern
colnames(sat_pattern) <- c("factor1", "factor2")
sat_reference <- mirt::mirt(sat_Y,
  mirt::mirt.model(sat_pattern, COV = matrix(FALSE, 2L, 2L)),
  itemtype = "2PL", method = "EM", quadpts = 31L, TOL = 1e-5,
  technical = list(NCYCLES = 1500L), verbose = FALSE)
sat_reference_items <- mirt::coef(sat_reference, simplify = TRUE, IRTpars = FALSE)$items
sat_reference_model <- list(loading = as.matrix(sat_reference_items[, c("a1", "a2")]),
                             intercept = sat_reference_items[, "d"])
sat_reference_loglik <- multi_quadrature(sat_Y, sat_reference_model, sat_rule)
sat_reference_gap <- abs(sat_reference_loglik - sat_comparison$loglik_higher[1])
print(data.frame(book_common_loglik = sat_comparison$loglik_higher[1],
  package_common_loglik = sat_reference_loglik, absolute_gap = sat_reference_gap,
  package_converged = mirt::extract.mirt(sat_reference, "converged")))
saveRDS(sat_reference, file.path("data/derived/ch14", "ch14-reference.rds"))
1
2
  book_common_loglik package_common_loglik absolute_gap package_converged
1          -8791.949             -8791.949            0              TRUE

The book and package EM fits give the same common log likelihood to the reported numerical precision, and the package reports convergence. This supports the two-factor calculation on this response matrix without validating the scoring of omitted item 32, the complete-case selection or the substantive interpretation of the factors. It also does not resolve the score warnings for the separately fitted MH-RM models. Those warnings remain recorded as review flags and in the interpretation above.

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