Post

Item response theory

An examinee answers several test items, some correctly and others incorrectly. Interpreting this pattern requires attention to the items as well as to the examinee. A correct answer to an easy item and a correct answer to a difficult item need not provide the same evidence about ability. The difficulty of the items, in turn, must be inferred from responses by people whose abilities are unknown. Item response theory (IRT) addresses this interdependence, relating each item’s response probabilities to ability so that the properties of the items and the meaning of a person’s answers can be assessed together. The chapter specifies models for binary and polytomous items, calibrates them by marginal maximum likelihood, examines weakly determined parameters and the ability distribution, and then turns from items to the estimation of each examinee’s ability.

10.1 Rasch, two-parameter, and three-parameter logistic models

Each examinee is an independent sampling unit. One observation within that unit is the response to a dichotomous item, scored 1 for a correct answer and 0 for an incorrect answer. Write $z_i$ for examinee $i$’s latent trait, or ability, and $Y_{ij}$ for that examinee’s response to item $j$. Ability describes the person, while the item parameters describe how a particular item functions for people at different abilities. The examples draw abilities from a standard normal distribution, so zero is the population mean and one unit is a population standard deviation. The item characteristic curve gives the probability of a correct answer at each ability. Its discrimination $a_j>0$ governs how sharply this probability rises, its intercept $d_j$ is the linear predictor at ability zero, and its lower asymptote $0\leq c_j<1$ allows a positive chance of success even at very low ability. The curve is

\[p_j(z)=\Pr(Y_{ij}=1\mid z_i=z) =c_j+(1-c_j)\operatorname{logit}^{-1}(a_jz+d_j).\]

The inverse logit is $\operatorname{logit}^{-1}(x)=1/(1+e^{-x})$, with no additional scaling constant in its argument here. Multiplying its value by $1-c_j$ and adding $c_j$ makes the response probability approach $c_j$ as ability decreases without bound and one as ability increases without bound. In multiple-choice testing, a positive lower asymptote accommodates correct answers from examinees who cannot reliably solve the item, for example through guessing. For this reason $c_j$ is often called a pseudo-guessing parameter. It represents the limiting probability of a correct answer, rather than the proportion of examinees who guess. Nor must it equal the reciprocal of the number of answer choices, since the options need not be chosen with equal probabilities.

Difficulty $b_j$ locates the item on the ability scale. It is the ability at which the probability reaches the midpoint between $c_j$ and one, namely $(1+c_j)/2$. With discrimination and lower asymptote fixed, a larger difficulty shifts the curve toward higher abilities and reduces the probability of a correct answer at any given ability. On the scale of these examples, a difficulty of one places the midpoint one population standard deviation above mean ability. When $c_j=0$, that midpoint probability is one half. To express this location using the intercept, set $z=b_j$ in the curve. The inverse logit must equal one half, so $a_jb_j+d_j=0$. Thus $d_j=-a_jb_j$, or $b_j=-d_j/a_j$, and the linear predictor can also be written as $a_j(z-b_j)$.

Discrimination describes how strongly differences in ability around the item’s difficulty appear as differences in the probability of a correct answer. Compare two items with the same difficulty and lower asymptote. A larger $a_j$ gives a higher probability just above that difficulty and a lower probability just below it, producing a steeper transition between the two. A smaller $a_j$ gives a more gradual transition over a wider range of abilities. The restriction $a_j>0$ makes the probability increase with ability. In this comparison $b_j$ is fixed, so the intercept changes with $a_j$ to preserve $d_j=-a_jb_j$. Fixing the intercept instead would also change the difficulty, except when the intercept is zero.

The intercept expresses the item’s location through its response probability at the population mean ability. At fixed discrimination and lower asymptote, increasing $d_j$ raises the probability at every ability and lowers the difficulty. Since $a_j$ is positive, a positive intercept corresponds to a negative difficulty, and a negative intercept to a positive difficulty. The code stores $a_j,d_j,c_j$ and obtains difficulty from $-d_j/a_j$. The intercept and difficulty therefore describe the same item location in different parameterizations, rather than adding two separate free parameters. The interpretation of the intercept as log odds depends on whether the lower asymptote is zero.

A Rasch item has $a_j=1$ and $c_j=0$, so its conditional log odds are $z+d_j=z-b_j$. Its intercept $d_j=-b_j$ is the log odds of a correct answer at ability zero. Only difficulty varies across items, so their curves have the same shape and differ in location. Fixing every discrimination at one sets the unit of ability. With the population mean fixed at zero, a marginal fit can then estimate the population variance in those units.

The two-parameter logistic (2PL) model allows each item its own positive discrimination and fixes $c_j=0$. Its two item parameters can be expressed as discrimination and difficulty, or as discrimination and intercept. The conditional log odds are $a_jz+d_j$, so $d_j$ is the log odds at ability zero. A one-unit increase in ability adds $a_j$ to those log odds and multiplies the odds by $\exp(a_j)$. The difficulty $b_j=-d_j/a_j$ again marks probability one half. Items can now differ in both the location and steepness of their curves.

In the three-parameter logistic (3PL) model, the lower asymptote can vary across items as well, giving the three item parameters $a_j,b_j,c_j$, or equivalently $a_j,d_j,c_j$. At ability zero the probability is $p_j(0)=c_j+(1-c_j)\operatorname{logit}^{-1}(d_j)$. With $c_j>0$, the intercept is the logit of the fraction $\lbrace p_j(0)-c_j\rbrace /(1-c_j)$, which measures the probability’s position between its lower and upper asymptotes. It is not the log odds of the full correct-response probability. Similarly, difficulty marks probability $(1+c_j)/2$, which exceeds one half when $c_j>0$. Evaluating a 3PL item at $c_j=0$ gives the corresponding 2PL curve. To estimate $c_j$ on the logit scale, however, the parameter $\log\lbrace c_j/(1-c_j)\rbrace $ must be finite, which requires $0<c_j<1$.

The slope of the probability curve gives a precise local measure of the change just described by discrimination. Write $t=\operatorname{logit}^{-1}\lbrace a_j(z-b_j)\rbrace $. With the item parameters fixed, its derivative with respect to ability is $a_jt(1-t)$. At the difficulty, $t=1/2$, giving

\[p_j'(b_j)=(1-c_j)a_j\left(\tfrac12\right)\left(1-\tfrac12\right) =\frac{(1-c_j)a_j}{4}.\]

This is a change in response probability per unit of ability near $b_j$. Thus $a_j$ controls the steepness but is not itself the slope on the probability scale. At a fixed lower asymptote, doubling $a_j$ doubles this slope. For the same discrimination, a positive lower asymptote reduces the slope because the probability rises over the smaller range from $c_j$ to one.

Item curves and simulated responses

From the book directory, load the numerical functions and set the random number generator for drawing responses.

1
2
3
4
5
6
7
.libPaths(c(".R-library", .libPaths()))
for (file in c("result", "stability", "families", "logit",
  "differentiation", "line_search",
  "quasi_newton", "newton", "glm", "transforms", "search", "simulation", "em",
  "em_acceleration", "integration", "dogleg", "factored_secant"))
  source(paste0("code/lib/", file, ".R"))
RNGkind("Mersenne-Twister", "Inversion", "Rejection")

The function dichotomous_item() checks the parameters and stores them with the model name and the number of categories, K. Given a vector of abilities, generate_dichotomous_responses() draws one independent uniform number for every examinee and item. It scores the answer as correct when that number is below the item probability. Responses are thus independent given an examinee’s ability, and each row of Y contains one examinee’s answers. This conditional independence of item responses is called local independence; it does not require the responses to be independent after averaging over ability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
dichotomous_item <- function(model = "2PL", a = 1, d = 0, c = 0) {
  stopifnot(model %in% c("Rasch", "2PL", "3PL"), length(a) == 1L,
    length(d) == 1L, length(c) == 1L, all(is.finite(c(a, d, c))),
    a > 0, c >= 0, c < 1)
  if (model == "Rasch") stopifnot(a == 1, c == 0)
  if (model == "2PL") stopifnot(c == 0)
  list(model = model, a = a, d = d, c = c, cuts = NULL, K = 2L)
}
generate_dichotomous_responses <- function(items, z) {
  U <- matrix(runif(length(z) * length(items)), length(z))
  Y <- vapply(seq_along(items), function(j) {
    item <- items[[j]]
    p <- item$c + (1 - item$c) * plogis(item$a * z + item$d)
    as.integer(U[, j] < p)
  }, integer(length(z)))
  colnames(Y) <- paste0("item", seq_along(items))
  Y
}

Figure 10.1 varies one item parameter at a time. The following calculation evaluates each curve at 501 abilities from $-5$ to 5.

1
2
3
4
5
6
7
8
9
10
11
12
13
curve_abilities <- seq(-5, 5, length.out = 501)
curve_settings <- list(difficulty = c(-1, 0, 1), discrimination = c(.5, 1, 2),
  lower_asymptote = c(0, .15, .3))
# Each matrix has one row per ability and one column per parameter setting.
curve_probabilities <- lapply(seq_along(curve_settings), function(panel) {
  vapply(curve_settings[[panel]], function(v) {
    a <- if (panel == 2) v else 1
    b <- if (panel == 1) v else 0
    c <- if (panel == 3) v else 0
    c + (1 - c) * plogis(a * (curve_abilities - b))
  }, numeric(length(curve_abilities)))
})
names(curve_probabilities) <- names(curve_settings)

Three panels show difficulty shifting curves to the right, discrimination changing their steepness around zero, and lower asymptotes lifting the left tails.

Figure 10.1. Probability of a correct response by ability. The solid, dashed and dotted lines correspond, in order, to difficulties of $-1$, 0 and 1 on the left, discriminations of 0.5, 1 and 2 in the middle, and lower asymptotes of 0, 0.15 and 0.30 on the right.

Raising difficulty moves the curve right. Raising discrimination lowers the probability below the common difficulty and raises it above that difficulty. In the third panel, all three items have difficulty zero. At that ability their probabilities are 0.50, 0.575 and 0.65.

The table compares three constructed items of difficulty zero at seven abilities. The following loads supply their constructors and probability functions. For the Rasch, 2PL and 3PL families, irt_item() calls dichotomous_item() and returns the same item list. The evaluator irt_prob() selects the probability function for the item model; Section 10.2 shows irt_item() and irt_prob(). In its returned probability matrix, rows follow the supplied abilities and columns follow responses 0 and 1, so column two gives the probability of a correct answer.

1
2
3
4
5
6
7
8
9
10
11
12
for (file in c("stability", "transforms", "irt"))
  source(paste0("code/lib/", file, ".R"), local = TRUE)
trait <- -3:3
settings <- data.frame(model = c("Rasch", "2PL", "3PL"), a = c(1, 2, 1), b = 0,
  c = c(0, 0, .15))
dichotomous <- do.call(rbind, lapply(seq_len(nrow(settings)), function(j) {
  s <- settings[j, ]
  item <- irt_item(s$model, a = s$a, d = -s$a * s$b, c = s$c)
  data.frame(trait, model = s$model, a = s$a, b = s$b, c = s$c,
    correct = irt_prob(item, trait)$probability[, 2])
}))
print(dichotomous, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 trait model a b    c     correct
    -3 Rasch 1 0 0.00 0.047425873
    -2 Rasch 1 0 0.00 0.119202922
    -1 Rasch 1 0 0.00 0.268941421
     0 Rasch 1 0 0.00 0.500000000
     1 Rasch 1 0 0.00 0.731058579
     2 Rasch 1 0 0.00 0.880797078
     3 Rasch 1 0 0.00 0.952574127
    -3   2PL 2 0 0.00 0.002472623
    -2   2PL 2 0 0.00 0.017986210
    -1   2PL 2 0 0.00 0.119202922
     0   2PL 2 0 0.00 0.500000000
     1   2PL 2 0 0.00 0.880797078
     2   2PL 2 0 0.00 0.982013790
     3   2PL 2 0 0.00 0.997527377
    -3   3PL 1 0 0.15 0.190311992
    -2   3PL 1 0 0.15 0.251322484
    -1   3PL 1 0 0.15 0.378600208
     0   3PL 1 0 0.15 0.575000000
     1   3PL 1 0 0.15 0.771399792
     2   3PL 1 0 0.15 0.898677516
     3   3PL 1 0 0.15 0.959688008

At zero, the Rasch and 2PL rows both give 0.5, while the 3PL row gives $0.15+0.85(0.5)=0.575$. At $z=-3$, doubling the discrimination from one to two lowers the probability from 0.0474 to 0.0025. For the 3PL item the same ability gives $0.15+0.85(0.0474)\approx0.1903$, still above its lower asymptote.

The IRT8 example and its companions simulate separate samples of 800 examinees. Their response matrices contain eight 2PL items in Y2, eight Rasch items in YR and sixteen 3PL items in Y3. The two eight-item sets share the same difficulties. The 3PL set repeats the eight discriminations, spaces sixteen difficulties over the same interval and assigns every item a lower asymptote of 0.15. Column sums count correct answers by item.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
slopes <- c(.7, .9, 1, 1.1, 1.2, .8, 1.3, 1)
difficulty <- seq(-1.5, 1.5, length.out = 8)
truth2 <- lapply(1:8, function(j) dichotomous_item("2PL",
  a = slopes[j], d = -slopes[j] * difficulty[j]))
truthR <- lapply(1:8, function(j) dichotomous_item("Rasch", d = -difficulty[j]))
# Repeat the eight slopes across sixteen items.
slopes16 <- rep(slopes, 2)
difficulty16 <- seq(-1.5, 1.5, length.out = 16)
truth3 <- lapply(1:16, function(j) dichotomous_item("3PL",
  a = slopes16[j], d = -slopes16[j] * difficulty16[j], c = .15))
set.seed(1001)
z2 <- rnorm(800)
Y2 <- generate_dichotomous_responses(truth2, z2)
set.seed(1002)
zR <- rnorm(800)
YR <- generate_dichotomous_responses(truthR, zR)
set.seed(1003)
z3 <- rnorm(800)
Y3 <- generate_dichotomous_responses(truth3, z3)
print(rbind(`2PL` = colSums(Y2), Rasch = colSums(YR)))
1
2
3
      item1 item2 item3 item4 item5 item6 item7 item8
2PL     574   569   495   447   358   315   209   168
Rasch   633   579   513   447   330   288   239   178

As difficulty increases from $-1.5$ to 1.5, the 2PL totals fall from 574 to 168. Of the 800 examinees in the separate Rasch sample, 633 answered its first item correctly. The longer test gives another set of totals.

1
print(colSums(Y3))
1
2
3
4
 item1  item2  item3  item4  item5  item6  item7  item8  item9 item10 item11 item12 item13 item14 item15 
   580    625    584    579    570    522    502    458    438    416    379    361    323    313    261 
item16 
   271 

In the 3PL sample, item one received 580 correct answers and items 15 and 16 received 261 and 271. These totals come from different samples and item parameters, with different difficulty spacing in the eight- and sixteen-item tests.

Log probabilities and their derivatives

For item calibration, meaning estimation of the item parameters from responses, take the probability of each observed answer at a common ability, multiply across the examinee’s items, and average that product over the population distribution of ability. The lists truth2, truthR and truth3 contain the generating item parameters; z2, zR and z3 contain the simulated abilities. Comparing fitted parameters or abilities with these known generating quantities assesses estimation error in the simulation. The marginal likelihood uses only the responses as observations.

For one item, suppress $j$ and write $\eta=az+d$, $t=\operatorname{logit}^{-1}(\eta)$ and $p=c+(1-c)t$. Let $\ell_0$ and $\ell_1$ denote the two log probabilities conditional on ability. Since $1-p=(1-c)/(1+e^\eta)$ and $p=(c+e^\eta)/(1+e^\eta)$,

\[\ell_0=\log(1-c)-\log(1+e^\eta),\qquad \ell_1=\log(c+e^\eta)-\log(1+e^\eta).\]

At $c=0$, $\ell_1=-\log(1+e^{-\eta})$. The derivative of $p$ with respect to $\eta$ is $(1-c)t(1-t)$. Dividing by $p$ for a correct answer and by $-(1-p)$ for an incorrect answer gives the pair in score_eta, in response order,

\[s_\eta=\left(\frac{\partial\ell_0}{\partial\eta}, \frac{\partial\ell_1}{\partial\eta}\right) =\left(-t,\frac{(1-c)t(1-t)}{p}\right).\]

Write $\ell=(\ell_0,\ell_1)$. By the chain rule, $\partial_a\ell=z s_\eta$ at fixed intercept, $\partial_d\ell=s_\eta$, and $\partial_z\ell=a s_\eta$. For a lower asymptote satisfying $0<c<1$, let $\gamma=\log\lbrace c/(1-c)\rbrace $. Since $\partial_\gamma c=c(1-c)$ and $\partial_c p=1-t$, the remaining pair is

\[\partial_\gamma\ell =\left(-c,\frac{c(1-c)(1-t)}{p}\right).\]

The function irt_dichotomous() evaluates one supplied item at every ability in z, with its parameters fixed. It returns log probabilities, probabilities, and derivatives of the log probabilities with respect to the item coordinates and ability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
irt_dichotomous <- function(item, z) {
  eta <- item$a * z + item$d
  t <- plogis(eta)
  log0 <- log1p(-item$c) - log1pexp(eta)
  log1 <- if (item$c == 0) -log1pexp(-eta) else {
    largest <- pmax(log(item$c), eta)
    largest + log(exp(log(item$c) - largest) + exp(eta - largest)) - log1pexp(eta)
  }
  logp <- cbind(log0, log1)
  # Differentiate the log probabilities for response 0 and response 1.
  score_eta <- cbind(-t, exp(log1p(-item$c) - log1pexp(-eta) - log1pexp(eta) - log1))
  P <- if (item$model == "Rasch") 1L else if (item$model == "2PL") 2L else 3L
  gradient <- array(0, c(length(z), 2L, P))
  # Item derivatives use a, d and logit c. A Rasch item has only d.
  if (P == 1L) gradient[, , 1] <- score_eta else {
    gradient[, , 1] <- score_eta * z
    gradient[, , 2] <- score_eta
  }
  if (P == 3L) gradient[, , 3] <- cbind(rep(-item$c, length(z)),
    exp(log(item$c) + log1p(-item$c) - log1pexp(eta) - log1))
  list(logp = logp, probability = exp(logp), gradient = gradient,
    d_log_probability_d_trait = item$a * score_eta)
}

The function first forms the linear predictors and the two log probabilities. For $c>0$, the code subtracts largest from both exponents before summing their exponentials and adds it back on the log scale. The returned matrices logp and probability each have length(z) rows and two columns, in response order 0 and 1. Exponentiating logp gives probability. The same log calculations evaluate the positive component of score_eta as the exponential of a log numerator minus log1, implementing the ratio above without first forming its small numerator and denominator. In gradient, the first index selects the ability, the second selects the response, and the third selects the item parameter. The 3PL slices follow $a,d,\gamma$ in order. The 2PL uses the first two and the Rasch item uses $d$ alone, so the array has three, two or one parameter slices. Multiplying score_eta by the discrimination gives the fourth return, d_log_probability_d_trait, another matrix with two response columns. Its entries differentiate the log probabilities with respect to ability.

The function dichotomous_check() compares these analytic derivatives with central differences of the same log probabilities. The calls use $h=10^{-6}$ for one item per model at seven abilities from $-40$ to 40.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
dichotomous_check <- function(item, z, h = 1e-6) {
  out <- irt_dichotomous(item, z)
  u <- switch(item$model, Rasch = item$d, `2PL` = c(item$a, item$d),
    `3PL` = c(item$a, item$d, qlogis(item$c)))
  rebuild <- function(v) switch(item$model, Rasch = dichotomous_item("Rasch", d = v[1]),
    `2PL` = dichotomous_item("2PL", a = v[1], d = v[2]),
    `3PL` = dichotomous_item("3PL", a = v[1], d = v[2], c = plogis(v[3])))
  # Perturb one item parameter and compare both response columns.
  coordinate_error <- max(vapply(seq_along(u), function(k) {
    e <- replace(numeric(length(u)), k, h)
    numerical <- (irt_dichotomous(rebuild(u + e), z)$logp -
      irt_dichotomous(rebuild(u - e), z)$logp) / (2 * h)
    max(abs(numerical - out$gradient[, , k]))
  }, 0.0))
  trait_error <- max(abs((irt_dichotomous(item, z + h)$logp -
    irt_dichotomous(item, z - h)$logp) / (2 * h) - out$d_log_probability_d_trait))
  c(coordinate_error = coordinate_error, trait_error = trait_error,
    sum_error = max(abs(rowSums(out$probability) - 1)), smallest = min(out$probability))
}
z_check <- c(-40, -6, -1, 0, .7, 3, 40)
check_items <- list(Rasch = dichotomous_item("Rasch", d = .3),
  `2PL` = dichotomous_item("2PL", a = 1.4, d = .3),
  `3PL` = dichotomous_item("3PL", a = 1.4, d = .3, c = .15))
print(t(vapply(check_items, dichotomous_check, numeric(4), z = z_check)))
1
2
3
4
      coordinate_error  trait_error    sum_error     smallest
Rasch     1.027956e-09 2.524757e-09 0.000000e+00 3.147258e-18
2PL       5.067022e-09 1.403032e-09 0.000000e+00 3.541773e-25
3PL       5.067022e-09 1.403032e-09 2.220446e-16 3.010507e-25

dichotomous_check() packs the item into u in the order of the analytic parameter slices, and its local rebuild() converts a perturbed vector back into an item. For the 3PL, qlogis() puts $c$ on the working logit scale and plogis() maps the perturbed coordinate back. For example, when k = 3, e contains zeros except for h in its third position. The two rebuilt items have unchanged $a$ and $d$ and use lower asymptotes $\operatorname{logit}^{-1}(\gamma+h)$ and $\operatorname{logit}^{-1}(\gamma-h)$. Their log-probability difference divided by $2h$ is compared with gradient[, , 3], the derivative in $\gamma$. The result coordinate_error is the largest absolute discrepancy over parameters, abilities and both responses. For trait_error, the item remains fixed while each supplied ability moves by $h$ in either direction. The remaining results are sum_error, the largest departure of a probability row sum from one, and smallest, the smallest evaluated probability. The returned vector contains four diagnostic numbers rather than a pass flag.

Across both responses and all seven abilities, the largest absolute discrepancies were below $5.1\times10^{-9}$ for item parameters and $2.6\times10^{-9}$ for ability. The two probabilities summed to one within $2.23\times10^{-16}$ even though the smallest probability was about $3.0\times10^{-25}$. Setting $c=0$ in the 3PL and $a=1$ in the 2PL checks the nested models. These checks concern the stated parameter values and perturbations; they do not establish numerical accuracy throughout the parameter space.

1
2
3
4
5
6
7
8
print(c(three_at_zero_vs_two = max(abs(
    irt_dichotomous(dichotomous_item("3PL", a = 1.4, d = .3, c = 0), z_check)$logp -
    irt_dichotomous(check_items$`2PL`, z_check)$logp)),
  two_at_one_vs_Rasch = max(abs(
    irt_dichotomous(dichotomous_item("2PL", a = 1, d = .3), z_check)$logp -
    irt_dichotomous(check_items$Rasch, z_check)$logp)),
  difficulty_conversion = max(abs(vapply(truth2, function(i) -i$d / i$a, 0) -
    difficulty))))
1
2
 three_at_zero_vs_two   two_at_one_vs_Rasch difficulty_conversion 
         0.000000e+00          0.000000e+00          2.220446e-16 

At all seven ability values, the 3PL log probabilities with $c=0$ matched the 2PL values exactly, as did the 2PL values with $a=1$ and the Rasch values. Recovering the eight generating difficulties as $-d/a$ gave a maximum absolute difference of about $2.22\times10^{-16}$. The mirt package fits all three dichotomous item models.

10.2 Graded response, generalized partial credit, and nominal response models

Suppose an examinee receives a score of 1 on an item with four possible scores, from 0 to 3. Everyone scoring at least 2 also scores at least 1. Removing those examinees from the group scoring at least 1 isolates the ones who scored exactly 1. The graded response model (GRM) applies this subtraction to probabilities. For a polytomous item with $K$ categories, let $Y$ be the observed score and write $C_h(z)=\Pr(Y\ge h\mid z)$ at ability $z$. This is a cumulative category response function: it gives the probability of reaching or exceeding category $h$, as distinct from the probability of category $h$ alone. For $h=1,\ldots,K-1$, the positive discrimination $a$ and threshold $b_h$ determine the curve. Because every response reaches 0 and none reaches $K$, the two end probabilities are fixed. The category response curve plots the probability $P_y(z)$ of the single score $y$. These probabilities satisfy

\[\begin{aligned} C_h(z)&=\operatorname{logit}^{-1}\{a(z-b_h)\},\quad 1\le h<K,\\ C_0(z)&=1,\quad C_K(z)=0,\\ P_y(z)&=C_y(z)-C_{y+1}(z),\quad 0\le y<K. \end{aligned}\]

Each threshold $b_h$ is the ability at which reaching category $h$ or higher has probability one half. With the other parameters fixed and threshold order preserved, raising $b_h$ lowers that cumulative probability at a given ability. The common discrimination $a$ is the increase in the cumulative log odds per unit of ability at every boundary; its effect on a single category probability follows from the difference of two cumulative curves. The thresholds increase strictly with $h$, so a higher boundary has a smaller probability of being reached at every finite ability. The category probabilities are positive and their sum telescopes to one.

In irt_item(), cuts stores the thresholds and its length determines the number of categories. For fitting, each cumulative logit has intercept $d_h=-ab_h$, the log odds of reaching category $h$ or higher at ability zero. The thresholds are in ability units, whereas these intercepts are on the cumulative-logit scale. Recovering $b_h=-d_h/a$ permits the same order check after a parameter change.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
irt_item <- function(model = "2PL", a = 1, d = 0, c = 0, cuts = NULL) {
  stopifnot(model %in% c("Rasch", "2PL", "3PL", "GRM", "GPCM", "nominal"))
  if (model %in% c("Rasch", "2PL", "3PL")) {
    return(dichotomous_item(model, a, d, c))
  } else if (model %in% c("GRM", "GPCM")) {
    stopifnot(length(a) == 1L, a > 0, length(cuts) >= 1L)
    if (model == "GRM") stopifnot(all(diff(cuts) > 0))
    K <- length(cuts) + 1L
  } else {
    stopifnot(length(a) == length(d), length(a) >= 2L, a[1] == 0, d[1] == 0)
    K <- length(a)
  }
  stopifnot(all(is.finite(c(a, d, c, cuts))))
  list(model = model, a = a, d = d, c = c, cuts = cuts, K = K)
}

For the four-score item, take $a=1$ and thresholds $(-1,0,1)$. At $z=0$, the probabilities of scores at least 1, at least 2 and at least 3 are $\operatorname{logit}^{-1}(1)$, $1/2$ and $\operatorname{logit}^{-1}(-1)$. The score-one probability is approximately $0.73106-0.50000=0.23106$. In R, plogis(z - c(-1, 0, 1)) gives these three cumulative probabilities. Placing a one before them and a zero after them gives cumulative, so -diff(cumulative) calculates the four category probabilities in score order. To evaluate the difference accurately when the cumulative probabilities are close, write $u=a(z-b_1)$ and $v=a(z-b_2)$. Factoring the difference gives

\[P_1(z)=\operatorname{logit}^{-1}(u)\{1-\operatorname{logit}^{-1}(v)\} \{1-\exp[-(u-v)]\}.\]

Here $u-v=a(b_2-b_1)>0$. The term -expm1(-gap) evaluates the last factor accurately even for a small gap. The first and last categories each use a single boundary. The first and second intercepts enter the score-one probability. The third sets the boundary for reaching score three.

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
irt_graded_response <- function(item, z) {
  Q <- length(z)
  K <- item$K
  a <- item$a
  t <- a * outer(z, item$cuts, "-")
  logp <- d_log_probability_d_trait <- matrix(0, Q, K)
  gradient <- array(0, c(Q, K, K))
  for (k in seq_len(K)) {
    # Array column k represents response category k - 1.
    lower <- upper <- numeric(Q)
    if (k == 1L) {
      logp[, k] <- -log1pexp(t[, 1L])
      upper <- -plogis(t[, 1L])
    } else if (k == K) {
      logp[, k] <- -log1pexp(-t[, K - 1L])
      lower <- plogis(-t[, K - 1L])
    } else {
      # Factor the difference between the two cumulative probabilities on the log scale.
      gap <- a * (item$cuts[k] - item$cuts[k - 1L])
      logp[, k] <- -log1pexp(-t[, k - 1L]) - log1pexp(t[, k]) + log(-expm1(-gap))
      lower <- plogis(-t[, k - 1L]) + 1 / expm1(gap)
      upper <- -plogis(t[, k]) - 1 / expm1(gap)
    }
    # Only the bounding intercepts contribute. The slope enters each linear predictor.
    if (k > 1L) {
      gradient[, k, 1L] <- lower * z
      gradient[, k, k] <- lower
    }
    if (k < K) {
      gradient[, k, 1L] <- gradient[, k, 1L] + upper * z
      gradient[, k, k + 1L] <- upper
    }
    d_log_probability_d_trait[, k] <- a * (lower + upper)
  }
  list(logp = logp, probability = exp(logp), gradient = gradient,
    d_log_probability_d_trait = d_log_probability_d_trait)
}

For a graded score $1\leq y\leq K-2$, put $D_h=C_h(1-C_h)$ for each threshold index $h=1,\ldots,K-1$. Differentiating the difference of cumulative probabilities and dividing by $P_y$ gives $L=D_y/P_y$ for intercept $d_y$ and $U=-D_{y+1}/P_y$ for $d_{y+1}$. The derivatives with respect to all other intercepts vanish. At the end categories the fixed boundary contributes zero. With intercepts fixed, both linear predictors change by $z$ per unit change in $a$, giving $\partial_a\log P_y=z(L+U)$. The derivative with respect to the trait is $a(L+U)$. This explains why the graded function multiplies the same lower + upper by ability for the derivative with respect to the slope and by discrimination for the derivative with respect to the trait. Fixing the thresholds instead would also change the intercepts $d_h=-ab_h$.

The function irt_graded_response() evaluates the category probabilities on the log scale. Its matrix t contains one row per ability and one column per threshold. Array column k = 2 represents score one, so it uses columns 1 and 2 of t. The evaluator returns the same four fields as the dichotomous evaluator, now with one column per category. Its derivative array has $K$ parameter slices in the order $a,d_1,\ldots,d_{K-1}$, with the intercepts fixed when differentiating in $a$.

Adjacent-category steps: the generalized partial credit model

A different interpretation of a step compares the probability of score $h$ directly with that of score $h-1$. The generalized partial credit model (GPCM) assigns a step parameter $b_h$ to that pair. At $z=b_h$ the two scores are equally probable. The step parameters need no ordering because each specifies a comparison with a different neighbor. The partial credit model fixes the discrimination at one across items; allowing it to differ gives the generalized partial credit model. In this chapter, subsequent references to partial credit items use this generalized model unless a unit discrimination is imposed. Summing the adjacent log ratios gives the log ratio to score zero. Writing this sum as $\eta_y$, with $\eta_0=0$, gives

\[\begin{aligned} \log\frac{P_h(z)}{P_{h-1}(z)}&=a(z-b_h),\\ \eta_y&=\sum_{h=1}^y a(z-b_h)=ayz+d_y,\qquad d_y=-a\sum_{h=1}^y b_h,\\ P_y(z)&=\frac{e^{\eta_y}}{\sum_{k=0}^{K-1}e^{\eta_k}}. \end{aligned}\]

Here $a>0$ is the increase in each adjacent-category log ratio per unit of ability: a one-unit increase multiplies $P_h/P_{h-1}$ by $\exp(a)$. Raising step $b_h$ at fixed ability and discrimination lowers that pair’s probability ratio. At the step the two category probabilities are equal, but each need not equal one half because the other categories remain possible. Thus score $y$ has slope $ay$ and a category intercept $d_y$, with $d_0=0$. The intercept is $\log\lbrace P_y(0)/P_0(0)\rbrace $, a comparison with score zero accumulated across steps; each $b_h$ is instead a location on the ability scale.

In irt_category_logits(), a row contains $\eta_y=\log\lbrace P_y(z)/P_0(z)\rbrace $ for all categories at one ability. These are log probability ratios relative to category zero, rather than the separate binary logits $\log\lbrace P_y(z)/(1-P_y(z))\rbrace $. Subtracting their logsumexp() before exponentiating gives that row’s probabilities.

The normalizer also determines the log-probability derivatives. For any parameter $\xi$ entering the linear predictors, let $A=\log\sum_k e^{\eta_k}$. Differentiation gives

\[\partial_\xi A =\frac{\sum_k e^{\eta_k}\partial_\xi\eta_k}{\sum_j e^{\eta_j}} =\sum_k P_k(z)\partial_\xi\eta_k,\qquad \partial_\xi\log P_y(z)=\partial_\xi\eta_y-\partial_\xi A.\]
1
2
3
4
5
6
7
8
9
10
irt_category_logits <- function(z, slope, intercept) {
  logits <- sweep(outer(z, slope), 2L, intercept, "+")
  logp <- logits - apply(logits, 1L, logsumexp)
  probability <- exp(logp)
  # The derivative of the log normalizer is the probability-weighted slope.
  d_log_probability_d_trait <- matrix(slope, length(z), length(slope), byrow = TRUE) -
    drop(probability %*% slope)
  list(logits = logits, logp = logp, probability = probability,
    d_log_probability_d_trait = d_log_probability_d_trait)
}

The function irt_partial_credit() evaluates the adjacent-category model using these category logits. Here cuts stores adjacent-category step parameters, whose order is unrestricted; for a graded item the same field stores strictly ordered cumulative thresholds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
irt_partial_credit <- function(item, z) {
  K <- item$K
  scores <- seq_len(K) - 1L
  # Summing adjacent-category logits sets the intercept for each score.
  intercept <- c(0, -item$a * cumsum(item$cuts))
  result <- irt_category_logits(z, item$a * scores, intercept)
  gradient <- array(0, c(length(z), K, K))
  # The first slice holds derivatives with respect to the slope, later slices those for the intercepts.
  gradient[, , 1L] <- outer(z, scores) - drop(result$probability %*% scores) * z
  for (h in seq_len(K - 1L)) {
    indicator <- as.numeric(seq_len(K) == h + 1L)
    gradient[, , h + 1L] <- matrix(indicator, length(z), K, byrow = TRUE) -
      result$probability[, h + 1L]
  }
  list(logp = result$logp, probability = result$probability, gradient = gradient,
    d_log_probability_d_trait = result$d_log_probability_d_trait)
}

The function supplies the score multiples as slopes and computes the intercepts with cumsum(). Taking successive differences reverses the construction during fitting, since $b_h=-(d_h-d_{h-1})/a$.

For partial credit, differentiating $ayz+d_y$ at fixed category intercepts and subtracting its mean gives $z\lbrace y-E(Y\mid z)\rbrace $. The log-probability derivative with respect to the trait is $a\lbrace y-E(Y\mid z)\rbrace $. For a nonreference category intercept, write $r_{yh}=\mathbf{1}\lbrace y=h\rbrace -P_h(z)$, the category indicator minus its probability. This is the derivative with respect to the nonreference intercept $d_h$.

Unordered categories: the nominal response model

When responses identify alternatives such as the options on a multiple-choice question, their labels alone give no reason to space the slopes at multiples of one discrimination. The nominal response model gives category $k$ its own linear predictor $\eta_k=a_kz+d_k$. Adding a common slope or a common intercept to every linear predictor leaves every probability unchanged. Setting $a_0=d_0=0$ fixes category zero as the reference, so $\eta_k$ is the log probability ratio of category $k$ to category zero. Exponentiating and dividing by the sum of all $K$ exponentials gives the category probabilities. At ability zero, $d_k$ is the log probability ratio of category $k$ to the reference. The slope $a_k$ is the change in that log ratio per ability unit, so a one-unit increase multiplies the ratio by $\exp(a_k)$. A positive $a_k$ favors category $k$ relative to category zero as ability rises; whether its probability itself rises also depends on the other category slopes.

The calculation can use two parameterizations. Direct coordinates store the $K-1$ nonreference slopes followed by their intercepts. The numbers attached to nominal categories are labels, not ordered ability scores.

For $K\ge3$ and a nonzero starting last slope, write $a_k=s\,t_k$, with $s=a_{K-1}/(K-1)$, $t_0=0$ and $t_{K-1}=K-1$. The free slope parameters are now $s$ and the $K-2$ middle relative slopes $t_k=a_k/s$. The common multiplier must remain nonzero for this conversion. Both representations recover slopes and intercepts in the original category order. The multiplier may be negative. These constraints remove the redundancy among category predictors within an item; a collection of nominal items under a symmetric ability distribution can still reverse all slopes and the direction of ability together without changing the marginal response probabilities.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
irt_direct_nominal_slopes <- function(item) {
  item$K == 2L || identical(item$nominal_coordinates, "category_slopes") ||
    item$a[item$K] == 0
}

irt_item_pack <- function(item) {
  # Graded intercepts use individual thresholds. Partial credit sums the steps.
  # For a nominal item, pack direct slopes or a multiplier and relative slopes.
  switch(item$model, Rasch = item$d, `2PL` = c(item$a, item$d),
    `3PL` = c(item$a, item$d, prob_to_logit(item$c)),
    GRM = c(item$a, -item$a * item$cuts),
    GPCM = c(item$a, -item$a * cumsum(item$cuts)),
    nominal = {
      K <- item$K
      if (irt_direct_nominal_slopes(item)) return(c(item$a[-1], item$d[-1]))
      s <- item$a[K] / (K - 1)
      c(s, if (K > 2L) item$a[2:(K - 1)] / s, item$d[-1])
    })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
irt_item_unpack <- function(u, template) {
  stopifnot(all(is.finite(u)), length(u) == length(irt_item_pack(template)))
  type <- template$model
  K <- template$K
  switch(type,
    Rasch = irt_item(type, d = u[1]),
    `2PL` = irt_item(type, a = u[1], d = u[2]),
    `3PL` = irt_item(type, a = u[1], d = u[2], c = logit_to_prob(u[3])),
    GRM = irt_item(type, a = u[1], cuts = -u[-1] / u[1]),
    GPCM = irt_item(type, a = u[1], cuts = -diff(c(0, u[-1])) / u[1]),
    nominal = {
      d <- c(0, tail(u, K - 1L))
      if (irt_direct_nominal_slopes(template)) {
        current <- irt_item(type, a = c(0, head(u, K - 1L)), d = d)
        if (K > 2L) current$nominal_coordinates <- "category_slopes"
        current
      } else {
        if (u[1] == 0) stop(
          "Relative category slopes require a nonzero common multiplier.")
        irt_item(type, a = u[1] * c(0, u[2:(K - 1L)], K - 1L), d = d)
      }
    })
}

For two categories, or for a starting last slope of zero, irt_item_pack() uses direct category slopes. In a multicategory item, irt_item_unpack() marks that choice so that a trial value moving the last slope away from zero still uses direct slopes. The predicate irt_direct_nominal_slopes() selects between the two representations, returning true for direct slopes.

The probabilities in irt_nominal_response() use the reconstructed slopes and intercepts. The choice of parameterization determines which derivatives occupy the third dimension of gradient.

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
irt_nominal_response <- function(item, z) {
  K <- item$K
  result <- irt_category_logits(z, item$a, item$d)
  gradient <- array(0, c(length(z), K, 2L * (K - 1L)))
  direct <- irt_direct_nominal_slopes(item)
  if (!direct) {
    # For a_k = s t_k, multiply z by t_k minus its conditional mean.
    s <- item$a[K] / (K - 1)
    t <- item$a / s
    gradient[, , 1L] <- outer(z, t) - drop(result$probability %*% t) * z
  }
  for (h in seq_len(K - 1L)) {
    indicator <- as.numeric(seq_len(K) == h + 1L)
    change <- matrix(indicator, length(z), K, byrow = TRUE) - result$probability[, h + 1L]
    if (direct) {
      # The derivative in category slope a_h is z times the same indicator residual.
      gradient[, , h] <- change * z
    } else if (h < K - 1L) {
      gradient[, , 1L + h] <- s * change * z
    }
    gradient[, , K - 1L + h] <- change
  }
  list(logp = result$logp, probability = result$probability, gradient = gradient,
    d_log_probability_d_trait = result$d_log_probability_d_trait)
}

In the direct nominal parameterization, gradient[, , h] contains $z r_{yh}$ for slope $a_h$ across abilities and responses. With $a_h=s\,t_h$, the chain rule instead gives

\[\partial_s\log P_y =\sum_h t_h z r_{yh} =z\left(t_y-\sum_hP_h(z)t_h\right),\qquad \partial_{t_h}\log P_y=s z r_{yh}\quad(1\le h<K-1).\]

In either nominal parameterization, differentiating with respect to ability gives $a_y-\sum_h P_h(z)a_h$.

Category probabilities of the three items

With one constructed item for each of the three models, evaluating them at seven abilities compares the probabilities they assign to each response category. The list element for ability zero contains one row per model and one column per category. The graded and partial credit items use $a=1$ and the same three values for their thresholds or steps. For the nominal item, take slopes $(0,0.5,1,1.5)$ and intercepts $(0,-0.5,-1,-2)$. Here $s=1.5/3=0.5$, so the relative slopes are $(0,1,2,3)$. In the probability calculation, normalize_logweights() (Section 1.4) converts the linear predictors into category probabilities.

1
2
3
4
5
6
7
8
9
10
trait_grid <- seq(-3, 3, by = 1)
category_grid <- lapply(trait_grid, function(z) {
  cumulative <- c(1, plogis(z - c(-1, 0, 1)), 0)
  rbind(GRM = -diff(cumulative),
    GPCM = normalize_logweights(c(0, cumsum(z - c(-1, 0, 1)))),
    nominal = normalize_logweights(c(0, c(.5, 1, 1.5) * z + c(-.5, -1, -2))))
})
at_zero <- category_grid[[match(0,trait_grid)]]
colnames(at_zero) <- paste0("category_",0:3)
print(cbind(at_zero,probability_sum=rowSums(at_zero)))
1
2
3
4
        category_0 category_1 category_2 category_3 probability_sum
GRM      0.2689414  0.2310586  0.2310586 0.26894142               1
GPCM     0.1344707  0.3655293  0.3655293 0.13447071               1
nominal  0.4739908  0.2874900  0.1743715 0.06414769               1

At zero, the graded model assigns 0.26894 to each end score. For partial credit, the successive adjacent logits are $1,0,-1$. Their cumulative sums, including the reference value, are $0,1,1,0$. The category probabilities are therefore proportional to $(1,e,e,1)$, giving each end probability $1/(2+2e)\approx0.13447$. The nominal linear predictors at zero equal their intercepts, giving probabilities 0.47399 and 0.06415 for categories zero and three. All three rows sum to one.

How does the probability of each category change away from zero? The function irt_prob() selects the item’s probability function. Given several abilities, its probability matrix has one category per column in response order.

1
2
3
4
5
6
irt_prob <- function(item, z) {
  stopifnot(is.numeric(z), length(z) > 0L, all(is.finite(z)))
  switch(item$model, Rasch = , `2PL` = , `3PL` = irt_dichotomous(item, z),
    GRM = irt_graded_response(item, z), GPCM = irt_partial_credit(item, z),
    nominal = irt_nominal_response(item, z), stop("Unknown item model"))
}

For the three items just compared, the table gives all four category probabilities at each integer ability from $-3$ to 3. The calculation runs from the book directory, loading the same item definitions for the table and drawing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (file in c("stability", "transforms", "irt"))
  source(paste0("code/lib/", file, ".R"), local = TRUE)
trait <- -3:3
items <- list(GRM = irt_item("GRM", cuts = c(-1, 0, 1)),
  GPCM = irt_item("GPCM", cuts = c(-1, 0, 1)),
  nominal = irt_item("nominal", a = c(0, .5, 1, 1.5), d = c(0, -.5, -1, -2)))
curves <- function(grid) lapply(items, function(item) irt_prob(item, grid)$probability)
p <- curves(trait)
tab <- do.call(rbind, lapply(names(p), function(name) {
  out <- p[[name]]
  colnames(out) <- paste0("category_", 0:3)
  data.frame(model = name, trait, out, total = rowSums(out))
}))
print(tab, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
   model trait  category_0  category_1  category_2  category_3 total
     GRM    -3 0.880797078 0.071777049 0.029439663 0.017986210     1
     GRM    -2 0.731058579 0.149738499 0.071777049 0.047425873     1
     GRM    -1 0.500000000 0.231058579 0.149738499 0.119202922     1
     GRM     0 0.268941421 0.231058579 0.231058579 0.268941421     1
     GRM     1 0.119202922 0.149738499 0.231058579 0.500000000     1
     GRM     2 0.047425873 0.071777049 0.149738499 0.731058579     1
     GRM     3 0.017986210 0.029439663 0.071777049 0.880797078     1
    GPCM    -3 0.875505990 0.118486851 0.005899113 0.000108046     1
    GPCM    -2 0.704153319 0.259043530 0.035057729 0.001745422     1
    GPCM    -1 0.413621976 0.413621976 0.152163022 0.020593026     1
    GPCM     0 0.134470711 0.365529289 0.365529289 0.134470711     1
    GPCM     1 0.020593026 0.152163022 0.413621976 0.413621976     1
    GPCM     2 0.001745422 0.035057729 0.259043530 0.704153319     1
    GPCM     3 0.000108046 0.005899113 0.118486851 0.875505990     1
 nominal    -3 0.865685170 0.117157748 0.015855577 0.001301505     1
 nominal    -2 0.781460521 0.174367411 0.038906628 0.005265440     1
 nominal    -1 0.652140410 0.239909049 0.088257607 0.019692934     1
 nominal     0 0.473990846 0.287489981 0.174371488 0.064147685     1
 nominal     1 0.277274781 0.277274781 0.277274781 0.168175656     1
 nominal     2 0.123681479 0.203916286 0.336201118 0.336201118     1
 nominal     3 0.042937193 0.116715391 0.317265326 0.523082091     1

Reflection about zero exchanges scores $k$ and $3-k$ for these graded and partial credit items. For the graded item this follows from the symmetric thresholds and the identity $\operatorname{logit}^{-1}(-x)=1-\operatorname{logit}^{-1}(x)$. For partial credit, reflection reverses the adjacent log ratios and changes their signs. Thus $P_k(z)=P_{3-k}(-z)$ in both cases. At zero, scores one and two each have probability 0.23106 under the graded model and 0.36553 under partial credit. Figure 10.2 draws the same items at 151 equally spaced abilities.

1
2
grid <- seq(-3, 3, length.out = 151L)
smooth <- curves(grid)

Four category curves in each panel. The graded and partial credit panels exchange opposite scores across zero. In the nominal panel three curves meet at ability one and the two highest curves meet at two.

Figure 10.2. Category probabilities by ability for the graded, generalized partial credit and nominal items. Within each panel, the solid, dashed, dotted and dot-dashed lines represent categories zero through three, respectively; these are ordered scores in the first two panels and response labels in the nominal panel.

For the nominal item, the four linear predictors are $0$, $0.5z-0.5$, $z-1$ and $1.5z-2$. The largest linear predictor gives the most probable category because all four probabilities share the same denominator. Category zero leads below 1. At 1 the first three linear predictors equal zero, so each of these three categories has probability 0.27727. Category two leads between 1 and 2, ties category three at 2, and yields to category three above 2. Category one is never uniquely most probable. Other nominal items can have their slopes in any order.

Checking the derivatives

Perturbing each packed parameter and then the trait by $10^{-6}$ in each direction checks the analytic log-probability derivatives for the three models numerically. The function item_check() uses the same central-difference comparisons as dichotomous_check(), with irt_item_pack() and irt_item_unpack() supplying the coordinates and reconstruction for each model. This makes the comparison follow the actual intercept or nominal-slope parameterization. Another check follows from $\sum_y P_y\partial_\xi\log P_y=\partial_\xi\sum_y P_y=0$ for each item parameter.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
item_check <- function(item, z, h = 1e-6) {
  out <- irt_prob(item, z)
  u <- irt_item_pack(item)
  coordinate_error <- max(vapply(seq_along(u), function(k) {
    e <- replace(numeric(length(u)), k, h)
    numerical <- (irt_prob(irt_item_unpack(u + e, item), z)$logp -
      irt_prob(irt_item_unpack(u - e, item), z)$logp) / (2 * h)
    max(abs(numerical - out$gradient[, , k]))
  }, 0.0))
  trait_error <- max(abs((irt_prob(item, z + h)$logp - irt_prob(item, z - h)$logp) /
    (2 * h) - out$d_log_probability_d_trait))
  # Weight each log probability derivative by its category probability.
  max_abs_mean_log_probability_derivative <- max(abs(vapply(seq_along(u), function(k)
    rowSums(out$probability * out$gradient[, , k]), numeric(length(z)))))
  c(coordinate_error = coordinate_error, trait_error = trait_error,
    sum_error = max(abs(rowSums(out$probability) - 1)),
      max_abs_mean_log_probability_derivative = max_abs_mean_log_probability_derivative)
}
z_poly <- c(-8, -2, -.4, 0, .9, 3, 8)
poly_items <- list(GRM = irt_item("GRM", a = 1.2, cuts = c(-.8, -.1, 1)),
  GPCM = irt_item("GPCM", a = 1.2, cuts = c(-.8, .1, .9)),
  nominal = irt_item("nominal", a = c(0, .5, 1, 1.5), d = c(0, -.5, -1, -2)))
print(t(vapply(poly_items, item_check, numeric(4), z = z_poly)))
1
2
3
4
        coordinate_error  trait_error    sum_error max_abs_mean_log_probability_derivative
GRM         1.402926e-09 1.128989e-09 2.220446e-16                            5.551115e-17
GPCM        2.713893e-09 2.330351e-09 2.220446e-16                            5.124807e-15
nominal     1.169754e-09 3.709796e-10 2.220446e-16                            2.997602e-15

The fourth result, max_abs_mean_log_probability_derivative, takes the largest absolute departure from zero across abilities and parameter slices after summing over response categories. For the three specified items, with positive graded and partial credit discriminations, strictly ordered graded thresholds and a nonzero nominal slope multiplier, evaluated at seven abilities from $-8$ to 8, the largest absolute differences from central differences were below $2.72\times10^{-9}$ for the packed parameters and $2.34\times10^{-9}$ for ability. Each probability row summed to one within $2.23\times10^{-16}$, and the largest absolute probability-weighted mean derivative was below $5.13\times10^{-15}$. The nominal item here uses relative slopes. Reversing the first two graded thresholds tests the order restriction separately.

1
2
print(c(unordered_GRM_cuts_refused =
  inherits(tryCatch(irt_item("GRM", cuts = c(0, -1, 1)), error = identity), "error")))
1
2
unordered_GRM_cuts_refused 
                      TRUE 

The constructor rejected the reversed thresholds, as required for positive probabilities between successive boundaries.

Simulated polytomous responses

To generate one response given an ability, irt_generate() draws a uniform number and counts how many cumulative category sums it exceeds. For four scores there are three such boundaries inside the unit interval. Each interval has length equal to the corresponding category probability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
irt_generate <- function(items, z) {
  U <- matrix(runif(length(z) * length(items)), length(z))
  Y <- matrix(0L, length(z), length(items))
  for (j in seq_along(items)) {
    p <- irt_prob(items[[j]], z)$probability
    # For multiple categories, count the cumulative boundaries below the draw.
    if (items[[j]]$K == 2L) Y[, j] <- as.integer(U[, j] < p[, 2]) else {
      cumulative <- t(apply(p, 1, cumsum))
      Y[, j] <- rowSums(U[, j] > cumulative[, -ncol(p), drop = FALSE])
    }
  }
  colnames(Y) <- paste0("item", seq_along(items))
  Y
}

The six graded items in ORD6 have discriminations from 0.8 to 1.3. Item $j$ adds $0.15(j-3.5)$ to each threshold in $(-1,0,1)$. The partial credit items use the graded discriminations and take the graded thresholds as adjacent-category steps, and all six nominal items use the four slopes and intercepts from the curve example. Seed 1004 gives 600 standard normal abilities and the graded responses. With these same abilities, seed 1005 starts a new sequence of draws for the partial credit responses followed by the nominal responses.

1
2
3
4
5
6
7
8
9
10
11
12
13
truthG <- lapply(1:6, function(j) irt_item("GRM", a = seq(.8, 1.3, length.out = 6)[j],
  cuts = c(-1, 0, 1) + .15 * (j - 3.5)))
truthP <- lapply(truthG, function(item) irt_item("GPCM", a = item$a, cuts = item$cuts))
truthN <- replicate(6, irt_item("nominal", a = c(0, .5, 1, 1.5), d = c(0, -.5, -1, -2)),
  simplify = FALSE)
set.seed(1004)
zG <- rnorm(600)
YG <- irt_generate(truthG, zG)
set.seed(1005)
YP <- irt_generate(truthP, zG)
YN <- irt_generate(truthN, zG)
print(rbind(GRM = tabulate(YG[, 1] + 1, 4), GPCM = tabulate(YP[, 1] + 1, 4),
  nominal = tabulate(YN[, 1] + 1, 4)))
1
2
3
4
        [,1] [,2] [,3] [,4]
GRM      167   88  102  243
GPCM      97  152  188  163
nominal  296  156   93   55

For the first item, scores zero through three occurred 167, 88, 102 and 243 times under the graded model. The partial credit counts were 97, 152, 188 and 163, and the nominal counts were 296, 156, 93 and 55. Each row counts 600 responses. An examinee has the same ability in all three draws but receives a fresh response under each item model.

The mirt package fits graded response, generalized partial credit and nominal response models.

10.3 Marginal likelihood and Bock-Aitkin expected counts

An examinee answers the first item correctly and leaves the second unanswered. The first answer gives information about ability, even though the examinee has no observed ability score. How much of that one correct response should count at each ability when estimating the first item’s parameters? Let $h$ index a distinct response pattern, $O_h$ its set of answered items, and $y_{hj}$ its score on item $j$. Write $P_{jk}(z;\theta_j)$ for the probability of score $k$ at ability $z$ under item parameters $\theta_j$, and let $\theta$ collect the parameters of all items. Conditional independence makes the probability of the observed answers a product at a common $z$. Averaging that product over the fixed standard normal ability distribution, with density $\phi$, gives the marginal probability of the observed answers. For nodes $z_q$ and quadrature weights $w_q$ summing to one, the quadrature approximation is

\[\begin{aligned} L_h(z;\theta)&=\prod_{j\in O_h}P_{j,y_{hj}}(z;\theta_j),\\ m_h(\theta)&=\int_{-\infty}^{\infty}L_h(z;\theta)\phi(z)\,dz \;\approx\;\widetilde m_h(\theta)=\sum_q w_q L_h(z_q;\theta). \end{aligned}\]

Why can the unanswered second item be omitted? Suppose the probability of the observed missingness pattern depends only on the recorded answers. This is the missing-at-random assumption here. When the missingness process and the response model also have distinct parameters, the missingness process is ignorable for item estimation. Summing over the possible answers to the omitted item gives $\sum_k P_{jk}(z;\theta_j)=1$ at every ability. The assumption rules out additional dependence on the unobserved answers or ability after conditioning on the recorded answers. Coding an omission as NA does not establish that assumption.

Independent examinees with identical observed scores and omissions have the same contribution. If $f_h$ examinees have pattern $h$, the approximate log likelihood is $\sum_h f_h\log\widetilde m_h(\theta)$. The function irt_data() groups repeated rows of the response matrix Y and adds their frequencies. For each item $j$ it constructs an indicator matrix $D^{(j)}$. Each of its rows corresponds to a pattern in order of first appearance. In row $h$, column $k+1$ is one if the observed score is $k$. An unanswered item has zeros across that row. frequency counts replicated examinees and must contain positive integers; these are frequency counts, not survey sampling weights.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
irt_data <- function(Y, items, frequency = rep(1, nrow(Y)), compress = TRUE) {
  Y <- as.matrix(Y)
  stopifnot(ncol(Y) == length(items), nrow(Y) > 0,
    length(frequency) == nrow(Y), all(is.finite(frequency)),
    all(frequency > 0), all(frequency == floor(frequency)))
  for (j in seq_along(items)) stopifnot(all(is.na(Y[, j]) |
    Y[, j] %in% (0:(items[[j]]$K - 1L))))
  key <- apply(Y, 1, paste, collapse = ":")
  index <- if (compress) match(key, unique(key)) else seq_len(nrow(Y))
  first <- !duplicated(index)
  patterns <- Y[first, , drop = FALSE]
  # Sum frequencies within each distinct pattern while retaining its first appearance.
  counts <- drop(rowsum(frequency, index, reorder = FALSE))
  # Columns index the response categories of this item.
  indicators <- lapply(seq_along(items), function(j) {
    out <- outer(patterns[, j], 0:(items[[j]]$K - 1L), "==")
    out[is.na(out)] <- FALSE
    1 * out
  })
  list(Y = Y, frequency = frequency, patterns = patterns, counts = counts,
    index = index, indicators = indicators, N = sum(frequency), J = ncol(Y))
}

Posterior node probabilities and expected counts

At the current item parameters, the joint probability of pattern $h$ and node $q$ under the quadrature rule is $w_q L_h(z_q;\theta)$. Dividing by the sum over nodes gives the posterior probability $\tau_{hq}$ of that node given the observed answers. The same denominator supplies the pattern’s likelihood contribution. The expectation step, or E step, of the Bock-Aitkin algorithm computes both from the log joint probabilities $b_{hq}$,

\[\begin{aligned} b_{hq}&=\log w_q+\sum_{j\in O_h}\log P_{j,y_{hj}}(z_q;\theta_j),\\ \tau_{hq}&=\frac{\exp(b_{hq}-b_h^*)}{\sum_r\exp(b_{hr}-b_h^*)},\qquad b_h^*=\max_r b_{hr}. \end{aligned}\]

The three arguments of irt_estep() have distinct roles. data records the observed patterns and their frequencies, items[[j]] contains the current parameter list $\theta_j$ of item $j$, and rule$nodes[q] and rule$weights[q] represent $z_q$ and $w_q$. The items list supplies one item object per response column; rule supplies the numerical approximation to the fixed ability distribution. Neither the observed patterns nor the posterior node probabilities are item parameters. Here “prior” refers to the ability distribution before observing a person’s answers, not a prior density on item parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
irt_estep <- function(data, items, rule) {
  stopifnot(length(rule$nodes) == length(rule$weights), all(is.finite(rule$weights)),
    all(rule$weights >= 0), any(rule$weights > 0),
    abs(sum(rule$weights) - 1) < 1e-9)
  evaluations <- lapply(items, irt_prob, z = rule$nodes)
  conditional <- matrix(0, nrow(data$patterns), length(rule$nodes))
  # Match each observed response to its log probability at every node.
  for (j in seq_len(data$J)) conditional <- conditional +
    tcrossprod(data$indicators[[j]], evaluations[[j]]$logp)
  # Normalize over nodes for each response pattern.
  log_joint <- sweep(conditional, 2, log(rule$weights), "+")
  maximum <- log_joint[cbind(seq_len(nrow(log_joint)),
    max.col(log_joint, ties.method = "first"))]
  mass <- exp(log_joint - maximum)
  posterior <- mass / rowSums(mass)
  contribution <- maximum + log(rowSums(mass))
  # Count all examinees represented by each posterior row.
  weighted <- posterior * data$counts
  mass_ratios <- exp(conditional - contribution)
  expected <- lapply(data$indicators, function(D) crossprod(weighted, D))
  # Restore one row for each person represented by the supplied frequencies.
  person_index <- rep(data$index, data$frequency)
  list(value = -sum(data$counts * contribution),
    loglik_contributions = contribution[person_index],
    pattern_log_marginal_probabilities = contribution, posterior = posterior,
    person_posterior = posterior[person_index, , drop = FALSE], expected = expected,
    node_counts = colSums(weighted),
    mass_ratios = mass_ratios, mass_gradient = colSums(mass_ratios * data$counts),
      evaluations = evaluations,
    nodes = rule$nodes, weights = rule$weights)
}

In irt_estep(), tcrossprod() uses the indicator for the observed category to select its log probability at every node. Adding across items gives one row of conditional per pattern. Adding the log prior mass to each node’s column gives log_joint. Subtracting the row maximum before exponentiating leaves all posterior ratios unchanged. Adding it back to the log sum of the shifted exponentials gives contribution, the approximate log marginal probability. The function returns the negative frequency-weighted sum of these contributions in value.

For the pattern with the single correct answer, its row of posterior allocates one person across nodes. Its row of weighted allocates all $f_h$ people with that pattern. For item $j$, the product crossprod(weighted, D) places $\sum_h f_h\tau_{hq}D^{(j)}_{h,k+1}$ in node row $q$ and response column $k+1$.

The returned mass_ratios are $L_h(z_q)/\widetilde m_h$, so multiplication by $w_q$ is needed to obtain posterior probabilities. The vector mass_gradient contains $\partial\ell/\partial w_q=\sum_h f_hL_h(z_q)/\widetilde m_h$ before enforcing the unit-sum constraint. The returned loglik_contributions repeat pattern contributions according to the input frequencies and row mapping.

The expected node totals and item response counts answer different questions. Summing down a column of weighted gives $N_q=\sum_h f_h\tau_{hq}$, the expected number of examinees at node $q$ given all their observed responses. To count correct answers to dichotomous item $j$ at that node, sum only over patterns that scored one there. Writing $n_{jqk}$ for the expected count of score $k$, this gives $n_{jq1}=\sum_h f_h\tau_{hq}D^{(j)}_{h,2}$. R stores this count in row $q$ of the second column of the item’s matrix in expected. An individual contributes a fraction at each node, yet the fractions for that person sum to one. Consequently, summing $n_{jq1}$ over nodes recovers the observed number of correct answers to item $j$.

For the examinee with only the first answer observed, that answer determines the posterior row. In the second item’s indicator matrix the same examinee selects no response column. For that item, $\sum_k n_{jqk}$ counts only people who answered it, weighted by their posterior probabilities at node $q$. It can be smaller than $N_q$. A person with every item missing contributes zero log marginal probability and no item response counts; that person’s posterior node probabilities equal the prior weights.

The maximization step uses the counts from the current parameters $\theta^{(t)}$ to evaluate candidate item parameters $\theta$. If each examinee’s node were observed, a response in category $k$ on item $j$ from a person at node $q$ would contribute $\log P_{jk}(z_q;\theta_j)$ to the complete-data log likelihood. Taking its conditional expectation replaces the number of such answers by $n_{jqk}^{(t)}$. With the prior node masses fixed, their log probabilities contribute a constant to the Q function for the item parameters,

\[Q(\theta\mid\theta^{(t)})= \sum_j\sum_q\sum_{k=0}^{K_j-1}n_{jqk}^{(t)}\log P_{jk}(z_q;\theta_j) +\text{constant},\]

where $K_j$ is the number of categories of item $j$. During maximization the counts are fixed. If each item has its own free parameters, changing $\theta_j$ affects only item $j$’s summand. This is how one posterior calculation for each whole pattern supplies a separate estimation problem for each item.

In an expectation-maximization fit, each expected count weights the log probability of one category at one ability. The maximization step, or M step, updates the item parameters with those counts fixed. For each polytomous model, the item update uses the BFGS optimizer to minimize the negative of this weighted sum with respect to all free item parameters. Its gradient weights each log probability derivative by the same expected count. A 3PL item also takes this route. Writing $\eta=az+d$, the 3PL log odds are $\log(c+e^\eta)-\log(1-c)$. Even at a fixed positive $c$, these log odds are nonlinear in $\eta$. At $c=0$ they reduce to $\eta$. Weighted logistic regression supplies the item criterion for the Rasch and 2PL models. Section 10.4 implements these item updates.

A check by direct enumeration

Consider three examinees answering two 2PL items, with the partially observed pattern in the second row of mini. The first and third examinees answer both items. For this check, normal_rule(3L) from code/lib/integration.R gives the three standard normal Gauss-Hermite nodes $-\sqrt{3},0,\sqrt{3}$ with masses $1/6,2/3,1/6$. In explicit, dbinom() gives the probability of the actual zero or one under each item’s success probability. For each person, the code multiplies those probabilities across answered items, multiplies by each node’s prior mass, and divides by the total over nodes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mini <- rbind(c(0, 0), c(1, NA), c(1, 1))
mini_items <- list(irt_item("2PL", a = .8, d = -.4), irt_item("2PL", a = 1.2, d = .3))
mini_rule <- normal_rule(3L)
mini_e <- irt_estep(irt_data(mini, mini_items), mini_items, mini_rule)
explicit <- t(vapply(seq_len(nrow(mini)), function(i) {
  joint <- vapply(seq_along(mini_rule$nodes), function(q) {
    p <- vapply(mini_items, function(item) plogis(item$a * mini_rule$nodes[q] + item$d),
      0.0)
    # A blank response supplies no Bernoulli factor.
    observed <- !is.na(mini[i, ])
    mini_rule$weights[q] * prod(dbinom(mini[i, observed], 1, p[observed]))
  }, 0.0)
  joint / sum(joint)
}, numeric(3)))
print(round(mini_e$person_posterior, 6))
1
2
3
4
         [,1]     [,2]     [,3]
[1,] 0.412805 0.574205 0.012990
[2,] 0.057975 0.648040 0.293985
[3,] 0.012894 0.572988 0.414118

The examinee with two incorrect answers has posterior mass 0.412805 at the lowest node. The examinee with two correct answers has mass 0.414118 at the highest. For the middle examinee, the center node contributes $(2/3)\operatorname{logit}^{-1}(-0.4)$ before normalization. Dividing by the sum over the three nodes gives 0.648040. The entire second row, $(0.057975,0.648040,0.293985)$, enters the first item’s correct-response column. It contributes zero to both columns for item two. At the center node, all three posterior rows count toward the expected number answering item one. Only the first and third rows count toward item two, giving $0.574205+0.572988=1.147193$ expected respondents there.

1
2
3
print(c(enumeration_error = max(abs(explicit - mini_e$person_posterior)),
  respondents_item1 = sum(mini_e$expected[[1]]),
    respondents_item2 = sum(mini_e$expected[[2]])))
1
2
enumeration_error respondents_item1 respondents_item2 
     1.110223e-16      3.000000e+00      2.000000e+00 

The largest absolute difference between direct enumeration and irt_estep() was approximately $1.11\times10^{-16}$. Summing all cells of each item’s expected-count matrix gives three respondents for item one and two for item two.

Expected counts for the IRT8 responses

For the eight-item IRT8 sample, irt_rule(61L) uses 61 equally spaced abilities from $-6$ to 6 and weights proportional to the standard normal density. The prior masses sum to one on this grid. This equally spaced rule is distinct from the Gauss-Hermite rule used in the three-node illustration. Its weights define a discrete approximation; a continuous normal variable has probability zero at any single node.

1
2
3
4
5
irt_rule <- function(n = 61L, limits = c(-6, 6)) {
  nodes <- seq(limits[1], limits[2], length.out = n)
  weights <- dnorm(nodes)
  list(nodes = nodes, weights = weights / sum(weights), measure = "standard_normal")
}

For the complete dichotomous response matrices, irt_start() uses category proportions to set the starting intercepts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
irt_start <- function(Y, model, K = rep(2L, ncol(Y)), prior = NULL) {
  Y <- as.matrix(Y)
  model <- rep_len(model, ncol(Y))
  div <- sqrt(.75) / 1.702
  lapply(seq_len(ncol(Y)), function(j) {
    p <- tabulate(Y[, j] + 1L, K[j]) / nrow(Y)
    a <- .5 * 1.702
    switch(model[j],
      Rasch = irt_item("Rasch", d = -qnorm(p[1]) / div),
      `2PL` = irt_item("2PL", a = a, d = -qnorm(p[1]) / div),
      `3PL` = irt_item("3PL", a = a, d = -qnorm(p[1]) / div,
        c = if (is.null(prior)) .15 else plogis(prior[1])),
      GRM = irt_item("GRM", a = a, cuts = -qnorm(1 - cumsum(p[-K[j]])) / div / a),
      GPCM = {
        d <- (qnorm(p) - qnorm(p[1]))[-1] / div
        irt_item("GPCM", a = a, cuts = -diff(c(0, d)) / a)
      },
      nominal = irt_item("nominal", a = a * c(0, rep(.5, K[j] - 2L), K[j] - 1),
        d = rep(0, K[j])))
  })
}

In its 2PL calculation, p[1] is the proportion incorrect, so a small p[1] gives a positive intercept through -qnorm(p[1]) / div. Each discrimination starts at $0.5(1.702)=0.851$. The factor 1.702 belongs to this starting-value calculation and does not multiply the model’s linear predictor. Proportions of zero or one can also produce infinite normal quantiles.

The three sets of starting items correspond to the response matrices Y2, YR and Y3. The E step below uses Y2 and its eight starting 2PL items. Column two of e0$expected[[1]] counts correct answers to item one across the 61 nodes.

1
2
3
4
5
6
7
8
9
10
11
start2 <- irt_start(Y2, "2PL")
startR <- irt_start(YR, "Rasch")
start3 <- irt_start(Y3, "3PL")
data2 <- irt_data(Y2, start2)
dataR <- irt_data(YR, startR)
data3 <- irt_data(Y3, start3)
rule61 <- irt_rule(61L)
e0 <- irt_estep(data2, start2, rule61)
print(c(people = data2$N, distinct_patterns = nrow(data2$patterns),
  respondents_item1 = sum(e0$expected[[1]]),
    successes_item1 = sum(e0$expected[[1]][, 2])))
1
2
           people distinct_patterns respondents_item1   successes_item1 
              800               161               800               574 

The 161 distinct patterns represent 800 examinees. Every examinee answered item one, and 574 answered it correctly. Changing from people to patterns saves repeated probability calculations. Each pattern’s posterior probabilities sum to one. Multiplying them by the pattern frequency therefore recovers its full number of respondents, and its full number of correct responses when the recorded answer is one. The mirt package provides marginal item estimation by EM.

10.4 Itemwise M steps and the use of weighted logistic regression

The first item in IRT8 received 574 correct answers from 800 examinees. To estimate its discrimination, the M step needs to know where on the ability scale those correct and incorrect responses fall. The E step supplies that information in e0$expected[[1]]. At node $z_q$, let $s_q$ denote the expected number of correct answers in column two and $n_q$ the expected number of respondents obtained by adding both columns. During this item update, both numbers remain fixed. For a candidate 2PL discrimination $a>0$ and intercept $d$, set $\eta_q=d+az_q$ and $p_q=\operatorname{logit}^{-1}(\eta_q)$. The item’s contribution to the expected complete-data log likelihood is

\[Q(d,a)=\sum_q\{s_q\log p_q+(n_q-s_q)\log(1-p_q)\}.\]

At each node, $s_q$ weights the log probability of a correct answer and $n_q-s_q$ weights that of an incorrect answer. The regression design $X$ therefore has one row $x_q^\top=(1,z_q)$ per node. Its coefficients in column order are $\beta=(d,a)^\top$. The two columns of expected counts play the roles of grouped successes and failures, even when a cell contains a fraction of a person.

The function make_binomial_q() constructs the negative expected item log likelihood $f_Q=-Q$ for minimization. Substituting the logistic probabilities yields $f_Q(\beta)=\sum_q\lbrace n_q\log(1+e^{\eta_q})-s_q\eta_q\rbrace $. Combinatorial constants play no part in this expected sum of individual log probabilities. Its derivative in $\eta_q$ is $n_qp_q-s_q$, the negative of the corresponding derivative of $Q$. Differentiating again gives $w_q=n_qp_q(1-p_q)$. Here $w_q$ is a working regression weight calculated from the expected respondent count. These regression weights differ from the quadrature weights denoted by the same letter in Section 10.3. With $W$ diagonal in those weights, the derivatives in coefficient order are

\[\nabla f_Q=\sum_q x_q(n_qp_q-s_q),\qquad \nabla^2 f_Q=X^\top W X.\]

The binomial forms of make_glm() and make_nll_logit() require integer observed counts. The E step supplies real values satisfying $0\le s_q\le n_q$, for which logit_score() and logit_info() still give the required derivatives. The new function negates the vector of first derivatives of $Q$ and uses its negative Hessian directly. For $w_q>0$, the working response is $v_q=\eta_q+(s_q-n_qp_q)/w_q$. Multiplying the working adjustment by $w_q$ recovers the count residual. The normal equations for the weighted fit therefore reduce to

\[X^\top W X(\beta_{\rm new}-\beta)=X^\top W(v-X\beta)=-\nabla f_Q(\beta).\]

If the weighted design has independent columns, this equation determines the same coefficient update as a full Newton step. Recomputing the working response and weights after each fit gives iteratively reweighted least squares (IRLS).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
make_binomial_q <- function(X, success, exposure) {
  stopifnot(is.matrix(X), nrow(X) == length(success), length(success) == length(exposure),
    all(is.finite(c(X, success, exposure))), all(success >= 0), all(exposure >= success))
  # Use the expected number of respondents at each node to form its working weight.
  working <- function(beta) {
    eta <- drop(X %*% beta)
    p <- plogis(eta)
    w <- exposure * p * plogis(-eta)
    active <- w > 0
    z <- eta
    z[active] <- eta[active] + (success[active] - exposure[active] * p[active]) /
      w[active]
    list(z = z, w = w)
  }
  list(X = X, y = success, trials = exposure,
    fn = function(beta) { eta <- drop(X %*% beta)
      sum(success * log1pexp(-eta) + (exposure - success) * log1pexp(eta)) },
    gr = function(beta) -logit_score(beta, X, success, exposure),
    he = function(beta) logit_info(beta, X, exposure), working = working)
}

In make_binomial_q(), success contains $s_q$ and exposure contains $n_q$. Here exposure means an expected number of respondents, not time at risk or an observed integer number of trials. A row with zero expected respondent count adds nothing to the equation. A weight rounded to zero at an extreme fitted probability needs separate care: its count residual need not be zero. The list returned by working() supplies weighted_qr() with the working response in z and the weights in w.

For item one, use the same expected counts in two calculations. Start the regression at $(d,a)=(0,0.8)$ and compare the coefficients from a single weighted QR fit with those from solving the Newton equation at that start.

1
2
3
4
5
6
7
q1 <- make_binomial_q(cbind(1, rule61$nodes), e0$expected[[1]][, 2],
  rowSums(e0$expected[[1]]))
working <- q1$working(c(0, .8))
qr_update <- weighted_qr(q1$X, working$z, working$w)$coefficients
newton_update <- c(0, .8) - solve(q1$he(c(0, .8)), q1$gr(c(0, .8)))
print(c(QR_Newton_difference = max(abs(qr_update - newton_update)),
  one_step_Q_gain = q1$fn(c(0, .8)) - q1$fn(qr_update)))
1
2
QR_Newton_difference      one_step_Q_gain 
        4.440892e-16         8.786018e+01 

The largest coefficient difference was $4.44\times10^{-16}$. This one update increased $Q$ by 87.86018.

Rasch, 3PL and polytomous updates

The same calculation extends to the other item models. For a Rasch item, the discrimination is fixed at one. Each node therefore contributes a known offset $z_q$ to the linear predictor $d+z_q$. A single intercept must account for the total correct count after these offsets have been included. With $p_q=\operatorname{logit}^{-1}(d+z_q)$, Newton’s method solves $\sum_q(n_qp_q-s_q)=0$. The derivative of this equation in $d$ is $\sum_q n_qp_q(1-p_q)$, giving the full Newton proposal

\[d_{\mathrm{new}}=d+\frac{\sum_q(s_q-n_qp_q)}{\sum_q n_qp_q(1-p_q)}.\]

A positive total residual raises the intercept and increases the predicted number correct.

For a 3PL item, let $L_q=\operatorname{logit}^{-1}(\eta_q)$ and $p_q=c+(1-c)L_q$. Differentiating its two weighted log probabilities with respect to the linear predictor gives

\[\frac{\partial Q_q}{\partial\eta_q} =(s_q-n_qp_q)\frac{p'_q}{p_q(1-p_q)},\qquad p'_q=(1-c)L_q(1-L_q).\]

For $c=0$, the multiplier of the count residual equals one. At a positive lower asymptote, it equals $L_q/p_q$, so applying the ordinary logistic score to the same counts would change the estimating equation. When $L_q$ is small relative to the lower asymptote, that node’s residual contributes little to the derivative in $\eta_q$. The 3PL update uses $(a,d,\gamma)$, with $\gamma=\log\lbrace c/(1-c)\rbrace $ for $0<c<1$. The item function supplies the log probabilities and their derivatives in these coordinates. An optional normal prior with mean $\mu$ and standard deviation $\sigma$ on $\gamma$ contributes $-(\gamma-\mu)/\sigma^2$ to the last component of the gradient of the log prior density. With no prior, irt_item_prior() returns zero for the log density and for every gradient component.

1
2
3
4
5
6
7
8
9
10
irt_item_prior <- function(item, prior = NULL) {
  # Normal prior on the logit of the lower asymptote: prior = c(mean, sd).
  p <- length(irt_item_pack(item))
  if (is.null(prior)) return(list(log_density = 0, gradient = rep(0, p)))
  stopifnot(item$model == "3PL", length(prior) == 2L, prior[2] > 0)
  u <- prob_to_logit(item$c)
  g <- rep(0, p)
  g[p] <- -(u - prior[1]) / prior[2]^2
  list(log_density = dnorm(u, prior[1], prior[2], log = TRUE), gradient = g)
}

For a graded, generalized partial credit or nominal item, let $n_{qk}$ be the expected count in category $k$ at node $q$. Its contribution is $Q=\sum_{qk}n_{qk}\log P_k(z_q)$. A graded response uses the difference of its bounding cumulative probabilities. Partial credit and nominal responses use probabilities normalized across all categories. Each model therefore weights its own log probability derivatives by $n_{qk}$. The function below selects the corresponding item objective and updates its free parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
irt_mstep_item <- function(counts, nodes, item, prior = NULL, control = list()) {
  start <- irt_item_pack(item)
  if (item$model %in% c("2PL", "Rasch")) {
    # With Rasch items the trait has coefficient one and enters as an offset.
    X <- if (item$model == "Rasch") matrix(1, length(nodes), 1) else cbind(1, nodes)
    q <- make_binomial_q(X, counts[, 2], rowSums(counts))
    if (item$model == "Rasch") {
      eta_fn <- function(d) d + nodes
      fn <- function(d) sum(counts[, 2] * log1pexp(-eta_fn(d)) +
        counts[, 1] * log1pexp(eta_fn(d)))
      gr <- function(d) sum(rowSums(counts) * plogis(eta_fn(d)) - counts[, 2])
      he <- function(d) matrix(sum(rowSums(counts) * plogis(eta_fn(d)) *
        plogis(-eta_fn(d))))
    } else {
      # The binomial negative log likelihood takes (d, a). The 2PL requires a > 0.
      fn <- function(u) if (is.finite(u[1]) && u[1] > 0) q$fn(u[2:1]) else Inf
      gr <- function(u) q$gr(u[2:1])[2:1]
      he <- function(u) q$he(u[2:1])[2:1, 2:1]
    }
    fit <- newton(fn, gr, he, start, modifyList(list(grad_tol = 1e-7, maxit = 50L), control))
  } else {
    evaluate <- function(u) {
      current <- irt_item_unpack(u, item)
      response <- irt_prob(current, nodes)
      penalty <- irt_item_prior(current, prior)
      # Sum the category log probabilities and their derivatives with the same counts.
      list(value = -sum(counts * response$logp) - penalty$log_density,
        gradient = -apply(response$gradient * as.vector(counts), 3, sum) -
          penalty$gradient)
    }
    fn <- function(u) tryCatch(evaluate(u)$value, error = function(e) Inf)
    gr <- function(u) tryCatch(evaluate(u)$gradient,
      error = function(e) rep(NA_real_, length(u)))
    fit <- bfgs(fn, gr, start, control)
  }
  # Measure the gain in the objective function used by this item update.
  gain <- fn(start) - fit$value
  accepted <- is.finite(gain) && gain >= -1e-10
  maximized <- accepted && fit$converged
  if (item$model == "2PL") {
    # At zero discrimination the fitted probability is the pooled success proportion.
    # Check the sign of the profiled derivative at that boundary.
    exposure <- rowSums(counts)
    success <- counts[, 2]
    if (!any(success > 0) || !any(counts[, 1] > 0)) {
      maximized <- FALSE
    } else {
      derivative_at_zero_discrimination <- sum(nodes * (success - exposure *
        sum(success) / sum(exposure)))
      # If all successes are above all failures, with some strict ordering, the
      # log likelihood can also approach its supremum along an unbounded slope.
      lowest_success <- min(nodes[success > 0])
      highest_failure <- max(nodes[counts[, 1] > 0])
      distinct_nodes <- diff(range(nodes[exposure > 0])) > 0
      if (distinct_nodes && (derivative_at_zero_discrimination <= 0 ||
        lowest_success >= highest_failure))
        maximized <- FALSE
    }
  }
  list(item = if (accepted) irt_item_unpack(fit$par, item) else item,
    gain = gain, accepted = accepted, maximized = maximized,
    optimizer = fit, evaluations = fit$evaluations)
}

The item parameter vector stores the discrimination first. For u containing $(a,d)$, q$fn(u[2:1]) evaluates the regression at $(d,a)$. The item update reverses the gradient components and both dimensions of the Hessian to express the Newton step in $(a,d)$.

In the Rasch branch, the design contains a single intercept column. The function eta_fn() adds nodes to $d$ each time the objective function or one of its derivatives is evaluated.

In irt_mstep_item(), apply() sums over node and response within each parameter slice. BFGS minimizes $-Q$ minus any log prior density with the analytic gradient of that objective function. The entries in each slice of response$gradient follow the same node and category order as the counts. This numerical maximization updates all free parameters of the item together. For graded response, generalized partial credit, nominal and 3PL items, the default relative tolerance of BFGS on the objective function is $\sqrt{\epsilon_{\rm machine}}$, with a limit of 100 iterations. For Rasch and 2PL items, the Newton iteration limit is 50. It can stop successfully when the largest absolute component of the scaled gradient reaches $10^{-7}$ or less, or when the relative step reaches $10^{-6}$ or less. A trial 2PL discrimination at or below zero gives an infinite value of the objective function, allowing the line search to shorten the step.

How should the returned item be read? The gain is the value of the objective function at the start minus its value at the proposed update. Without a prior, this is the increase in $Q$. With a prior, it also includes the change in log prior density. A finite gain of at least $-10^{-10}$ sets accepted to true and returns the updated parameters. Otherwise the function returns its input item. For unpenalized EM on a fixed quadrature rule, an exact nondecrease in $Q$ implies a nondecrease in the corresponding marginal log likelihood. The acceptance tolerance allows a small numerical loss. The optimizer field contains the inner fit, including its stopping reason. The maximized flag requires acceptance and optimizer convergence, with further checks for a positive finite 2PL maximum. These checks exclude the boundary and separation cases below. They do not certify exact maximization.

To examine the lower boundary when both response categories occur, set $a=0$ and fit the intercept. The fitted probability is the pooled proportion $\bar p=\sum_q s_q/\sum_q n_q$. The derivative of the profiled $Q$ at zero is

\[\left.\frac{d}{da}\max_d Q(d,a)\right|_{a=0} =\sum_q z_q(s_q-n_q\bar p).\]

Profiling contributes no additional term to this derivative because $\partial_d Q=0$ at $d=\operatorname{logit}(\bar p)$. With positive expected respondent counts at at least two distinct nodes, concavity puts the maximum for $a\ge0$ at zero if this derivative is nonpositive. That boundary is outside the fitted domain. At the opposite extreme, if every success is at or above every failure with some strict ordering, increasing the slope can approach the supremum without attaining it. Counts consisting entirely of successes or entirely of failures also have no finite intercept maximum. The code clears maximized in these cases even if it accepts the proposed step.

Updates for the eight IRT8 items

For the eight item updates, use the corresponding count matrix e0$expected[[j]] and start each fit at its own data-based parameters in start2[[j]].

1
2
3
4
5
6
7
updates <- lapply(seq_len(8), function(j) irt_mstep_item(e0$expected[[j]],
  rule61$nodes, start2[[j]]))
print(data.frame(item = 1:8, Q_gain = vapply(updates, `[[`, 0.0, "gain"),
  maximized = vapply(updates, `[[`, TRUE, "maximized"),
  reason = vapply(updates, function(u) u$optimizer$reason, ""),
  max_abs_scaled_gradient = vapply(updates, function(u) with(u$optimizer,
    max(abs(gradient) * pmax(1, abs(par))) / max(1, abs(value))), 0.0)))
1
2
3
4
5
6
7
8
9
  item     Q_gain maximized    reason max_abs_scaled_gradient
1    1 0.25260353      TRUE converged            3.854197e-13
2    2 0.19089299      TRUE converged            4.605641e-14
3    3 0.12613990      TRUE converged            6.739410e-08
4    4 1.56875302      TRUE converged            2.377118e-10
5    5 1.29227465      TRUE converged            1.019694e-10
6    6 0.07062983      TRUE converged            2.452463e-09
7    7 3.08212509      TRUE converged            3.138325e-09
8    8 0.20885209      TRUE converged            2.122480e-13

Item one now gains 0.25260353. Its starting discrimination is 0.851 and its intercept, computed from the 226 incorrect responses, is about 1.131. Thus 87.86018 measures one step from the chosen regression coefficients, while 0.25260353 measures the entire optimization from the data-based start on the same item objective function. The gains across items range from 0.07062983 for item six to 3.08212509 for item seven. All eight return converged and pass the 2PL maximization checks. The last column scales each gradient component by the larger of one and the absolute parameter, takes the largest magnitude, and divides by the larger of one and the absolute value of the objective function. It ranges from $4.61\times10^{-14}$ for item two to $6.74\times10^{-8}$ for item three.

Constructed counts for five item models

For a comparison across models, construct counts equal to 20 times a specified item’s category probabilities at each of seven equally spaced nodes from $-2$ to 2. If $t_k$ is a generating probability and $r_k$ a fitted probability at the same node, the loss in that row’s $Q$ is $20\sum_k t_k\log(t_k/r_k)\ge0$. The generating item attains equality at every node and therefore maximizes the sum. Add 0.15 to each packed parameter to obtain the starting item for both fits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
controlled_nodes <- seq(-2, 2, length.out = 7)
controlled_items <- list(irt_item("Rasch", d = -.5),
  irt_item("3PL", a = 1.1, d = -.5, c = .15),
  irt_item("GRM", a = 1.2, cuts = c(-1, 0, 1)),
    irt_item("GPCM", a = 1.2, cuts = c(-1, 0, 1)),
  irt_item("nominal", a = c(0, .5, 1, 1.5), d = c(0, -.5, -1, -2)))
controlled_updates <- lapply(controlled_items, function(target) {
  counts <- 20 * irt_prob(target, controlled_nodes)$probability
  u <- irt_item_pack(target) + .15
  initial <- irt_item_unpack(u, target)
  first <- irt_mstep_item(counts, controlled_nodes, initial, control = list(maxit = 1L))
  full <- irt_mstep_item(counts, controlled_nodes, initial)
  c(first_gain = first$gain, first_maximized = first$maximized,
    full_gain = full$gain, full_maximized = full$maximized)
})
names(controlled_updates) <- vapply(controlled_items, `[[`, "", "model")
print(do.call(rbind, controlled_updates))
1
2
3
4
5
6
        first_gain first_maximized full_gain full_maximized
Rasch    0.2740911               0 0.2740976              1
3PL      0.7012480               0 0.7112950              1
GRM      0.4400692               0 0.9478602              1
GPCM     0.4462964               0 0.6147017              1
nominal  1.8914480               0 2.4781516              1

One Newton iteration for the Rasch item gains 0.2740911, close to the full gain of 0.2740976. The 3PL gain rises from 0.7012480 after one iteration to 0.7112950 in the full fit. The corresponding pairs are 0.4400692 and 0.9478602 for graded response, 0.4462964 and 0.6147017 for partial credit, and 1.8914480 and 2.4781516 for nominal response. In this table, the maximization flags print as zero and one. All five single-iteration fits gained $Q$ and stopped short of their inner convergence criteria. All five full fits met their criteria. The printed gains compare initial and final values of the negative expected item log likelihood. Measuring the distance to the generating parameters would require the fitted coordinates. The Rasch row shows why a gain close to the full gain alone cannot establish convergence. The stats package fits weighted binomial regressions, and mirt provides EM estimation for these item models.

10.5 Direct marginal maximum likelihood, EM, and Ramsay acceleration

After updating the eight items using their expected counts, how well do the new discriminations and intercepts explain the 800 observed response vectors? An examinee supplies one vector of answers. Its probability averages the product of eight item probabilities over a single ability shared by those answers. For pattern $h$ with frequency $f_h$, write $L_h(z_q;u)$ for this product at node $z_q$ and item parameters $u$. With the 61 masses $w_q$ in rule61, the marginal log likelihood used for fitting is

\[\ell(u)=\sum_{h=1}^{161} f_h\log\widetilde m_h(u), \qquad \widetilde m_h(u)=\sum_{q=1}^{61}w_q L_h(z_q;u).\]

The input data2 contains the 161 patterns from the simulated responses Y2, supplied in data/source/ch10/IRT8-2.rds. The starting items are in start2. All three methods fix the ability mean at zero and variance at one. The nodes run from $-6$ to $6$, with masses proportional to the standard normal density. Each method needs the same correspondence between the parameters it changes and the items used to evaluate the likelihood. Packing places each discrimination immediately before its intercept, giving $u=(a_1,d_1,\ldots,a_8,d_8)^\top$. Unpacking takes the lengths and item models from the original templates, so the third coordinate again belongs to the discrimination of item two.

1
2
3
4
5
6
7
8
irt_pack <- function(items) unlist(lapply(items, irt_item_pack), use.names = FALSE)
irt_unpack <- function(u, templates) {
  lengths <- vapply(templates, function(item) length(irt_item_pack(item)), 0L)
  stopifnot(length(u) == sum(lengths))
  groups <- split(u, factor(rep(seq_along(templates), lengths),
    levels = seq_along(templates)))
  Map(irt_item_unpack, unname(groups), templates)
}

The E step supplies the derivative a direct optimizer needs. The chain rule gives $\nabla\log\widetilde m_h=(\nabla\widetilde m_h)/\widetilde m_h$. Inside the sum, write the derivative of $L_h$ as $L_h$ times the derivative of its logarithm. The resulting multiplier $w_q L_h(z_q;u)/\widetilde m_h(u)$ is the posterior probability $\tau_{hq}(u)$ of node $q$. Write $\theta_j=(a_j,d_j)^\top$ for item $j$’s block and $n_{jqk}(u)$ for its expected count in category $k$ at node $q$, evaluated at the current vector $u$. Only item $j$ contributes a derivative with respect to its own block. Grouping patterns by their response to that item gives

\[\begin{aligned} \nabla_{\theta_j}\ell(u) &=\sum_h f_h\sum_q\tau_{hq}(u)\, \nabla_{\theta_j}\log P_{j,y_{hj}}(z_q;\theta_j)\\ &=\sum_{q,k}n_{jqk}(u)\,\nabla_{\theta_j}\log P_{jk}(z_q;\theta_j). \end{aligned}\]

For item one, let $p_q$ denote its success probability. A correct answer contributes $\log p_q$, whose derivative with respect to discrimination is $z_q(1-p_q)$. An incorrect answer contributes $\log(1-p_q)$, giving derivative $-z_qp_q$. The expected numbers of correct and incorrect answers weight the two terms at each node. At the central node, $z_q=0$, even a large excess of correct responses contributes zero to the derivative with respect to the discrimination. It still contributes to the derivative with respect to the intercept, whose multiplier is one. These counts came from differentiating the log of a sum at the current vector. In the M step they agree with the marginal-gradient weights at the entering vector, then remain fixed as the inner trial moves.

The function irt_objective() evaluates the negative marginal log likelihood and its gradient at each trial item vector. A specified item prior would contribute its negative log density, but every prior here is NULL. The gradient follows from differentiating the same pattern probabilities.

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
irt_objective <- function(data, templates, rule, priors = rep(list(NULL),
  length(templates))) {
  old <- NULL
  previous_evaluation <- NULL
  evaluate <- function(u) {
    if (identical(u, old)) return(previous_evaluation)
    items <- irt_unpack(u, templates)
    e <- irt_estep(data, items, rule)
    prior <- Map(irt_item_prior, items, priors)
    gradient <- unlist(lapply(seq_along(items), function(j)
      -apply(e$evaluations[[j]]$gradient * as.vector(e$expected[[j]]), 3, sum) -
        prior[[j]]$gradient), use.names = FALSE)
    old <<- u
    previous_evaluation <<- list(value = e$value - sum(vapply(prior, `[[`, 0.0,
      "log_density")),
      negative_marginal_loglik = e$value, log_prior = sum(vapply(prior, `[[`, 0.0,
        "log_density")),
      gradient = gradient, items = items, estep = e)
    previous_evaluation
  }
  list(fn = function(u) tryCatch(evaluate(u)$value, error = function(e) Inf),
    gr = function(u) tryCatch(evaluate(u)$gradient, error = function(e) rep(NA_real_,
      length(u))),
    evaluate = evaluate)
}

At a new trial vector, irt_objective() unpacks the items and calls irt_estep() to compute the pattern probabilities and posterior weights there. Its fn returns the negative log likelihood for minimization. The stored value and gradient can serve two successive requests at identical coordinates. A change in even one discrimination can change every pattern’s allocation across nodes, so the function recomputes the E step when the vector changes. In irt_objective(), -apply sums the weighted log probability derivatives over nodes and categories and negates each parameter component. The prior gradient is zero.

At the common start, the following check compares all sixteen derived components with numerical derivatives of the negative marginal log likelihood.

1
2
3
4
check_objective <- irt_objective(data2, start2, rule61)
print(c(direct_gradient_check = max(abs(num_grad(check_objective$fn,
  irt_pack(start2))$gradient -
  check_objective$gr(irt_pack(start2))))))
1
2
direct_gradient_check 
         4.036015e-07 

The largest absolute discrepancy is $4.04\times10^{-7}$. The numerical calculation perturbs one coordinate at a time, recomputes the marginal criterion on both sides, and combines central differences at four successively halved step sizes. Agreement here checks the sign, the item order and the posterior weighting at this starting vector.

Direct marginal maximum likelihood (MML) passes fn and gr to BFGS in the same packed coordinates. Its line search evaluates the marginal criterion at each new candidate. Gradients at successive accepted points supply the changes used to update the inverse Hessian approximation. Thus a trial change in item one’s slope alters the posterior weights used to evaluate the direct gradient for item two, even if item two’s parameters remain fixed. The direct fit sets the relative tolerance on the objective function to $10^{-8}$. This tolerance concerns the size of the decrease in the value of the objective function relative to its current magnitude. The direct fit returns items and the gradient of the marginal criterion at those items.

1
2
3
4
5
6
7
irt_mml_direct <- function(data, start, rule = irt_rule(61L), priors = rep(list(NULL),
  length(start)), control = list()) {
  objective <- irt_objective(data, start, rule, priors)
  fit <- bfgs(objective$fn, objective$gr, irt_pack(start), modifyList(list(rel_tol = 1e-8),
    control))
  irt_result(fit, objective, rule, priors)
}

EM with Ramsay acceleration

EM uses those posterior allocations to construct a different function for each cycle. Let $u_t$ be the entering vector and let $n_{jqk}^{(t)}$ count responses to item $j$ in category $k$ at node $q$, in expectation given the answers and $u_t$. For a trial vector $u$, the item part of the objective function minimized in the M step is $-Q(u\mid u_t)=-\sum_{j,q,k}n_{jqk}^{(t)}\log P_{jk}(z_q;\theta_j)$, up to a constant. Here $\theta_j=(a_j,d_j)^\top$ is item $j$’s block of $u$. During an M step the expected counts remain fixed while the candidate item probabilities change. The function below combines the eight item objectives for one optimization of all sixteen coordinates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
irt_q_objective <- function(e, templates, rule, priors = rep(list(NULL),
  length(templates))) {
  evaluate <- function(u) {
    items <- irt_unpack(u, templates)
    value <- 0
    gradient <- vector("list", length(items))
    for (j in seq_along(items)) {
      p <- irt_prob(items[[j]], rule$nodes)
      prior <- irt_item_prior(items[[j]], priors[[j]])
      value <- value - sum(e$expected[[j]] * p$logp) - prior$log_density
      gradient[[j]] <- -apply(p$gradient * as.vector(e$expected[[j]]), 3, sum) -
        prior$gradient
    }
    list(value = value, gradient = unlist(gradient, use.names = FALSE))
  }
  list(fn = function(u) tryCatch(evaluate(u)$value, error = function(e) Inf),
    gr = function(u) evaluate(u)$gradient)
}

The argument e supplies the same counts throughout the inner optimization. Only the category probabilities and their derivatives change with a trial. Adding all eight item contributions and concatenating their gradients lets one BFGS run update the sixteen coordinates together. This full calibration does not call irt_mstep_item() and therefore does not inherit its separate accepted and maximized checks. The loop uses the returned inner parameters without requiring inner convergence or explicitly checking an increase in $Q$.

The successive blocks below form one definition of irt_mml_em(). The complete function and the functions it calls are also in code/lib/irt.R. For these 2PL fits, variance and histogram are both false, so the nodes and masses remain fixed. The outer tolerance is $10^{-4}$, with at most 500 cycles. This tolerance measures how far the ordinary update moves each parameter.

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
irt_mml_em <- function(data, start, rule = irt_rule(61L), accelerate = "Ramsay",
                       priors = rep(list(NULL), length(start)), control = list(),
                         variance = FALSE,
                       histogram = FALSE) {
  stopifnot(accelerate %in% c("Ramsay", "squarem", "none"),
    all(names(control) %in% c("tol", "maxit")),
    !(histogram && variance))
  settings <- modifyList(list(tol = 1e-4, maxit = 500L), control)
  logit_index <- unlist(lapply(start, function(item) {
    k <- length(irt_item_pack(item))
    if (item$model == "3PL") seq_len(k) == k else rep(FALSE, k)
  }))
  k_items <- length(logit_index)
  if (variance) logit_index <- c(logit_index, FALSE)
  scale <- function(u) replace(u, logit_index, plogis(u[logit_index]))
  rule_at <- function(u) if (variance) irt_variance_rule(rule$nodes,
    u[k_items + 1L]) else rule
  # The histogram uses the preceding expected node counts after the first cycle.
  masses <- list(rule$weights)
  counts <- NULL
  items_of <- function(u) u[seq_len(k_items)]
  u <- c(irt_pack(start), if (variance) 1)
  pre <- pre2 <- u
  rate <- .4
  loglik <- numeric(0)
  runs <- list()
  converged <- FALSE

The setup stores the entering vectors needed for extrapolation and a separate list of inner optimizer results. With variance=TRUE, the last coordinate of u is the positive ability variance $v$. It describes population differences between examinees in squared ability units; it is distinct from the uncertainty of an individual ability estimate. The call to irt_variance_rule() uses the fixed nodes and normalizes the $N(0,v)$ density values at those nodes to obtain the E-step masses. A free population variance requires a scale restriction such as the fixed Rasch slopes used in Section 10.8. Freely varying both all item discriminations and the population variance would leave the scale unidentified in the continuous model.

At the start of a cycle, the E step supplies both the marginal log likelihood $\ell_t=\ell(u_t)$ and the counts for the new $Q$. The entry recorded in loglik[cycle] therefore belongs to the items entering that cycle. The initial rate $r=0.4$ allows the inner BFGS run $\max(\lceil50r\rceil,15)=20$ iterations. After an increase in the entering likelihood, $r$ becomes $\exp(\ell_{t-1}-\ell_t)$. A large increase brings the allowance toward its minimum of 15, whereas a small positive increase gives an allowance near 50. When the likelihood is unchanged or decreases, the preceding finite rate is retained.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  for (cycle in seq_len(settings$maxit)) {
    if (histogram && cycle > 1L) masses[[cycle]] <- counts / sum(counts)
    e <- irt_estep(data, irt_unpack(items_of(u), start),
      if (histogram) list(nodes = rule$nodes, weights = masses[[cycle]],
        measure = "empirical_histogram") else rule_at(u))
    if (histogram) counts <- e$node_counts
    loglik[cycle] <- -e$value
    if (cycle > 1L) {
      rise <- loglik[cycle] - loglik[cycle - 1L]
      if (rise > 0) rate <- exp(-rise)  # after a rise in the log likelihood
      rate <- if (is.finite(rate)) rate else 1e-6
    }
    pre2 <- pre
    pre <- u
    q <- irt_q_objective(e, start, rule, priors)

The M step optimizes the item parameters with the current expected counts fixed. Before acceleration, the stopping test compares the ordinary update with the entering vector. If every absolute change is strictly below the outer tolerance, the function returns that update. The optional free-variance branch uses a bounded optimizer. With expected node counts $N_q$ fixed, its normal-density contribution and derivative are

\[Q_v(v)=\sum_q N_q\log\phi(z_q;0,v),\qquad \frac{dQ_v(v)}{dv}=\frac{1}{2v^2}\sum_q N_q(z_q^2-v).\]

The M-step expression uses the continuous normal log density, whereas the E step uses normalized masses on the fixed nodes. The fixed nodes approximate integration under the continuous normal model. Maximizing a normalized discrete-mass criterion instead would add $-N\log\sum_q\phi(z_q;0,v)$, where $N=\sum_qN_q$, and would define a different update. The displayed derivative belongs to the continuous-density expression. The calculation here retains the continuous-normal M step with numerical quadrature in the E step.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    if (variance) {
      r <- e$node_counts
      fn <- function(w) {
        v <- w[k_items + 1L]
        if (!(v > 0)) return(1e100)
        -(-q$fn(items_of(w)) + sum(r * irt_log_density(rule$nodes, v)))
      }
      gr <- function(w) {
        v <- w[k_items + 1L]
        g <- 0
        for (k in seq_along(r)) g <- g + r[k] * (((1 / v) * (rule$nodes[k] *
          rule$nodes[k] - 1 * v)) * (1 / v) / 2)
        c(q$gr(items_of(w)), -g)
      }
      # A free variance uses a bounded double-dogleg update.
      run <- dogleg_minimize(u, fn, gr,
        control = list(max_iter = max(ceiling(rate * 100), 25)),
        lower = c(rep(-Inf, k_items), 0), upper = Inf)
      run$converged <- run$convergence == 0L
      run$evaluations <- c(objective = run$evaluations[[1]],
        gradient = run$evaluations[[2]], hessian = 0L)
    } else run <- bfgs(q$fn, q$gr, u, list(maxit = max(ceiling(rate * 50), 15)))
    runs[[cycle]] <- run[c("iterations", "evaluations", "converged")]
    u <- run$par
    if (all(abs(scale(pre) - scale(u)) < settings$tol)) {
      converged <- TRUE
      break
    }

Here $v$ is a variance, and r stores the $N_q$. The function irt_log_density() evaluates the normal log density with a lower numerical bound of $-690.7755$. The loop accumulates the displayed normal-density derivative in g; -g enters the gradient because fn minimizes the negative expected log likelihood. The displayed derivative ceases to differentiate the floored expression where the floor is active.

In the fixed-variance branch, run$par is the numerical M-step candidate. A 2PL item uses its discrimination and intercept directly in the stopping comparison. For a 3PL item, scale() first converts the working logit of the lower asymptote to a probability.

Every third cycle that reaches this point is eligible for acceleration. Write $x_0$ for pre2, $x_1$ for pre, and $x_2$ for the ordinary update in u. The current step is $\Delta=x_2-x_1$ and its second difference is $v=\Delta-(x_1-x_0)$. When the rate $r$ exceeds 0.01, the Ramsay branch sets $b=\max(1-\Vert \Delta\Vert /\Vert v\Vert ,-5)$ and takes $x_2-b\Delta$ directly for the item coordinates. A negative $b$ extends the current step in its own direction. For $r\leq 0.01$, the ordinary update stands. The optional squared extrapolation uses $s=x_1-x_0$ and starts from $\alpha=-\Vert s\Vert /\Vert v\Vert $. Its proposed coordinates are $x_0-2\alpha s+\alpha^2v$. Substitution of $\alpha=-1$ gives $x_2$, which explains the choice at the upper bound.

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
    if (accelerate != "none" && cycle %% 3 == 0) {
      # Extrapolate the item coordinates and retain the current variance.
      items_only <- function(proposal) replace(u, seq_len(k_items),
        proposal[seq_len(k_items)])
      dot <- function(x) {
        total <- 0
        for (value in x) total <- total + value * value
        total
      }
      if (accelerate == "Ramsay" && rate > .01) {
        dX <- u - pre
        d2X <- dX - (pre - pre2)
        accel <- max(1 - sqrt(dot(dX) / dot(d2X)), -5)
        u <- items_only((1 - accel) * u + accel * pre)
      } else if (accelerate == "squarem") {
        # SQUAREM (scheme S3): r, the first change; v, the change in the change.
        point_at <- function(a) items_only(pre2 - 2 * a * r + a^2 * v)
        r <- pre - pre2
        v <- u - pre - r
        accel <- -sqrt(dot(r) / dot(v))
        # A length above -1 becomes -1. Otherwise, while the trial point does not raise the
        # log likelihood (an E-step error counts as no rise), the length moves halfway toward
        # -1; after the fourth failure it is -1.
        if (accel > -1) {
          accel <- -1
        } else {
          for (tries in 1:4) {
            trial <- point_at(accel)

For the squared option, a coefficient above $-1$ is set to $-1$. For a longer trial the code evaluates the marginal log likelihood and requires a strict improvement over $\ell_t$. An invalid trial receives log likelihood $-\infty$. After a failure the next coefficient is $(\alpha-1)/2$, halfway back to $-1$. Four failures restore the ordinary update.

1
2
3
4
5
6
7
8
9
10
11
            trial_loglik <- tryCatch(-irt_estep(data, irt_unpack(items_of(trial), start),
              rule_at(trial))$value,
              error = function(err) -Inf)
            if (trial_loglik > loglik[cycle]) break
            accel <- if (tries == 4L) -1 else (accel - 1) / 2
          }
        }
        u <- point_at(accel)
      }
    }
  }

Here dot() sums the squares of one supplied vector to compute each squared norm. The helper items_only() replaces the item coordinates of a proposal while retaining the current variance, and point_at() constructs the squared extrapolation at a specified coefficient.

The direct assignment in the Ramsay branch has no trial likelihood comparison. The squared option compares response log likelihood without item priors. In histogram mode, rule_at() also supplies the initial weights rather than the current estimated masses. The test therefore does not, in general, check an increase in the criterion being fitted. Both extrapolations require a nonzero second-difference norm; the code has no separate check for a zero denominator.

After the loop, the final evaluation uses the returned items and the final quadrature rule. This can differ from the last entering state stored in the likelihood history.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  # The histogram reported is the normalized expected counts of the last E step.
  final_rule <- if (histogram) list(nodes = rule$nodes, weights = counts / sum(counts),
    measure = "empirical_histogram") else rule_at(u)
  objective <- irt_objective(data, start, final_rule, priors)
  optimizer <- new_result(items_of(u), objective$fn(items_of(u)),
    objective$gr(items_of(u)), converged,
    if (converged) "small_parameter_change" else "iteration_limit", cycle,
    Reduce(`+`, lapply(runs, `[[`, "evaluations")), list(loglik = loglik))
  result <- irt_result(optimizer, objective, final_rule, priors)
  result$mstep_runs <- runs
  result$accelerate <- accelerate
  if (variance) result$constraints$latent_variance <- u[k_items + 1L]
  if (histogram) result$masses <- masses
  result
}

On leaving the loop, irt_result() passes optimizer$par to the objective evaluator and collects the fitted items, criterion, gradient and E-step results. It attaches the optimizer status, quadrature rule and priors, and exposes the person log likelihood contributions as loglik_contributions. Its value is the negative marginal log likelihood minus any specified log prior density at the returned item parameters. Thus the last history entry and the returned value can refer to different vectors even when the change was small enough to stop. The optimizer’s evaluation counts are accumulated from runs, one inner fit per completed cycle. The returned gradient differentiates only item parameters at the final rule. It excludes derivatives with respect to an estimated ability variance or histogram masses, so a small value cannot certify stationarity in those additional parameters.

Comparing the three calibrations

The three fits start the eight items at start2. The label BL refers to the Bock-Lieberman approach of directly maximizing the marginal likelihood. Here that maximization uses BFGS; the label does not mean that the original numerical algorithm has been reproduced. The two EM calls differ only in Ramsay acceleration, with the accelerated calibration stored in fit2. The table compares the attained negative marginal log likelihood, its largest absolute gradient component and the optimizer counts.

1
2
3
4
5
6
7
8
fit2_direct <- irt_mml_direct(data2, start2)
fit2_plain <- irt_mml_em(data2, start2, accelerate = "none")
fit2 <- irt_mml_em(data2, start2)
fit_methods <- list(BL = fit2_direct, EM = fit2_plain, Ramsay_EM = fit2)
print(do.call(rbind, lapply(fit_methods, function(f) c(nll = f$value,
  max_abs_gradient_component = max(abs(f$gradient)), iterations = f$optimizer$iterations,
  objective_function_evaluations = f$optimizer$evaluations[[1]],
    gradient_evaluations = f$optimizer$evaluations[[2]]))))
1
2
3
4
               nll max_abs_gradient_component iterations objective_function_evaluations gradient_evaluations
BL        3821.381                0.008026318         21                             70                   21
EM        3821.381                0.004141828         22                            542                  108
Ramsay_EM 3821.381                0.006723879         16                            431                   86

All three negative marginal log likelihoods round to 3821.381. The column objective_function_evaluations counts evaluations of the function minimized by each optimizer. For BL, the 70 evaluations of the objective function and 21 of the gradient over 21 BFGS iterations refer to the marginal criterion. Ordinary EM took 22 outer cycles. Its 542 evaluations of the objective function and 108 of the gradient sum the inner BFGS calls on the successive fixed-count objective functions. Ramsay EM took 16 cycles, with corresponding counts of 431 and 86. The six-cycle reduction also saves six entering E steps in this fit. Neither EM counter includes those E steps or the separate evaluation at the returned items, so the columns alone cannot measure total computing time. At their endpoints the largest absolute marginal gradient components are about 0.0080, 0.0041 and 0.0067 in row order. They measure the steepest remaining slope among the sixteen coordinate directions. Each method stopped under its own rule, which allows these slopes to differ at the displayed likelihood precision.

How much does the spacing of the ability nodes affect that comparison? With the endpoints of the integration interval fixed, halve the spacing, first from 0.2 to 0.1 and then to 0.05. Evaluating the same item vector on two grids isolates the effect of changing the quadrature rule on the negative log likelihood. Restarting EM on a finer grid also lets the item estimates move.

1
2
3
4
5
6
fit2_121 <- irt_mml_em(data2, fit2$items, irt_rule(121L))
print(c(fixed_parameter_61_to_121 = irt_estep(data2, fit2$items, irt_rule(121L))$value -
  fit2$value,
  refit_working_change = max(abs(irt_pack(fit2_121$items) - irt_pack(fit2$items))),
  fixed_parameter_121_to_241 = irt_estep(data2, fit2_121$items, irt_rule(241L))$value -
    fit2_121$value))
1
2
 fixed_parameter_61_to_121       refit_working_change fixed_parameter_121_to_241 
              4.930598e-08               5.379177e-05               2.953766e-08 

At the retained 61-point Ramsay estimates, fit2$items, the 121-point value exceeds the 61-point value by $4.93\times10^{-8}$. Restarting from those items on 121 nodes moves the most changed working coordinate by $5.38\times10^{-5}$, which includes the effect of further optimization as well as the grid change. The middle column measures a distance in item parameters. The outside columns measure changes in the negative log likelihood summed over examinees. At the refined estimates, fit2_121$items, the 241-point evaluation exceeds the 121-point value by $2.95\times10^{-8}$. The two fixed-vector differences are too small to affect the three decimals reported for these fits. The acceleration of the supplied irt_mml_em() is adapted from the mirt package (code/NOTICE.md), which provides marginal maximum likelihood estimation for these item models. Refining spacing while retaining $[-6,6]$ does not assess the contribution beyond that interval and does not supply a bound on the total integration error.

10.6 Lower asymptotes, ordered thresholds, and Bayesian modal estimation

How much can correct responses at moderate or high ability reveal about an item’s success probability at very low ability? For a 3PL item, the lower asymptote $c$ is the limit of $p(z)=c+(1-c)\operatorname{logit}^{-1}(az+d)$ as ability $z$ tends to $-\infty$. The guessing parameter denotes the lower asymptote; the response model by itself does not identify the proportion of examinees who actually guessed. Consider a single item at five equally spaced abilities from 1 to 2. At each node form 20 expected responses using $a=1$, $d=-0.5$ and $c=0.15$. If $s_q$ of those responses are expected to be correct, a trial probability $p_q$ contributes $s_q\log p_q+(20-s_q)\log(1-p_q)$ to $Q$. Fix $c$ at each of three values and let BFGS optimize the slope and intercept from the same start. The first two components of the item gradient correspond to these free parameters. From the book directory, the following calculation returns one row per fixed asymptote.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
for (file in c("result", "stability", "transforms", "quasi_newton", "irt"))
  source(paste0("code/lib/", file, ".R"), local = TRUE)
weak_nodes <- seq(1, 2, length.out = 5)
weak_item <- irt_item("3PL", a = 1, d = -.5, c = .15)
weak_counts <- 20 * irt_prob(weak_item, weak_nodes)$probability
weak_profiles <- lapply(c(.02, .15, .30), function(cg) {
  evaluate <- function(u) {
    item <- irt_item("3PL", a = u[1], d = u[2], c = cg)
    p <- irt_prob(item, weak_nodes)
    list(value = -sum(weak_counts * p$logp),
      gradient = -apply(p$gradient * as.vector(weak_counts), 3, sum)[1:2])
  }
  fit <- bfgs(function(u) tryCatch(evaluate(u)$value, error = function(e) Inf),
    function(u) evaluate(u)$gradient, c(1, -.5))
  c(c = cg, a = fit$par[1], d = fit$par[2], negative_Q = fit$value)
})
print(do.call(rbind, weak_profiles))
1
2
3
4
        c         a          d negative_Q
[1,] 0.02 0.9510388 -0.2338377   53.35296
[2,] 0.15 1.0000000 -0.5000000   53.35291
[3,] 0.30 1.0904473 -0.9177280   53.35307

As $c$ rises from 0.02 through 0.15 to 0.30, the fitted slope rises from 0.95104 through 1 to 1.09045, while the intercept falls from $-0.23384$ through $-0.5$ to $-0.91773$. After these adjustments the profiled negative $Q$ ranges only from 53.35291 to 53.35307. This profile uses fixed, constructed expected counts. An observed-data likelihood-ratio cutoff does not apply to differences in this conditional criterion.

To see what the adjustments accomplish, compare the three fitted probabilities at the same ability. For a specified success probability $p>c$, the logistic component must equal $(p-c)/(1-c)$. Raising $c$ therefore requires a smaller logistic component to reproduce $p$. Changing both $d$ and $a$ lets that adjustment differ across the five nodes. Each row of profiles supplies one whole item. The second column returned by irt_prob() gives the chance of a correct response at each original node.

1
2
3
4
5
6
7
8
profiles <- do.call(rbind, weak_profiles)
weak <- do.call(rbind, lapply(seq_len(nrow(profiles)), function(j) {
  par <- profiles[j, ]
  item <- irt_item("3PL", a = par[["a"]], d = par[["d"]], c = par[["c"]])
  data.frame(trait = weak_nodes, c = item$c, a = item$a, d = item$d,
    correct = irt_prob(item, weak_nodes)$probability[, 2])
}))
print(weak, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 trait    c         a          d   correct
  1.00 0.02 0.9510388 -0.2338377 0.6785506
  1.25 0.02 0.9510388 -0.2338377 0.7276695
  1.50 0.02 0.9510388 -0.2338377 0.7718827
  1.75 0.02 0.9510388 -0.2338377 0.8108366
  2.00 0.02 0.9510388 -0.2338377 0.8445142
  1.00 0.15 1.0000000 -0.5000000 0.6790904
  1.25 0.15 1.0000000 -0.5000000 0.7273019
  1.50 0.15 1.0000000 -0.5000000 0.7713998
  1.75 0.15 1.0000000 -0.5000000 0.8107049
  2.00 0.15 1.0000000 -0.5000000 0.8449383
  1.00 0.30 1.0904473 -0.9177280 0.6801510
  1.25 0.30 1.0904473 -0.9177280 0.7266700
  1.50 0.30 1.0904473 -0.9177280 0.7705077
  1.75 0.30 1.0904473 -0.9177280 0.8104383
  2.00 0.30 1.0904473 -0.9177280 0.8456995

At ability 1 the probabilities range from 0.67855 to 0.68015. At ability 2 they range from 0.84451 to 0.84570. Even the ordering changes inside the interval. At 1.50 the item with $c=0.30$ has the lowest success probability of the three. A difference of 0.28 between lower asymptotes can thus accompany differences smaller than 0.002 at all five abilities supplying counts.

A prior on the lower asymptote

A prior can influence the estimate when the counts distinguish these curves so weakly. Let $\gamma=\log\lbrace c/(1-c)\rbrace $ be the working parameter and give it a normal prior with mean $-1.5$ and standard deviation 3. If $\pi_\gamma$ denotes its density, the Bayesian modal item update maximizes

\[Q(a,d,\gamma)+\log\pi_\gamma(\gamma) =Q(a,d,\gamma)-\frac{(\gamma+1.5)^2}{18}-\log(3\sqrt{2\pi}).\]

The M step subtracts the log prior density from the negative $Q$ it minimizes. The density and optimization both use $\gamma$, so no Jacobian enters. Transforming this mode to $c$ does not generally give the mode of a density expressed in $c$. All three item parameters are now free, with the same five rows of counts.

1
2
3
weak_modal <- irt_mstep_item(weak_counts, weak_nodes, weak_item, prior = c(-1.5, 3))
print(c(a = weak_modal$item$a, d = weak_modal$item$d, c = weak_modal$item$c,
  log_prior = irt_item_prior(weak_modal$item, c(-1.5, 3))$log_density))
1
2
         a          d          c  log_prior 
 1.0156068 -0.5778123  0.1823559 -2.0175508 

The returned lower asymptote 0.18236 is just $0.0000696$ below $\operatorname{logit}^{-1}(-1.5)=0.1824255$, the probability corresponding to the prior mode on the logit scale. The log prior density at the returned item is $-2.01755$, equal to its peak to five decimals. This is one item update conditional on its expected counts.

Nearly coincident graded thresholds

A different boundary issue arises for ordered graded-response thresholds. The gap between two adjacent thresholds can approach zero, making the intervening category probability tend to zero. For a graded item with slope one, let $C_h(z)=\operatorname{logit}^{-1}(z-b_h)$ be the probability of scoring at least $h$. With thresholds $(-1,0,10^{-8})$, the probability of score two at ability zero is $C_2(0)-C_3(0)$. The two cumulative probabilities differ by about $10^{-8}/4$ because the inverse logit function has derivative $1/4$ at zero. For a separate M step, construct 100 expected responses at each of nine nodes from an item with thresholds $(-1,0,1)$. Pool the counts for scores one and two into the score-one column, leaving zero in the score-two column. Fit all four declared categories, then fit the three columns with retained scores.

1
2
3
4
5
6
7
8
9
10
11
near_empty <- irt_prob(irt_item("GRM", cuts = c(-1, 0, 1e-8)), 0)$probability
empty_nodes <- seq(-2, 2, length.out = 9)
empty_counts <- 100 * irt_prob(irt_item("GRM",
  cuts = c(-1, 0, 1)), empty_nodes)$probability
empty_counts[, 2] <- empty_counts[, 2] + empty_counts[, 3]
empty_counts[, 3] <- 0
empty_full <- irt_mstep_item(empty_counts, empty_nodes,
  irt_item("GRM", cuts = c(-1, 0, 1)))
empty_reduced <- irt_mstep_item(empty_counts[, c(1, 2, 4)], empty_nodes,
  irt_item("GRM", cuts = c(-1, 1)))
print(near_empty)
1
2
          [,1]      [,2]    [,3] [,4]
[1,] 0.2689414 0.2310586 2.5e-09  0.5

The one-node example gives probabilities 0.26894, 0.23106, $2.5\times10^{-9}$ and 0.5. In the nine-node example, the zero count gives score two no direct term in $Q$, but its two bounding thresholds also determine probabilities for the neighboring scores. The next print gives the two negative $Q$ values and the gap between the last two thresholds of the four-category fit.

1
2
3
print(c(full_negative_Q = empty_full$optimizer$value,
  reduced_negative_Q = empty_reduced$optimizer$value,
  final_cut_gap = diff(tail(empty_full$item$cuts, 2))))
1
2
   full_negative_Q reduced_negative_Q      final_cut_gap 
      8.305457e+02       8.196817e+02       1.272344e-07 

Pooling scores one and two gives $(C_1-C_2)+(C_2-C_3)=C_1-C_3$. If the bounding thresholds coincide, $C_2=C_3$, score two has zero probability and the three retained probabilities agree with those of the reduced item at corresponding parameters. Equality is a limiting case because the four-category item requires strictly ordered thresholds. The four-category fit returned a gap of $1.27\times10^{-7}$ and a negative $Q$ of 830.5457. The reduced fit reached 819.6817.

1
print(c(full=empty_full$optimizer$reason,reduced=empty_reduced$optimizer$reason))
1
2
       full     reduced 
"converged" "converged" 

Both optimizers report convergence, yet their negative $Q$ values differ by about 10.86. The gap of $1.27\times10^{-7}$ is a distance between two thresholds within the four-category fit, whereas the difference in negative $Q$ compares the two fits. The printed endpoints and stopping reasons do not identify the cause of that difference.

Sensitivity to starting values and lower asymptotes near zero

The examples above used constructed counts for single items; the same weak determination appears in a full calibration. For the 16-item 3PL companion IRT16-3, ability is unobserved and the criterion is the marginal likelihood of 800 examinees’ response vectors. The responses Y3 are supplied in data/source/ch10/IRT16-3.rds. The item templates in start3 provide the initial slopes and intercepts, and data3 contains the response patterns and frequencies. How much do the returned estimates depend on the starting items? Three EM runs set all sixteen initial lower asymptotes to 0.05, 0.15 or 0.30 and retain the other starting coordinates. Twelve further starts use seed 20261120. For each item they draw $\log a\sim N(\log 0.8,0.3^2)$, $d\sim N(0,0.5^2)$ and $c\sim\mathrm{Uniform}(0.02,0.30)$. All runs use the same 61-node standard normal rule and Ramsay acceleration.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Y3 <- readRDS("data/source/ch10/IRT16-3.rds")
start3 <- irt_start(Y3, "3PL")
data3 <- irt_data(Y3, start3)
fit3_starts <- lapply(c(.05, .15, .3), function(cg) {
  initial <- lapply(start3, function(item) { item$c <- cg; item })
  irt_mml_em(data3, initial)
})
set.seed(20261120)
random_starts3 <- lapply(1:12, function(k) lapply(1:16, function(j) irt_item("3PL",
  a = exp(rnorm(1, log(.8), .3)), d = rnorm(1, 0, .5), c = runif(1, .02, .3))))
fit3_starts <- c(fit3_starts,
  lapply(random_starts3, function(initial) irt_mml_em(data3, initial)))
names(fit3_starts) <- c(paste0("c_", c(.05, .15, .3)), paste0("random_", 1:12))
fit3_best <- fit3_starts[[which.min(vapply(fit3_starts, `[[`, 0.0, "value"))]]

which.min() retains the run with the lowest negative marginal log likelihood. The preceding block reproduces the fifteen calibrations. The following table uses their saved fit objects in the original order, replacing fit3_starts with those records. The refinement column evaluates the response criterion at the returned items using 121 nodes and subtracts its 61-node value.

1
2
3
4
5
6
7
8
9
10
saved <- readRDS("data/derived/ch10/fits.rds")
fit3_starts <- saved$unpenalized_3PL
print(do.call(rbind, lapply(fit3_starts, function(f) c(negative_loglik = f$value,
  converged = f$converged,
  iterations = f$optimizer$iterations,
  max_abs_gradient_component = max(abs(f$gradient)),
    max_a = max(vapply(f$items, `[[`, 0.0, "a")),
  min_c = min(vapply(f$items, `[[`, 0.0, "c")), max_c = max(vapply(f$items, `[[`, 0.0,
    "c")),
  refinement = irt_estep(data3, f$items, irt_rule(121L))$value - f$value))))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
          negative_loglik converged iterations max_abs_gradient_component    max_a        min_c     max_c
c_0.05           7884.440         0        500                0.040908356 2.926386 0.0020933779 0.4436795
c_0.15           7884.446         0        500                0.041426925 2.946585 0.0024257140 0.4438527
c_0.3            7884.402         1        178                0.008995635 2.990260 0.0001064637 0.4448405
random_1         7884.433         0        500                0.030012583 2.958243 0.0017663863 0.4434567
random_2         7884.444         0        500                0.040168337 2.987089 0.0022804977 0.4444775
random_3         7884.417         0        500                0.034188776 2.921847 0.0007661296 0.4442820
random_4         7884.429         0        500                0.034679011 2.927884 0.0013713646 0.4442704
random_5         7884.442         0        500                0.042288996 2.926091 0.0020101977 0.4442339
random_6         7884.452         0        500                0.052109732 2.927624 0.0023967153 0.4443200
random_7         7884.451         0        500                0.049245339 2.935440 0.0023783148 0.4441589
random_8         7884.401         1        209                0.012406876 2.911941 0.0001025314 0.4427090
random_9         7884.430         0        500                0.032081268 2.935218 0.0015642930 0.4435438
random_10        7884.421         0        500                0.031591363 2.922760 0.0010447847 0.4437074
random_11        7884.423         0        500                0.029615915 2.925360 0.0012155330 0.4436755
random_12        7884.434         0        500                0.036274225 2.933516 0.0016721793 0.4440812
            refinement
c_0.05    1.496001e-07
c_0.15    1.472481e-07
c_0.3     1.457947e-07
random_1  1.501376e-07
random_2  1.421358e-07
random_3  1.431681e-07
random_4  1.428089e-07
random_5  1.424414e-07
random_6  1.448234e-07
random_7  1.464532e-07
random_8  1.497965e-07
random_9  1.479857e-07
random_10 1.478229e-07
random_11 1.462840e-07
random_12 1.446260e-07

A zero in the convergence column marks the thirteen runs that reach the 500-cycle limit. Their negative log likelihoods range from 7884.417 to 7884.452 and their largest absolute marginal gradient components from 0.030 to 0.052. Two runs meet the parameter-change rule. Starting at $c=0.30$ gives 7884.402 after 178 cycles. The eighth random start gives 7884.401 after 209 cycles, the smallest value observed among the fifteen. Across all runs the largest slope ranges from 2.91 to 2.99, the smallest lower asymptote from about 0.00010 to 0.00243, and the largest lower asymptote remains near 0.44. Grid refinement changes each negative log likelihood by about $1.5\times10^{-7}$. These endpoints are consistent with weak determination of some item parameters. They give neither the likelihood along a path between endpoints nor a guarantee of a global maximum. A small positive asymptote is not an estimate exactly equal to zero. The table does not measure likelihood curvature, which would require second derivatives or additional evaluations around an estimate.

What changes when each of the sixteen lower-asymptote logits receives the normal prior used for the single item? The usual unpenalized maximum likelihood (ML) run starts each $c$ at 0.15. The maximum a posteriori (MAP) run, which seeks the posterior mode in the stated parameterization, starts each at $\operatorname{logit}^{-1}(-1.5)$ and adds the sixteen log prior densities to the marginal log likelihood.

1
2
3
prior3 <- rep(list(c(-1.5, 3)), 16)
fit3 <- irt_mml_em(data3, start3)
fit3_modal <- irt_mml_em(data3, irt_start(Y3, "3PL", prior = c(-1.5, 3)), priors = prior3)

The two saved objects correspond to these particular starts. The gradient in each row is for the function that run minimized.

1
2
3
4
5
6
7
8
9
fit3 <- saved$ML_3PL
fit3_modal <- saved$modal_3PL
print(do.call(rbind, lapply(list(ML = fit3, MAP = fit3_modal),
  function(f) c(negative_loglik = f$negative_marginal_loglik, log_prior = f$log_prior,
    negative_loglik_minus_log_prior = f$value,
      max_abs_gradient_component = max(abs(f$gradient)),
    converged = f$converged, iterations = f$optimizer$iterations,
    min_c = min(vapply(f$items, `[[`, 0.0, "c")),
      max_c = max(vapply(f$items, `[[`, 0.0, "c"))))))
1
2
3
4
5
6
    negative_loglik log_prior negative_loglik_minus_log_prior max_abs_gradient_component converged iterations
ML         7884.446    0.0000                        7884.446                 0.04142693         0        500
MAP        7884.975  -32.8665                        7917.841                 0.01134645         1        133
          min_c     max_c
ML  0.002425714 0.4438527
MAP 0.036052149 0.4369534

The unpenalized run reaches 500 cycles at 7884.446, with maximum absolute gradient component 0.041 and smallest $c=0.0024$. The MAP run meets the stopping rule in 133 cycles. Its negative marginal log likelihood is 7884.975 and its log prior density is $-32.8665$, giving 7917.841 for the minimized criterion. The largest absolute partial derivative of that criterion is 0.011. With the prior, the smallest lower asymptote is 0.036 and the largest is 0.437. The fitted lower asymptotes remain farther from zero in this run.

To check the integration in the MAP row, fix its item parameters and compare the response likelihood on the two grids.

1
2
print(c(MAP_61_to_121 = irt_estep(data3, fit3_modal$items, irt_rule(121L))$value -
  fit3_modal$negative_marginal_loglik))
1
2
MAP_61_to_121 
  1.25222e-07 

The negative marginal log likelihood changes by only $1.25\times10^{-7}$.

On the response data alone, the two returned vectors have log likelihoods of $-7884.446$ for the usual unpenalized start and $-7884.975$ for the MAP start, a decrease of about 0.53. The zero in the ML row’s log_prior column records that the fit used no prior. Comparing posterior densities at these two vectors would require evaluating the same sixteen normal densities at the ML logits as well. The value 7917.841 describes the MAP endpoint on the stated logit scale. Establishing a global optimum for either criterion would require more than these endpoint evaluations. The mirt package supports Bayesian modal estimation of item parameters.

10.7 Estimating the latent distribution with an empirical histogram

Suppose more examinees answer either very few or very many items correctly than a normal ability distribution would predict. Can the responses indicate how much probability to assign to different parts of the ability scale? Retain the 2PL form for the eight item curves and let the distribution place mass $\pi_q$ at ability $z_q$, with $\pi_q\geq 0$ and $\sum_q\pi_q=1$. For response pattern $h$, write $L_h(z_q;\theta)$ for the product of its conditional item probabilities. Its marginal probability is now $\sum_q\pi_q L_h(z_q;\theta)$. The same population masses enter every examinee’s pattern probability. In an empirical histogram fit, these masses are estimated along with the item parameters $\theta$.

Here empirical histogram names the estimated masses on a fixed grid. The masses are population proportions; a person’s posterior probabilities depend additionally on that person’s answers. The fitted object is a discrete distribution, not a continuous density whose heights can be read directly as probabilities.

The grid and its initial masses are constructed as follows. Load the item functions from the book directory. With its default arguments, irt_histogram_rule() sets up 121 equally spaced abilities between $-6$ and $6$. It assigns each point an initial mass proportional to the standard normal density there. The node locations remain fixed throughout estimation.

1
2
3
4
5
6
7
8
for (file in c("result", "stability", "transforms", "quasi_newton", "irt"))
  source(paste0("code/lib/", file, ".R"), local = TRUE)
irt_histogram_rule <- function(nodes = seq(-6, 6, length.out = 121L)) {
  stopifnot(length(nodes) >= 3L, all(diff(nodes) > 0))
  # Initialize normal masses at the supplied nodes. The nodes stay fixed during fitting.
  list(nodes = nodes, weights = normalize_logweights(dnorm(nodes, log = TRUE)),
    measure = "empirical_histogram")
}

To estimate a population mass, consider first what would happen if each examinee’s node were observed. The joint probability of that person’s node and responses would contain one factor $\pi_q$. Taking its logarithm adds $\log\pi_q$ to the response terms. With ability unobserved, an examinee with pattern $h$ contributes a fraction $\tau_{hq}=\pi_q L_h(z_q;\theta)/\sum_r\pi_r L_h(z_r;\theta)$ to the count at $q$. If $f_h$ people have that pattern, the expected count is $N_q=\sum_h f_h\tau_{hq}$. Each posterior row sums to one, so summing the expected counts over nodes recovers the number of examinees. With these counts fixed, maximize the mass term subject to unit total mass. For positive counts the Lagrange multiplier $\lambda$ satisfies

\[\frac{\partial}{\partial\pi_q} \left\{\sum_r N_r\log\pi_r-\lambda\left(\sum_r\pi_r-1\right)\right\} =\frac{N_q}{\pi_q}-\lambda=0, \qquad \pi_q^{\mathrm{new}}=\frac{N_q}{\sum_r N_r}.\]

The denominator follows by summing $N_q=\lambda\pi_q$ over $q$. A node with zero expected count receives zero mass. The update thus averages the individual posterior probabilities to estimate a population proportion, which the next E step can use for an examinee with any response pattern.

Changes of scale and standardization

Fixing the nodes also fixes the coordinate system in which these proportions are reported. If the node locations could shift and stretch freely, items with free intercepts and discriminations could absorb the same change of scale. The responses alone could not distinguish those descriptions of the population. Fixing a grid does not by itself prove that its masses and all item parameters are jointly identifiable from the finite set of response-pattern probabilities. In particular, leaving masses unrestricted does not impose a population mean of zero or variance of one.

To see exactly what such a change of scale preserves, let $m=\sum_q\pi_qz_q$ and $s^2=\sum_q\pi_q(z_q-m)^2$. For $s>0$, write $z_q^\ast =(z_q-m)/s$. Substituting $z_q=m+sz_q^\ast $ in the 2PL linear predictor gives

\[d+az_q=(d+am)+(as)z_q^*=d^*+a^*z_q^* .\]

Thus irt_standardize() changes the intercept to $d+am$ and the discrimination to $as$. The corresponding nodes have identical response probabilities for each item. Leaving their masses unchanged preserves the weighted probability of every response pattern, while the transformed nodes have weighted mean zero and variance one. A zero variance leaves no scale by which to divide.

For a Rasch item the slope must remain one, which requires $1\times s=1$. At a shifted node its linear predictor is $(z_q-m)+(d+m)=z_q+d$, giving the original Rasch probability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
irt_standardize <- function(items, nodes, weights) {
  stopifnot(all(vapply(items, function(item) item$model %in% c("2PL", "Rasch"), TRUE)),
    length(nodes) == length(weights), all(is.finite(nodes)), all(is.finite(weights)),
    abs(sum(weights) - 1) < 1e-12, all(weights >= 0))
  mean <- sum(weights * nodes)
  sd <- sqrt(sum(weights * (nodes - mean)^2))
  if (!is.finite(sd) ||
    sd == 0) stop("Standardization requires a positive latent variance.")
  if (any(vapply(items, function(item) item$model == "Rasch", TRUE))) {
    if (abs(sd - 1) > 1e-12)
      stop(
"Unit Rasch slopes and unchanged response probabilities require the original trait scale."
      )
    sd <- 1
  }
  # z = mean + sd * z_new leaves every linear predictor d + a * z unchanged.
  items <- lapply(items, function(item) {
    item$d <- item$d + item$a * mean
    item$a <- item$a * sd
    item
  })
  list(items = items, nodes = (nodes - mean) / sd, weights = weights,
    mean = mean, sd = sd)
}

If any item is Rasch, the function requires a positive $s$ within $10^{-12}$ of one, sets it to one and shifts location only.

To check the transformation separately from fitting responses, construct positive counts from a formula on the default grid, normalize them, and take a 2PL item with $a=1.2$ and $d=-0.3$. The function moments() computes moments from the supplied node and weight vectors.

1
2
3
4
5
6
7
8
9
hist_rule <- irt_histogram_rule()
mass_counts <- 25 * exp(.4 * hist_rule$nodes - .2 * hist_rule$nodes^2) + .1
proportions <- mass_counts / sum(mass_counts)
example_item <- list(irt_item("2PL", a = 1.2, d = -.3))
standardized <- irt_standardize(example_item, hist_rule$nodes, proportions)
moments <- function(nodes, weights) c(total = sum(weights), mean = sum(weights * nodes),
  variance = sum(weights * (nodes - sum(weights * nodes))^2))
print(rbind(illustrative_proportions = moments(hist_rule$nodes, proportions),
  standardized = moments(standardized$nodes, standardized$weights)))
1
2
3
                         total         mean variance
illustrative_proportions     1 9.863212e-01 2.586389
standardized                 1 2.925177e-16 1.000000

The illustrative proportions are calculated from mass_counts, without responses or an E step. The total remains one. The original mean 0.98632 and variance 2.58639 become a mean of $2.93\times10^{-16}$ and variance one. The change in units should also be visible in the item parameters.

1
2
3
print(c(a = standardized$items[[1]]$a, d = standardized$items[[1]]$d,
  linear_predictor_change = max(abs(-.3 + 1.2 * hist_rule$nodes - (standardized$items[[1]]$d +
    standardized$items[[1]]$a * standardized$nodes)))))
1
2
                      a                       d linear_predictor_change 
           1.929870e+00            8.835854e-01            8.881784e-16 

The new discrimination is 1.929870 and the new intercept is 0.883585. The maximum absolute change in the linear predictor across the 121 corresponding pairs of nodes is $8.88\times10^{-16}$. This calculation changes the numbers printed as abilities and item parameters while preserving the response curves at corresponding abilities.

Fitting the histogram by EM

The fitting function irt_histogram() retains the original grid. Its first E step uses the initial normal masses. At the beginning of each subsequent cycle, irt_mml_em() divides the preceding expected counts by their total and uses those masses at the same nodes. The ordinary M step updates the item parameters. EM stops if every absolute item change from the entering value is below $10^{-4}$, with a limit of 2,000 cycles. The masses do not enter that test.

1
2
3
4
5
6
7
8
9
10
11
12
13
irt_histogram <- function(data, start, rule = irt_histogram_rule(), control = list()) {
  # Update mass at each fixed node from the preceding expected count.
  stopifnot(all(names(control) %in% c("maxit", "tol")))
  settings <- modifyList(list(maxit = 2000L, tol = 1e-4), control)
  fit <- irt_mml_em(data, start, rule, control = settings, histogram = TRUE)
  n <- length(fit$masses)
  loglik <- fit$optimizer$history$loglik
  # Compare the last two entering likelihoods and the last entering and returned masses.
  fit$iterations <- fit$optimizer$iterations
  fit$last_gain <- if (n > 1L) loglik[n] - loglik[n - 1L] else NA_real_
  fit$last_mass_change <- max(abs(fit$rule$weights - fit$masses[[n]]))
  fit
}

If $t$ is the stopping cycle, last_gain subtracts the marginal log likelihood entering $t-1$ from the one entering $t$. The second diagnostic, last_mass_change, compares the masses used in cycle $t$ with those returned by normalizing that cycle’s E-step counts.

The final value of the objective function is evaluated at the returned item parameters and masses. For a returned object named fit, calculate the population moments with moments(fit$rule$nodes, fit$rule$weights). The mean and variance fields in fit$constraints retain generic defaults and do not give this histogram’s fitted moments. For the free-normal-variance branch, the reported variance parameter likewise describes the normal density used to construct the weights; the actual variance of the normalized finite grid is computed from its nodes and weights.

A small change over one EM cycle can occur where progress is slow and therefore gives no distance to a maximizer. With the item curves fixed, each pattern contributes the logarithm of a linear function of the masses, a concave function. This conditional concavity gives no assurance that the returned items and masses together constitute a stationary or unique joint solution.

Grid choice in one sample

How much does the estimated distribution depend on the chosen grid in one sample? Generate abilities for 800 examinees from a mixture with component means $-1$ and $1$, common standard deviation 0.5 and respective mixing proportions 0.4 and 0.6. Before standardization its mean is 0.2 and its variance is $0.5^2+0.4(-1-0.2)^2+0.6(1-0.2)^2=1.21$. Subtract the mean and divide by $\sqrt{1.21}$ before drawing the eight IRT8 responses. Seed 1007 produces the matrix supplied in data/source/ch10/IRT8-histogram.rds. The items in start2 supply the category structure to irt_data(). The fits take their starting values from the new responses YH.

1
2
3
4
5
6
7
8
9
10
11
12
13
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
slopes <- c(.7, .9, 1, 1.1, 1.2, .8, 1.3, 1)
difficulty <- seq(-1.5, 1.5, length.out = 8)
truth2 <- lapply(1:8, function(j) dichotomous_item("2PL", a = slopes[j],
  d = -slopes[j] * difficulty[j]))
Y2 <- readRDS("data/source/ch10/IRT8-2.rds")
start2 <- irt_start(Y2, "2PL")
set.seed(1007)
group <- runif(800) < .4
zH <- (ifelse(group, -1, 1) + rnorm(800, 0, .5) - .2) / sqrt(1.21)
YH <- irt_generate(truth2, zH)
dataH <- irt_data(YH, start2)
fitH_normal <- irt_mml_em(dataH, irt_start(YH, "2PL"))

Fit a pair of models on each grid. The first retains the initial normal masses and the second estimates them. The first two grids have the same endpoints and different spacing. The second and third have the same number of points but cover different intervals. Within each pair the starting items and node locations agree. The generating mixture also gives a known probability for the event $Z\leq 0$. In the original units this event includes abilities up to 0.2, so its probability is $0.4\Phi(2.4)+0.6\Phi(-1.6)$, with $\Phi$ the standard normal distribution function.

1
2
3
4
5
6
7
8
9
10
hist_grids <- list(seq(-4, 4, length.out = 31), seq(-4, 4, length.out = 41),
  seq(-5, 5, length.out = 41))
grid_rules <- lapply(hist_grids, irt_histogram_rule)
# Hold the grid and starting items constant within each pair of fits.
fixed_grid_fits <- lapply(grid_rules, function(rule)
  irt_mml_em(dataH, irt_start(YH, "2PL"), rule))
fitH <- lapply(grid_rules,
  function(rule) irt_histogram(dataH, irt_start(YH, "2PL"), rule))
mixture_cdf <- function(z) .4 * pnorm((sqrt(1.21) * z + .2 + 1) / .5) +
  .6 * pnorm((sqrt(1.21) * z + .2 - 1) / .5)

As a separate quadrature check, evaluate the ordinary normal fit on its 61 points over $[-6,6]$ and then on 121 points over the same interval, with the item parameters fixed.

1
2
3
4
print(c(normal_61_negative_loglik = fitH_normal$value,
  same_parameters_normal_121_negative_loglik =
    irt_estep(dataH, fitH_normal$items, irt_rule(121L))$value,
  true_mass_at_or_below_zero = mixture_cdf(0)))
1
2
3
4
                 normal_61_negative_loglik same_parameters_normal_121_negative_loglik 
                              3835.9756880                               3835.9756880 
                true_mass_at_or_below_zero 
                                 0.4296006 

Both normal evaluations give 3835.9756880 at the precision shown. The mixture puts 0.4296006 of its probability at or below zero. To estimate this quantity on each of the three coarser grids, sum the returned masses through the node at zero, including that node.

1
2
3
4
5
6
7
print(do.call(rbind, Map(function(f, fixed, grid) data.frame(nodes = length(grid),
  extent = max(grid), fixed_grid_nll = fixed$value, histogram_nll = f$value,
  fixed_converged = fixed$converged, histogram_converged = f$converged,
  iterations = f$iterations, last_nll_gain = f$last_gain,
  last_mass_change = f$last_mass_change,
  mass_at_or_below_zero = sum(f$rule$weights[f$rule$nodes <= 0])),
  fitH, fixed_grid_fits, hist_grids)))
1
2
3
4
5
6
7
8
  nodes extent fixed_grid_nll histogram_nll fixed_converged histogram_converged iterations last_nll_gain
1    31      4       3835.971      3826.522            TRUE                TRUE        480  0.0004145707
2    41      4       3835.970      3826.522            TRUE                TRUE        480  0.0004154795
3    41      5       3835.976      3826.518            TRUE                TRUE        486  0.0003966058
  last_mass_change mass_at_or_below_zero
1     1.054517e-04             0.4708058
2     7.751069e-05             0.4695736
3     7.514593e-05             0.4704562

For 31 and 41 points over $[-4,4]$ and 41 over $[-5,5]$, the fixed-mass negative log likelihoods are 3835.971, 3835.970 and 3835.976. Estimating masses lowers them to 3826.522, 3826.522 and 3826.518. The histogram fits meet the item-change rule in 480, 480 and 486 cycles. The positive last_nll_gain entries correspond to decreases of about $4\times10^{-4}$ in negative log likelihood between the last two entering states. The largest final mass changes are $1.05\times10^{-4}$, $7.75\times10^{-5}$ and $7.51\times10^{-5}$. The first exceeds the item tolerance even though that run stopped. The three cumulative masses are 0.47081, 0.46957 and 0.47046. Their spread is less than 0.0013 across grids, yet all exceed the generating probability by about 0.04 in this sample. These estimates use only the item responses. The simulated abilities are used to draw those responses and are withheld from the fits.

Repeated samples from the mixture

Would another sample from the same mixture give the same excess? In the saved histogram study, each of 200 samples has its own L’Ecuyer-CMRG random number stream from seed 101007. Each sample has 800 examinees and the same eight 2PL items. Every histogram uses the default 121 points on $[-6,6]$. The saved records supply the stop indicator and the fitted distribution for each sample. For a run meeting the item-change rule, let $\widehat F_i(0)$ be the sum of its masses over nodes $z_q\leq 0$. Subtracting mixture_cdf(0) gives the error for that sample. Average the errors to estimate bias, and take the square root of their mean square to obtain the root mean squared error (RMSE). The Monte Carlo standard error of the mean is the sample standard deviation of the retained estimates $\widehat F_i(0)$ divided by the square root of their number. It measures variation in this summary across repeated simulation studies.

1
2
3
4
5
6
7
8
9
study_histogram <- readRDS("data/derived/ch10/study-histogram.rds")
hist_ok <- vapply(study_histogram$results,
  function(r) isTRUE(r$histogram$converged), TRUE)
hist_mass <- vapply(study_histogram$results[hist_ok], function(r)
  sum(r$histogram$rule$weights[r$histogram$rule$nodes <= 0]), 0.0)
print(c(replications = 200, converged_histogram = sum(hist_ok),
  mean_mass_at_or_below_zero = mean(hist_mass), bias = mean(hist_mass) - mixture_cdf(0),
  MCSE_mean = sd(hist_mass) / sqrt(length(hist_mass)),
  RMSE = sqrt(mean((hist_mass - mixture_cdf(0))^2)), normal_mass_at_or_below_zero = .5))
1
2
3
4
5
6
                replications          converged_histogram   mean_mass_at_or_below_zero 
                2.000000e+02                 2.000000e+02                 4.522882e-01 
                        bias                    MCSE_mean                         RMSE 
                2.268769e-02                 2.808447e-03                 4.565434e-02 
normal_mass_at_or_below_zero 
                5.000000e-01 

All 200 fits met the item-change rule, so every sample contributes. The sum includes mass at zero. Its mean is 0.45229 and its mean error is 0.02269. The sample standard deviation of the fitted masses divided by $\sqrt{200}$ gives a Monte Carlo standard error of 0.00281 for the mean. The mean error is about eight such standard errors above zero, in the same direction as the single-sample excess. The RMSE of 0.04565 also reflects variation between samples. The reference value 0.5 is the continuous standard normal probability through zero. On a symmetric discrete grid with mass $w_0$ at zero, including that point would instead give $(1+w_0)/2$. A concentration of mass at a single node must be read at the resolution of its grid. The cumulative mass through zero changed little across the three grids in one sample. The repeated samples quantify the excess on the default grid without identifying its cause. The mirt package provides empirical histogram estimation for item response models.

10.8 Rasch conditional likelihood, elementary symmetric functions, and the limitations of joint maximum likelihood

Two examinees each answer three of eight items correctly, but they answer different items correctly. What do comparisons between patterns with the same total reveal about item difficulty? In the Rasch model every item has slope one, and an examinee of ability $z$ answers item $j$ correctly with probability $\operatorname{logit}^{-1}(z-b_j)$, where $b_j$ is its difficulty. Let $y=(y_1,\ldots,y_J)$ be a complete vector of zeros and ones and let $r=\sum_j y_j$. By conditional independence, the probability of this pattern factors as

\[\Pr(Y=y\mid z,b) =\prod_{j=1}^J\frac{\exp\{y_j(z-b_j)\}}{1+\exp(z-b_j)} =\frac{\exp(zr)}{\prod_{j=1}^J\{1+\exp(z-b_j)\}}\, \exp\!\left(-\sum_{j=1}^J y_j b_j\right).\]

The first factor has the same value for every pattern with total $r$. Dividing by the sum of the pattern probabilities at that total cancels it. The total score $R$ is therefore sufficient for the person’s ability given the difficulties. Which items were answered correctly still carries information about the difficulties, and the conditional probability of that pattern can be computed without assigning a population distribution to $z$.

Consider first an examinee with one correct answer. The pattern in which item $j$ alone is correct has weight $w_j=\exp(-b_j)$. Its conditional probability is $w_j/(w_1+\cdots+w_J)$, so easier items receive more weight. With $r$ correct answers, the numerator is the product of the weights of those $r$ items. The denominator sums such products over every subset $S$ of size $r$. This sum is the elementary symmetric function of degree $r$,

\[e_r(w)=\sum_{S:\,|S|=r}\prod_{j\in S}w_j, \qquad \Pr(Y=y\mid R=r,b)=\frac{\prod_{j=1}^J w_j^{y_j}}{e_r(w)}.\]

Adding the same constant $k$ to every difficulty multiplies each degree-$r$ product by $\exp(-kr)$. The numerator and denominator acquire the same factor, leaving only difficulty differences identifiable. The restriction $\sum_j b_j=0$ expresses each difficulty relative to the mean difficulty of these items.

The denominator for total two already has one term for each distinct pair. To compute all denominators without listing the subsets, let $e_r^{(j)}$ use the first $j$ items. A subset omitting item $j$ contributes to $e_r^{(j-1)}$. A subset including it has $r-1$ other items and contributes their product times $w_j$. Thus

\[e_r^{(j)}=e_r^{(j-1)}+w_j e_{r-1}^{(j-1)}.\]

The empty product gives $e_0^{(j)}=1$ for every $j$, and $e_r^{(j)}=0$ for $r>j$. Start with degree zero alone and update degrees from $j$ down to one when adding an item. For example, when processing item two, this order computes $e_2^{(2)}=w_2w_1$ before replacing $e_1^{(1)}=w_1$ with $w_1+w_2$. Updating degree one first would incorrectly let $w_2^2$ enter the coefficient for a pair of distinct items.

First implement the recursion on the log scale. From the book directory, load the numerical routines and define esf() to return the logarithms of the elementary symmetric functions.

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/factored_secant.R")
source("code/lib/irt.R")
source("code/lib/dogleg.R")
source("code/lib/result.R")
source("code/lib/differentiation.R")
source("code/lib/line_search.R")
source("code/lib/lbfgsb.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
esf <- function(log_weights) {
  J <- length(log_weights)
  loge <- c(0,rep(-Inf,J))
  for (j in seq_len(J)) for (r in j:1L)
    loge[r+1L] <- logsumexp(c(loge[r+1L],log_weights[j]+loge[r]))
  loge
}

The entry returned by esf() for degree $r$ is at R index $r+1$. The logarithm of a zero coefficient starts at $-\infty$, and logsumexp() combines the two contributions to each new coefficient.

For four items with difficulties $(-1,-0.3,0.4,0.9)$, there are six patterns with total two. Compare their summed weights with the exponential of the third entry returned by esf(). The simulated eight-item responses saved in YR will then supply the data for the conditional fit.

1
2
3
4
5
6
YR <- readRDS("data/source/ch10/IRT8-R.rds")
small_b <- c(-1, -.3, .4, .9)
all_patterns <- as.matrix(expand.grid(rep(list(0:1), 4)))
score_two <- all_patterns[rowSums(all_patterns) == 2, ]
print(c(recurrence = exp(esf(-small_b)[3]),
  enumeration = sum(exp(-drop(score_two %*% small_b)))))
1
2
 recurrence enumeration 
   8.322767    8.322767 

Both routes give 8.322767. For the pattern $(1,1,0,0)$, dividing its weight $\exp(1+0.3)$ by that sum gives a conditional probability of about 0.441. A separate check evaluates the six original response probabilities at $z=-2$ and divides each by their sum. Repeat that normalization at $z=1$ and compare corresponding entries.

1
2
3
4
5
6
conditional_at <- vapply(c(-2, 1), function(z) {
  joint <- apply(score_two, 1, function(y) prod(dbinom(y, 1, plogis(z - small_b))))
  joint / sum(joint)
}, numeric(6))
print(c(conditional_probability_difference = max(abs(conditional_at[, 1] -
  conditional_at[, 2]))))
1
2
conditional_probability_difference 
                      1.387779e-16 

The largest absolute difference is $1.39\times10^{-16}$. Ability can change the chance of obtaining total two, but the relative probabilities of the six ways to obtain it agree to rounding error.

Fitting the conditional likelihood

To fit the model, write $\beta_j=-b_j$ for item easiness and collect the easinesses of items two through $J$ in a vector $\eta$. The matrix $W$ implements the sum-zero contrast: its first row contains minus ones and the remaining rows form an identity matrix. Thus $\beta=W\eta=(-\sum_{k=1}^{J-1}\eta_k,\eta_1,\ldots,\eta_{J-1})^\top$ sums to zero. For $n_r$ examinees with total $r$ and $s_j$ correct responses to item $j$, summing the negative log conditional probabilities gives

\[-\ell_C(\eta)=\sum_{r=1}^J n_r\log\gamma_r-\sum_{j=1}^J s_j\beta_j, \qquad \gamma_r=e_r(e^{\beta_1},\ldots,e^{\beta_J}).\]

The score-zero term vanishes because $\gamma_0=1$. The following blocks form the definition of rasch_cml() for conditional maximum likelihood (CML) estimation. A row of Y can represent one examinee or a pattern repeated frequency times. Begin by computing the item totals and the numbers of examinees at each total score.

1
2
3
4
5
6
7
8
9
10
11
12
rasch_cml <- function(Y, frequency = rep(1,nrow(Y))) {
  Y <- as.matrix(Y)
  stopifnot(nrow(Y) > 0, ncol(Y) >= 2, all(Y %in% 0:1),
    length(frequency) == nrow(Y), all(is.finite(frequency)),
    all(frequency > 0), all(frequency == floor(frequency)))
  J <- ncol(Y)
  total <- rowSums(Y)
  informative <- total>0 & total<J
  # Item one balances the free easinesses of items two through J.
  W <- rbind(rep(-1, J - 1L), diag(1, J - 1L))
  item_totals <- colSums(Y * frequency)
  score_counts <- vapply(seq_len(J), function(r) sum(frequency[total == r]), 0.0)

The row sum total selects each pattern’s denominator. Weighted column sums supply the item totals in the numerator, and score_counts counts the frequency of each total from one through $J$.

The optimizer’s criterion uses a second version of the recursion, computing the coefficients on the original scale. In $\prod_j(1+e^{\beta_j}t)$, the coefficient of $t^r$ is $\gamma_r$. Multiplication by the next linear factor adds the previous coefficient vector to a copy shifted by one place and weighted by the new item.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
  criterion <- function(eta) {
    beta <- as.vector(W %*% eta)
    eps <- exp(beta)
    # Elementary symmetric functions gamma_0, gamma_1, ... of eps, built one item at a
    # time: column col holds the functions so far shifted down by col - 1 rows, times the
    # item's factor (1 or its eps), and the rows are summed.
    gamma <- c(1, eps[1])
    for (t in seq_len(J - 1L)) {
      factor <- c(1, eps[t + 1L])
      h <- length(factor)
      rows <- h + length(gamma) - 1L
      shifted <- sapply(seq_len(h), function(col) c(rep(0, col - 1L), gamma, rep(0, h - col)))
      gamma <- rowSums(shifted * matrix(rep(factor, each = rows), rows, h))
    }
    sum(score_counts %*% log(gamma[2:(J + 1L)])) - sum(item_totals %*% beta)
  }

The first column of shifted places a zero after the old coefficients. The second places a zero before them and is multiplied by the new weight. Their row sums give the next polynomial. The criterion takes logarithms after the multiplication. These multiplications can overflow even when a log-scale evaluation of the same conditional probability is finite. The stable recursion used for the returned person contributions does not make this separate optimization criterion stable.

Complete the function by minimizing this criterion, converting the fitted easinesses to difficulties, and evaluating the conditional log probabilities on the log scale.

1
2
3
4
5
6
7
8
9
10
11
  # Ignore warnings from nonfinite trial values during the line search.
  fit <- suppressWarnings(factored_secant_minimize(criterion, rep(0, J - 1L), maxit = 5000L))
  b <- -as.vector(W %*% fit$estimate)
  # Compute the conditional log probability of each observed pattern on the log scale.
  loge <- esf(-b)
  list(value = fit$minimum, gradient = fit$gradient, b = b, loge = loge, optimizer = fit,
    converged = fit$code %in% 1:2, informative = sum(frequency[informative]),
    extreme = sum(frequency[!informative]),
    loglik_contributions = rep(-drop(Y %*% b) - loge[total + 1L], frequency),
    constraint = "sum of item difficulties is zero")
}

Starting all $J-1$ free easinesses at zero, factored_secant_minimize() minimizes the scalar criterion by quasi-Newton steps with a finite-difference gradient and a limit of 5,000 iterations; Section 13.5 shows the routine. On return, negating $W\hat\eta$ gives the difficulties. For each person’s log probability the function uses the log-scale recursion at these fitted items and subtracts loge[total + 1L] from $-\sum_j y_j\hat b_j$.

Fit the eight difficulties in the saved response matrix YR using the conditional probabilities at each examinee’s own score.

1
2
3
4
fitR_cml <- rasch_cml(YR)
print(c(negative_conditional_loglik = fitR_cml$value, informative = fitR_cml$informative,
  extreme = fitR_cml$extreme, max_abs_gradient_component = max(abs(fitR_cml$gradient)),
  iterations = fitR_cml$optimizer$iterations))
1
2
3
4
negative_conditional_loglik                 informative                     extreme 
               2.140722e+03                7.570000e+02                4.300000e+01 
 max_abs_gradient_component                  iterations 
               1.106449e-03                1.700000e+01 

Of 800 examinees, 757 have informative totals between one and seven. The other 43 either missed every item or answered every item correctly. At either extreme, conditioning leaves just one pattern, with log probability zero. In particular, at total $J$, $\log\gamma_J=\sum_j\beta_j$ cancels the all-correct numerator exactly.

The negative conditional log likelihood is 2140.722 after 17 quasi-Newton iterations. The largest absolute component of its numerical gradient in the seven free easiness coordinates is about 0.0011. The optimizer’s returned code is one, indicating that its scaled gradient met the stopping tolerance.

A finite, unique conditional estimate also requires response comparisons that identify the item contrasts. Removing total-zero and total-$J$ patterns alone does not ensure this; if every pattern is extreme, the conditional criterion is constant and supplies no item information. The present routine does not check the general existence condition.

Why joint maximum likelihood can fail

Joint maximum likelihood would estimate a separate $z_i$ for each examinee along with the common difficulties. With $J$ fixed, adding an examinee adds another ability parameter supported by just $J$ answers.

The resulting incidental-parameter problem can be seen with two items. Let $\Delta=b_2-b_1$ and let $n_{10}$ and $n_{01}$ count the two patterns with total one, both represented. Their conditional odds are $\exp(\Delta)$, giving the conditional estimate $\log(n_{10}/n_{01})$.

For either pattern, the derivative with respect to $z_i$ is the observed total, one, minus the sum of the two success probabilities. It vanishes at $z_i=(b_1+b_2)/2$, where those probabilities sum to one. Write $q=\operatorname{logit}^{-1}(\Delta/2)$. At that ability the joint probabilities of the two patterns are $q^2$ and $(1-q)^2$. The all-correct and all-incorrect patterns approach probability one as their respective abilities tend to $+\infty$ and $-\infty$. Taking the supremum over the person parameters gives the profile likelihood for the contrast,

\[L_{\mathrm{prof}}(\Delta)\propto q^{2n_{10}}(1-q)^{2n_{01}},\qquad \hat q=\frac{n_{10}}{n_{10}+n_{01}},\qquad \widehat\Delta_{\mathrm{joint}}=2\log\frac{n_{10}}{n_{01}}.\]

The last equality follows by solving $q=\operatorname{logit}^{-1}(\Delta/2)$ for $\Delta$. As the number of independent score-one responses grows, their observed odds approach $\exp(\Delta)$. The joint estimate then approaches $2\Delta$, illustrating inconsistency for a nonzero contrast when the test length remains fixed.

Comparing conditional and marginal difficulties

Marginal maximum likelihood uses the probability of each complete pattern, including the extreme patterns, by averaging over a specified ability distribution. For the same 800 examinees, fix the item slopes at one and the normal ability mean at zero, and estimate the variance $v$ starting at one. The calculation uses 61 fixed nodes on $[-6,6]$ and normalized normal-density masses at the current $v$. The free-variance branch of irt_mml_em() updates the intercepts and variance together with the bounded double-dogleg optimizer. The separate marginal fit starts from item parameters computed from YR. The distinction between its continuous-density M step and normalized finite-grid E step is the one explained in Section 10.5.

1
2
3
4
5
6
startR <- irt_start(YR, "Rasch")
dataR <- irt_data(YR, startR)
fitR <- irt_mml_em(dataR, startR, variance = TRUE)
b_mml <- -vapply(fitR$items, `[[`, 0.0, "d")
print(c(latent_variance = fitR$constraints$latent_variance,
  cycles = fitR$optimizer$iterations))
1
2
latent_variance          cycles 
       1.006998       10.000000 

The fitted variance is 1.006998 after ten outer EM cycles. Each cycle includes an E step and a numerical M step. To compare item locations, convert marginal intercepts to difficulties and subtract their mean. This shift preserves every pairwise difference and puts the reported difficulties on the conditional fit’s sum-zero scale. This centering is only for reporting relative difficulties; it does not redefine the fitted zero-mean ability distribution. Preserving each response probability after shifting all difficulties would require the same shift of ability.

1
print(data.frame(item = 1:8, CML = fitR_cml$b, centered_MML = b_mml - mean(b_mml)))
1
2
3
4
5
6
7
8
9
  item        CML centered_MML
1    1 -1.5779725   -1.5775440
2    2 -1.1433944   -1.1452437
3    3 -0.6887564   -0.6898958
4    4 -0.2743380   -0.2746229
5    5  0.4375262    0.4387809
6    6  0.7041924    0.7056147
7    7  1.0365032    1.0374094
8    8  1.5062395    1.5055015

The largest absolute gap occurs at item two. Its conditional difficulty is $-1.1433944$, compared with a centered marginal difficulty of $-1.1452437$, a difference of 0.0018493. The two fits give close relative difficulties on these responses, although only the marginal fit estimates an ability variance. The criterion of the supplied rasch_cml() is adapted from the eRm package (code/NOTICE.md), which provides conditional maximum likelihood estimation for the Rasch model.

10.9 ML, MAP, and EAP ability estimates and test information

An examinee misses the first four items and answers the last four correctly. Where does that pattern place the examinee on the ability scale? Use the eight items from the fitted two-parameter logistic (2PL) model, with their discriminations and intercepts fixed. The unknown is now one person’s ability $z$. Let $O$ contain the indices of the answered items and let $P_{jk}(z)$ be the probability of category $k$ on item $j$. Conditional independence gives the likelihood of the observed pattern $y$ and its score with respect to ability. A prime denotes differentiation with respect to $z$.

\[L(z;y)=\prod_{j\in O}P_{j,y_j}(z),\qquad U(z;y)=\frac{d}{dz}\log L(z;y) =\sum_{j\in O}\frac{P'_{j,y_j}(z)}{P_{j,y_j}(z)}.\]

A positive score means that a small increase in ability raises the log likelihood. To measure how precisely this set of items distinguishes nearby abilities at a specified $z$, consider the expected squared score over the responses those items could produce. This expectation is the test information $I_O(z)$. Here score means the derivative of log likelihood with respect to ability, not the observed number correct. Test information is Fisher information for ability with the item parameters fixed.

For a dichotomous item with success probability $p=p_j(z)$, a correct response contributes $p^{\prime}/p$ to the score and an incorrect response contributes $-p^{\prime}/(1-p)$. Their weighted mean is zero. Weighting their squares by the same response probabilities gives the item information.

\[I_j(z)=p\left(\frac{p'}p\right)^2+(1-p)\left(\frac{-p'}{1-p}\right)^2 =\frac{(p')^2}{p(1-p)}.\]

In the 2PL, $p^{\prime}=a_jp(1-p)$, so $I_j(z)=a_j^2p(1-p)$. An item supplies its greatest information at its difficulty, where its two responses are equally probable. Conditional independence and the zero mean of each item score make the expected cross products between different items vanish. Test information therefore adds across the answered items. With several categories the same expectation gives

\[I_O(z)=\sum_{j\in O} I_j(z),\qquad I_j(z)=\sum_{k=0}^{K_j-1}\frac{[P'_{jk}(z)]^2}{P_{jk}(z)}.\]

The quotient applies at positive category probabilities. When a probability approaches zero at a trait limit, take the limit of the whole contribution along finite abilities for which the category probabilities are positive. For example, the 2PL expression $a_j^2p(1-p)$ tends to zero in either tail.

For any supplied abilities, irt_trait() selects the recorded category for the log likelihood and score. For information, it multiplies the squared derivative of each category’s log probability by that category’s probability and sums across the row. Missing answers contribute to none of the three quantities.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
for (file in c("result", "stability", "transforms", "quasi_newton", "irt"))
  source(paste0("code/lib/", file, ".R"), local = TRUE)
irt_trait <- function(y, items, z) {
  stopifnot(length(y) == length(items))
  for (j in seq_along(items)) stopifnot(is.na(y[j]) || y[j] %in% (0:(items[[j]]$K - 1L)))
  loglik <- score <- information <- rep(0, length(z))
  for (j in seq_along(items)) if (!is.na(y[j])) {
    e <- irt_prob(items[[j]], z)
    loglik <- loglik + e$logp[, y[j] + 1L]
    score <- score + e$d_log_probability_d_trait[, y[j] + 1L]
    information <- information + rowSums(e$probability * e$d_log_probability_d_trait^2)
  }
  list(loglik = loglik, score = score, information = information)
}

ML, MAP and EAP estimates

Maximum likelihood (ML) scoring searches for the peak of the pattern likelihood. For a person who answered at least one 2PL item, positive discriminations give

\[U(z;y)=\sum_{j\in O}a_j(y_j-p_j(z)),\qquad \ell''(z)=-\sum_{j\in O}a_j^2p_j(z)\{1-p_j(z)\}<0, \qquad \ell=\log L.\]

For a pattern with at least one correct and one incorrect answer, the score tends to the sum of the slopes of the correctly answered items on the left and to minus the sum of the slopes of the missed items on the right. It decreases strictly between these limits and crosses zero once, giving a unique finite ML estimate. With every answer incorrect, the likelihood increases toward one as $z\to-\infty$, and with every answer correct it increases toward one as $z\to+\infty$. In each case one is the supremum and every finite ability gives a smaller likelihood.

The function irt_trait_limits() finds each observed category’s log probability in both tails. For a nominal item, the categories with the smallest slope retain probability in the left tail and those with the largest slope retain probability in the right. Tied slopes at either extreme share the limiting probability in proportion to the exponentials of their intercepts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
irt_trait_limits <- function(item, response) {
  if (item$model == "nominal") {
    slope <- item$a[response + 1L]
    extreme <- function(value) {
      tied <- item$a == value
      if (slope == value) item$d[response + 1L] - logsumexp(item$d[tied]) else -Inf
    }
    lo <- min(item$a)
    hi <- max(item$a)
    return(c(left = extreme(lo), right = extreme(hi), increasing = slope == hi,
      decreasing = slope == lo))
  }
  if (item$model == "3PL") {
    if (response == 1) return(c(left = log(item$c), right = 0, increasing = TRUE,
      decreasing = FALSE))
    return(c(left = log1p(-item$c), right = -Inf, increasing = FALSE, decreasing = TRUE))
  }
  low <- response == 0
  high <- response == item$K - 1L
  c(left = if (low) 0 else -Inf, right = if (high) 0 else -Inf,
    increasing = high, decreasing = low)
}

With no observed responses, the empty product equals one at every ability. Every finite value maximizes the likelihood, but the data identify no location. A prior supplies information about ability while the item parameters remain fixed.

A standard normal prior gives the maximum a posteriori (MAP) estimate by maximizing $\ell(z)-z^2/2$. Its derivative is $U(z;y)-z$. Because the likelihood is bounded by one, its product with the normal density tends to zero in both tails. The posterior density is proportional to this product. Even an extreme 2PL pattern therefore has a finite posterior mode. The following blocks define theta_fit() for ML and MAP scoring.

1
2
3
4
5
6
7
8
9
10
11
theta_fit <- function(y, items, method = "ML", start = 0) {
  stopifnot(length(y) == length(items), method %in% c("ML", "MAP"), length(start) == 1L,
    is.finite(start))
  observed <- which(!is.na(y))
  for (j in observed) stopifnot(y[j] %in% (0:(items[[j]]$K - 1L)))
  if (!length(observed) && method == "ML") return(list(estimate = NA_real_,
    converged = FALSE,
    finite_maximum = TRUE, reason = "no_observed_responses", optimizer = NULL))

  fn <- function(z) -irt_trait(y, items, z)$loglik + if (method == "MAP") z^2 / 2 else 0
  gr <- function(z) -irt_trait(y, items, z)$score + if (method == "MAP") z else 0

The ML branch returns NA when no responses are observed. For an observed pattern, fn and gr supply the negative log likelihood and its derivative. The MAP branch adds the negative standard normal log prior and its derivative to these quantities.

The next block handles extreme ordered patterns directly and searches numerically for other ML patterns and for MAP estimates. Category order supplies a direction only for the ordered response models with positive slopes.

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
  # Category order implies a direction only for ordered response models with positive slopes.
  ordered <- all(vapply(items[observed], function(item)
    item$model %in% c("Rasch", "2PL", "3PL", "GRM", "GPCM") && all(item$a > 0), logical(1)))
  last <- vapply(items[observed], function(item) as.integer(item$K - 1L), integer(1))
  lowest <- all(y[observed] == 0)
  highest <- all(y[observed] == last)
  if (method == "ML" && ordered && (lowest || highest)) {
    estimate <- if (lowest) -Inf else Inf
    fit <- NULL
    converged <- FALSE
    reason <- "extreme_response_pattern"
  } else {
    binary <- all(vapply(items[observed],
      function(item) item$model %in% c("Rasch", "2PL"), logical(1)))
    fit <- if (binary) bfgs(fn, gr, start) else NULL
    if (binary && isTRUE(fit$converged) && abs(fit$par) < 20) {
      # Accept the finite solution within the numerical search range for Rasch or 2PL items.
      estimate <- fit$par
      converged <- fit$converged
      reason <- fit$reason
    } else {
      # Penalize trial values outside the numerical scoring range.
      criterion <- function(z) {
        if (abs(z) > 20) return(1e10)
        fn(z) - if (method == "MAP") dnorm(0, log = TRUE) else 0
      }
      fit <- nlm(criterion, start)
      estimate <- fit$estimate
      converged <- fit$code %in% 1:2
      reason <- paste0("nlm_code_", fit$code)
    }
  }

For the ordered response models with positive slopes, an ML pattern entirely in the first categories returns $-\infty$, and one entirely in the last categories returns $+\infty$. Nominal category labels do not trigger these shortcuts. For other patterns the function tries BFGS for Rasch or 2PL items and accepts a converged estimate inside $(-20,20)$. The fallback search penalizes trial values outside that interval. The limits $-20$ and 20 are numerical search limits, not bounds on the model’s ability scale.

How the numerical search ends is separate from whether the likelihood attains its supremum at a finite ability. Complete the function by comparing the observed categories’ tail limits with finite likelihood evaluations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  # Assess whether the ML likelihood reaches its supremum at a finite point.
  # The endpoint convention above is independent of this mathematical question.
  finite <- TRUE
  if (method == "ML") {
    limits <- vapply(observed, function(j) irt_trait_limits(items[[j]], y[j]), numeric(4))
    increasing <- all(limits[3, ] == 1)
    decreasing <- all(limits[4, ] == 1)
    if (increasing || decreasing) {
      finite <- increasing && decreasing
      if (!finite && ((increasing && estimate == Inf) ||
        (decreasing && estimate == -Inf)))
        reason <- "infinite_ML_supremum"
    } else {
      tail_loglik <- max(rowSums(limits[1:2, , drop = FALSE]))
      tolerance <- if (is.finite(tail_loglik)) 32 * .Machine$double.eps *
        max(1, abs(tail_loglik)) else 0
      at <- if (is.finite(estimate)) estimate else start
      finite <- if (-fn(at) > tail_loglik + tolerance) TRUE else NA
    }
  }
  list(estimate = estimate, converged = converged, finite_maximum = finite,
    reason = reason, optimizer = fit)
}

The fields converged and reason describe how scoring ended. For the two extreme 2PL patterns the function skips optimization, returns converged = FALSE, and records "infinite_ML_supremum". The separate finite_maximum field assesses finite attainment from the tail limits and finite evaluations.

Nominal categories illustrate why this assessment cannot rely on category labels. For a three-category item with slopes $(0,-1,1)$ and zero intercepts, the first-category probability is $1/(1+e^{-z}+e^z)$. It has its maximum at zero and tends to zero in both tails. Applying the first-category shortcut to this nominal item would therefore be incorrect. The function searches numerically and returns an estimate at zero to numerical precision, with finite_maximum true.

The expected a posteriori (EAP) estimate is instead the posterior mean of ability. At 121 equally spaced nodes from $-6$ to 6, let $w_q$ be the normalized normal-density weights. Multiplying each prior mass by the pattern likelihood and normalizing gives posterior masses $h_q$. These masses approximate the posterior mean and variance. The variance measures remaining uncertainty about this person’s ability given the observed answers, prior and fixed item parameters, in squared ability units. Its square root is the posterior standard deviation in ability units. These scoring functions use a standard normal prior by default. They do not automatically inherit an estimated calibration variance or empirical histogram: theta_eap() requires the corresponding rule explicitly, and theta_fit() fixes the MAP prior to standard normal.

\[h_q=\frac{w_qL(z_q;y)}{\sum_r w_rL(z_r;y)},\qquad \hat z_{\mathrm{EAP}}\approx\sum_q h_qz_q,\qquad V(z\mid y)\ \approx\ \sum_q h_q(z_q-\hat z_{\mathrm{EAP}})^2.\]
1
2
3
4
5
6
7
theta_eap <- function(y, items, rule = irt_rule(121L)) {
  ll <- irt_trait(y, items, rule$nodes)$loglik
  mass <- normalize_logweights(log(rule$weights) + ll)
  mean <- sum(mass * rule$nodes)
  list(estimate = mean, variance = sum(mass * (rule$nodes - mean)^2), posterior = mass,
    rule = rule)
}

In theta_eap(), rule$weights contains the $w_q$, ll contains $\log L(z_q;y)$, mass contains $h_q$, and estimate and variance are the two sums above.

Three response patterns

The saved Ramsay EM fit supplies calibrated items whose difficulties $-d_j/a_j$ increase from item one to item eight. Pattern 00001111 answers the four hardest items correctly. The calculation compares its ability estimates with those for all-incorrect and all-correct patterns.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
fit2 <- readRDS("data/derived/ch10/fits.rds")$dichotomous$Ramsay_EM
calibrated <- fit2$items
person_patterns <- rbind(all_incorrect = rep(0, 8), mixed = c(0, 0, 0, 0, 1, 1, 1, 1),
  all_correct = rep(1, 8))
person_results <- lapply(seq_len(nrow(person_patterns)), function(i) {
  y <- person_patterns[i, ]
  list(ML = theta_fit(y, calibrated, "ML"), MAP = theta_fit(y, calibrated, "MAP"),
    EAP = theta_eap(y, calibrated))
})
person_table <- do.call(rbind, lapply(person_results,
  function(f) data.frame(ML = f$ML$estimate,
  MAP = f$MAP$estimate, EAP = f$EAP$estimate, posterior_SD = sqrt(f$EAP$variance))))
rownames(person_table) <- rownames(person_patterns)
print(person_table)
1
2
3
4
                     ML        MAP        EAP posterior_SD
all_incorrect      -Inf -1.5326262 -1.5967026    0.7152216
mixed         0.3678745  0.2367331  0.2311555    0.6115336
all_correct         Inf  1.6264544  1.6962484    0.6837210

The mixed pattern gives an ML estimate of 0.36787. The prior pulls both the posterior mode (0.23673) and mean (0.23116) toward zero. With eight incorrect answers the mode is $-1.53263$ and the mean is $-1.59670$. With eight correct answers they are 1.62645 and 1.69625, respectively.

Evaluate the test information for these eight items at the prior mean. This expected information depends on the items and the specified ability, whereas the posterior distribution also depends on the observed answers.

1
2
print(c(test_information_at_zero =
  irt_trait(person_patterns[2, ], calibrated, 0)$information))
1
2
test_information_at_zero 
                1.754004 

All three patterns use the same items and hence have the same information of 1.754004 at zero. Figure 10.3 shows how the answers change the likelihood and, through the prior, the posterior density. Each likelihood is divided by its own maximum across the 501 displayed values from $-5$ to 5. The posterior density uses the quadrature approximation to the marginal probability of that pattern as its denominator.

1
2
3
4
5
6
7
8
9
10
11
12
posterior_grid <- seq(-5, 5, length.out = 501)
# Rows are abilities; columns are the three response patterns.
pattern_loglik <- vapply(seq_len(nrow(person_patterns)), function(i)
  irt_trait(person_patterns[i, ], calibrated, posterior_grid)$loglik,
  numeric(length(posterior_grid)))
relative_likelihood <- exp(sweep(pattern_loglik, 2, apply(pattern_loglik, 2, max), "-"))
posterior_density <- vapply(seq_len(nrow(person_patterns)), function(i) {
  normalizer <- logsumexp(log(person_results[[i]]$EAP$rule$weights) +
    irt_trait(person_patterns[i, ], calibrated,
      person_results[[i]]$EAP$rule$nodes)$loglik)
  exp(pattern_loglik[, i] + dnorm(posterior_grid, log = TRUE) - normalizer)
}, numeric(length(posterior_grid)))

The two extreme likelihoods rise toward opposite edges and the mixed likelihood peaks near zero. Three posterior curves have finite peaks and vertical lines at their means.

Figure 10.3. Relative likelihood (left) and posterior density (right) by ability for all incorrect (solid), mixed (dashed) and all correct (dotted) responses. The mixed likelihood peaks near 0.37. Vertical lines mark the three posterior means.

The posterior standard deviation (SD) measures spread in ability units given the actual answers and the normal prior. It is 0.61153 for the mixed pattern, 0.71522 for all incorrect and 0.68372 for all correct. Test information at zero averages over possible answers conditional on ability zero. Both calculations treat the fitted items as known. Repeating the calibration study would give different estimates of the item slopes and difficulties, introducing another source of uncertainty into the person scores. The mirt package provides ML, MAP and EAP ability scoring in R.

10.10 Checking parameter recovery and comparing marginal and conditional estimates

If two programs give different coefficients for an item, do they assign different probabilities to its responses? The mirt package writes the linear predictor for a dichotomous item as $a_1z+d$. On the ability scale used here, the discrimination is $a_1$, the difficulty is $-d/a_1$, and the lower asymptote of a 3PL item is the parameter g.

For a graded item, the logit for scoring at least $k$ is $a_1(z-t_k)$ at threshold $t_k$. The corresponding intercept is therefore $d_k=-a_1t_k$.

For the generalized partial credit model, scoring values run from zero to $K-1$ for $K$ categories. Reaching category $k$ accumulates the first $k$ steps, so its intercept relative to category zero is $d_k=-a_1\sum_{h=1}^k t_h$.

The reference function builds a one-factor model and obtains a parameter table with a row for each item coefficient and rows for the population parameters. From the book directory, load the numerical and item functions before defining it. In direct calls to mirt, the free-parameter flag is est and the convergence tolerance is TOL. These external argument names are used in code/checks/ch10_references.R.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
.libPaths(c(".R-library", .libPaths()))
for (file in c("result", "stability", "families", "logit", "differentiation",
  "line_search",
  "quasi_newton", "newton", "glm", "transforms", "search", "simulation", "em",
  "em_acceleration", "integration", "dogleg", "factored_secant"))
  source(paste0("code/lib/", file, ".R"))
source("code/lib/irt.R")
reference_item_calibration <- function(Y, type, prior = NULL, start = NULL, fixed = FALSE,
                                       positive_2pl = FALSE, tolerance = 1e-4) {
  itemtype <- switch(type, GRM = "graded", GPCM = "gpcm", nominal = "nominal", type)
  model <-
    if (is.null(prior)) 1 else mirt::mirt.model(sprintf(
    "F = 1-%d\nPRIOR = (1-%d, g, norm, %g, %g)",
    ncol(Y), ncol(Y), prior[1], prior[2]))
  values <- mirt::mirt(Y, model, itemtype = itemtype, pars = "values", verbose = FALSE)
  for (j in seq_len(ncol(Y))) {
    use <- values$item == colnames(Y)[j]
    if (!is.null(start)) {
      i <- start[[j]]
      if (type != "nominal") values$value[use & values$name == "a1"] <- i$a
      if (type %in% c("Rasch", "2PL", "3PL")) values$value[use & values$name == "d"] <-
        i$d
      if (type == "3PL") values$value[use & values$name == "g"] <- i$c
      if (type == "GRM") values$value[use & grepl("^d[1-9]", values$name)] <- -i$a *
        i$cuts
      if (type == "GPCM") values$value[use & grepl("^d[1-9]", values$name)] <- -i$a *
        cumsum(i$cuts)

For the nominal fit considered here, the first and last scoring values are fixed at zero and $K-1$, and the first category intercept is zero. The effective slope of category $k$ is the common multiplier $a_1$ times its scoring value. The last effective slope thus determines the multiplier when converting a fitted item into these coordinates. Matching by category label preserves which response receives each probability. In the separate comparison using category slopes directly, the multiplier is fixed at one and each nonreference slope is free.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
      if (type == "nominal") {
        # Preserve the category labels when converting the slopes.
        category <- seq_len(i$K) - 1L
        names_j <- ifelse(use, as.character(values$name), "")
        slope <- match("a1", names_j)
        scores <- match(paste0("ak", category), names_j)
        intercepts <- match(paste0("d", category), names_j)
        stopifnot(!anyNA(c(slope, scores, intercepts)))
        direct <- irt_direct_nominal_slopes(i)
        multiplier <- if (direct) 1 else i$a[i$K] / (i$K - 1L)
        values$value[slope] <- multiplier
        values$value[scores] <- i$a / multiplier
        values$value[intercepts] <- i$d
        if (direct) {
          values$est[slope] <- FALSE
          values$est[scores] <- category != 0L
        }
      }
    }
  }

The next block applies any requested slope bound or fixed-parameter setting and fits the reference model. The comparisons here use EM with 61 points from $-6$ to 6 and tolerance $10^{-4}$.

1
2
3
4
5
6
7
8
9
10
11
12
13
  if (positive_2pl) {
    stopifnot(type == "2PL")
    values$lbound[values$name == "a1"] <- 0
  }
  if (fixed) values$est <- FALSE
  # Passing a values table can impose bounds on the lower asymptotes.
  # Use it only for supplied values, fixed parameters or explicit bounds.
  ref <- if (!is.null(start) || fixed || positive_2pl)
    mirt::mirt(Y, model, itemtype = itemtype, pars = values, quadpts = 61L,
      TOL = tolerance, verbose = FALSE) else
    mirt::mirt(Y, model, itemtype = itemtype, quadpts = 61L, TOL = tolerance,
      verbose = FALSE)
  coefficients <- stats4::coef(ref, simplify = TRUE)$items

The routine passes the values table when the call requests starting values, fixed parameters or an explicit slope bound. Otherwise, start = NULL leaves mirt() to choose the starting values that the book’s formulas reproduce for these examples. The ordinary 2PL call leaves the optional slope bound unset. The 3PL modal fit also supplies a normal prior on the logit of each lower asymptote. Passing back a complete values table in that fit can impose finite bounds and change the optimizer used in the M step.

After fitting, the conversion runs in reverse. For example, two adjacent partial credit category intercepts differ by $-a_1t_k$, so dividing their negative difference by $a_1$ recovers the step. The returned list contains both the package fit and items on the scale used by irt_prob(). This permits direct comparison of category probabilities even when the two programs report different kinds of coefficients.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  items <- lapply(seq_len(nrow(coefficients)), function(j) {
    r <- coefficients[j, ]
    if (type %in% c("Rasch", "2PL", "3PL")) irt_item(type, a = r["a1"], d = r["d"],
      c = if (type == "3PL") r["g"] else 0) else
    if (type == "GRM") irt_item(type, a = r["a1"], cuts = -r[grep("^d[1-9]", names(r))] /
      r["a1"]) else
    if (type == "GPCM") irt_item(type, a = r["a1"], cuts = -diff(r[grep("^d[0-9]",
      names(r))]) / r["a1"]) else {
      item <- irt_item(type, a = r["a1"] * r[grep("^ak", names(r))],
        d = r[grep("^d[0-9]", names(r))])
      if (!is.null(start) && irt_direct_nominal_slopes(start[[j]]) && item$K > 2L)
        item$nominal_coordinates <- "category_slopes"
      item
    }
  })
  list(reference = ref, items = items, values = values,
    converged = mirt::extract.mirt(ref, "converged"), iterations = mirt::extract.mirt(ref,
      "iterations"))
}

The ability distribution also sets the units of a discrimination. Multiplying ability by a constant and dividing all slopes by that constant leaves the linear predictors unchanged. The 2PL calibration fixes the latent mean at zero and variance at one. The comparisons below therefore require both matching parameter meanings and matching ability scales.

Comparing weighted and expanded responses

The observed LSAT7 data distributed with mirt contain responses to five dichotomously scored items from the Law School Admissions Test. The dataset documentation describes the source. The first five columns, Item.1 through Item.5, record the responses, and the sixth, freq, counts examinees with that pattern. For example, the row $(0,0,0,0,1)$ represents 19 examinees. If its marginal probability is $P$, all 19 contribute $\log P$ apiece, or $19\log P$ in the grouped calculation. More generally, if pattern $r$ has frequency $n_r$ and marginal probability $P_r$, the negative log likelihood is $-\sum_r n_r\log P_r$. Replicating each row index according to its frequency reconstructs one row per person. Use those expanded observations for the starting values and the package fit. The book’s fit can use the shorter table with frequencies. Compare the two representations first at the book’s items, then compare both calibrations on the weighted data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
data("LSAT7", package = "mirt", envir = environment())
LSAT_Y <- as.matrix(LSAT7[, 1:5])
LSAT_frequency <- LSAT7[[6]]
LSAT_expanded <- LSAT_Y[rep(seq_len(nrow(LSAT_Y)), LSAT_frequency), , drop = FALSE]
lsat_start <- irt_start(LSAT_expanded, "2PL")
lsat_data <- irt_data(LSAT_Y, lsat_start, frequency = LSAT_frequency)
fit_lsat <- irt_mml_em(lsat_data, lsat_start)
ref_lsat <- reference_item_calibration(LSAT_expanded, "2PL")
print(c(pattern_rows = nrow(LSAT7), people = sum(LSAT_frequency),
  weighted_expanded_gap = irt_estep(lsat_data, fit_lsat$items, irt_rule(121L))$value -
    irt_estep(irt_data(LSAT_expanded, lsat_start), fit_lsat$items, irt_rule(121L))$value,
  LSAT_common_rule_difference_in_negative_loglik = irt_estep(lsat_data, fit_lsat$items,
    irt_rule(121L))$value -
    irt_estep(lsat_data, ref_lsat$items, irt_rule(121L))$value))
1
2
3
4
                                  pattern_rows                                         people 
                                  3.200000e+01                                   1.000000e+03 
                         weighted_expanded_gap LSAT_common_rule_difference_in_negative_loglik 
                                  0.000000e+00                                   3.637979e-12 

The 32 rows represent 1,000 examinees. On the 121-point rule the weighted and expanded negative log likelihoods differ by zero at the same items. Substituting the package items into the weighted calculation gives a book-minus-package difference of about $3.64\times10^{-12}$. The first subtraction checks the representation of the data. The second compares two fitted sets of items.

Comparing six item calibrations

The book’s EM accelerates its cycles by a step adapted from mirt and reproduces the package’s starting values (code/NOTICE.md). Agreement in the six calibrations below, including the cycle counts, checks the translation rather than giving an independent fit (Section E.3).

For the six calibration rows, load the simulated response matrices and retrieve the book’s item estimates. The graded, partial credit and nominal fits each use their own matrix of six four-category items. The 3PL comparison uses the 16-item calibration. The five calls without a lower-asymptote prior take the matrix and model name as arguments.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
saved <- readRDS("data/derived/ch10/fits.rds")
Y2 <- readRDS("data/source/ch10/IRT8-2.rds")
YR <- readRDS("data/source/ch10/IRT8-R.rds")
YG <- readRDS("data/source/ch10/ORD6-G.rds")
YP <- readRDS("data/source/ch10/ORD6-P.rds")
YN <- readRDS("data/source/ch10/ORD6-N.rds")
Y3 <- readRDS("data/source/ch10/IRT16-3.rds")
fit2 <- saved$dichotomous$Ramsay_EM
fitR <- saved$MML_Rasch
polytomous_fits <- saved$polytomous
fit3_modal <- saved$modal_3PL
start3 <- irt_start(Y3, "3PL")
data3 <- irt_data(Y3, start3)
model_Y <- list(`2PL` = Y2, Rasch = YR, GRM = YG, GPCM = YP, nominal = YN)
model_fit <- c(list(`2PL` = fit2, Rasch = fitR), polytomous_fits)
reference_results <- lapply(names(model_Y),
  function(type) reference_item_calibration(model_Y[[type]], type))
names(reference_results) <- names(model_Y)

In the marginal Rasch calibration, both implementations fix the discrimination of every item at one, retain a zero mean and estimate the variance of ability. The estimated variance describes the spread of examinees in those units. Two comparisons follow from this choice. One compares the estimated variances directly. The other evaluates the returned items with the same standard normal weights, so a difference in that calculation comes from the items. This shared-weight evaluation is not the marginal likelihood of each fitted Rasch population when its estimated variance differs from one.

Evaluate both sets of items by irt_estep() on 121 common nodes. Its value is the negative log marginal likelihood, including pattern frequencies. Subtract the value at the reference items from the value at the book items. A positive difference means that the reference items assign a larger likelihood to the observations under this rule. A second calculation examines each item separately. At 81 abilities from $-4$ to 4 in increments of 0.1, compare the conditional probabilities of every category and take the largest absolute difference across items, categories and abilities. The column named max_probability_error records this difference between implementations, not error relative to the unknown population probabilities.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
reference_table <- do.call(rbind, lapply(names(model_Y), function(type) {
  book <- model_fit[[type]]
  ref <- reference_results[[type]]
  d <- irt_data(model_Y[[type]], book$items)
  probability_error <- max(vapply(seq_along(book$items), function(j)
    max(abs(irt_prob(book$items[[j]], seq(-4, 4, by = .1))$probability -
      irt_prob(ref$items[[j]], seq(-4, 4, by = .1))$probability)), 0.0))
  data.frame(model = type, book_converged = book$converged,
    reference_converged = ref$converged,
    book_iterations = book$optimizer$iterations, reference_iterations = ref$iterations,
    common_121_nll_gap = irt_estep(d, book$items, irt_rule(121L))$value -
      irt_estep(d, ref$items, irt_rule(121L))$value,
        max_probability_error = probability_error)
}))

For the sixth row, the normal prior on the logit of each lower asymptote has mean $-1.5$ and standard deviation 3. It affects the calibration. The common evaluation uses only the response likelihood at the two resulting sets of estimates.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ref3 <- reference_item_calibration(Y3, "3PL", prior = c(-1.5, 3))
reference_results[["3PL_MAP"]] <- ref3
common3 <- irt_rule(121L)
reference_table <- rbind(reference_table, data.frame(model = "3PL_MAP",
  book_converged = fit3_modal$converged,
  reference_converged = ref3$converged, book_iterations = fit3_modal$optimizer$iterations,
  reference_iterations = ref3$iterations,
  common_121_nll_gap = irt_estep(data3, fit3_modal$items, common3)$value -
    irt_estep(data3, ref3$items, common3)$value,
  max_probability_error = max(vapply(1:16, function(j) max(abs(
    irt_prob(fit3_modal$items[[j]], seq(-4, 4, by = .1))$probability -
      irt_prob(ref3$items[[j]], seq(-4, 4, by = .1))$probability)), 0.0))))
names(reference_table)[6] <- "common_rule_difference_in_negative_loglik"
print(reference_table, row.names = FALSE)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
   model book_converged reference_converged book_iterations reference_iterations
     2PL           TRUE                TRUE              16                   16
   Rasch           TRUE                TRUE              10                   10
     GRM           TRUE                TRUE              13                   13
    GPCM           TRUE                TRUE              31                   31
 nominal           TRUE                TRUE              22                   22
 3PL_MAP           TRUE                TRUE             133                  133
 common_rule_difference_in_negative_loglik max_probability_error
                              1.818989e-12          3.389289e-12
                             -8.503775e-11          4.212691e-11
                             -8.185452e-12          1.627365e-12
                              9.094947e-13          2.775558e-15
                              2.728484e-12          8.848478e-14
                              0.000000e+00          4.884981e-15

The two implementations report convergence after the same number of outer cycles for each model, from 10 for the Rasch fit to 133 for the 3PL modal fit. Read the second group of columns in the same row order as the first. The largest absolute difference in negative log likelihood occurs in the Rasch row, about $8.50\times10^{-11}$, and its maximum category probability difference is about $4.21\times10^{-11}$. The Rasch likelihood comparison uses standard normal weights for both item vectors. Compare the fitted variances on their own scale.

1
2
print(c(Rasch_latent_variance_gap = fitR$constraints$latent_variance -
  mirt::coef(reference_results$Rasch$reference, simplify = TRUE)$cov[1, 1]))
1
2
Rasch_latent_variance_gap 
            -5.976375e-11 

The book’s variance estimate is smaller than the package estimate by about $5.98\times10^{-11}$.

Comparing scores at fixed item parameters

For person scoring, the item parameters can remain fixed. Supply the eight fitted 2PL items with start = calibrated and fixed = TRUE. Give mirt::fscores() the same three patterns as the book’s scoring functions and compare the estimates in units of ability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
calibrated <- fit2$items
person_results <- saved$person
person_patterns <- rbind(all_incorrect = rep(0, 8), mixed = c(0, 0, 0, 0, 1, 1, 1, 1),
  all_correct = rep(1, 8))
person_table <- do.call(rbind, lapply(person_results,
  function(f) data.frame(ML = f$ML$estimate,
  MAP = f$MAP$estimate, EAP = f$EAP$estimate, posterior_SD = sqrt(f$EAP$variance))))
rownames(person_table) <- rownames(person_patterns)
fixed_reference <- reference_item_calibration(Y2, "2PL", start = calibrated, fixed = TRUE)
ref_eap <- mirt::fscores(fixed_reference$reference, method = "EAP",
  response.pattern = person_patterns,
  full.scores.SE = TRUE)
ref_map <- mirt::fscores(fixed_reference$reference, method = "MAP",
  response.pattern = person_patterns,
  start = matrix(0, 3, 1), full.scores.SE = FALSE)
print(c(EAP_max_difference = max(abs(person_table$EAP - ref_eap[, "F1"])),
  posterior_SD_max_difference = max(abs(person_table$posterior_SD - ref_eap[, "SE_F1"])),
  MAP_max_difference = max(abs(person_table$MAP - ref_map[, "F1"]))))
1
2
         EAP_max_difference posterior_SD_max_difference          MAP_max_difference 
               4.440892e-16                1.110223e-16                8.261161e-07 

The largest absolute differences across these three patterns are approximately $4.44\times10^{-16}$ for posterior means, $1.11\times10^{-16}$ for posterior standard deviations and $8.26\times10^{-7}$ for posterior modes. This agreement concerns the three patterns at the fixed calibration and stated scoring settings. In the six preceding rows the item parameters themselves were estimated.

Comparing conditional Rasch estimates

A comparison of Rasch conditional estimates needs the same conditioning and the same location constraint. The package eRm fits the responses in YR conditional on each examinee’s total score. With sum0 = TRUE its coefficient vector betapar gives item easinesses on a sum-zero scale. Negate those coefficients to obtain difficulties and subtract their mean to align their location with the book’s conditional estimates. The call omits standard errors because the comparison uses the fitted difficulties. The book’s conditional criterion computes the elementary symmetric functions by the summation recursion of eRm (code/NOTICE.md), so this comparison checks that adaptation (Section E.3).

1
2
3
4
5
fitR_cml <- saved$CML
ref_cml <- eRm::RM(YR, sum0 = TRUE, se = FALSE)
ref_cml_b <- -ref_cml$betapar
ref_cml_b <- ref_cml_b - mean(ref_cml_b)
print(c(CML_difficulty_max_difference = max(abs(fitR_cml$b - ref_cml_b))))
1
2
CML_difficulty_max_difference 
                 4.633371e-09 

The largest absolute difference over the eight difficulties is $4.63\times10^{-9}$ between two conditional estimates. Comparing a conditional estimate to a marginal one asks a different question even on the same response matrix. Conditioning removes ability through the observed total, whereas the marginal likelihood averages the response probabilities over an ability distribution.

Parameter recovery in repeated 2PL samples

Agreement on a given sample leaves open how well a calibration recovers the items that generated the responses. In the regular 2PL study, each of 200 independent replications draws 800 standard normal abilities and responses to eight items with known discriminations and difficulties. Each fit starts from its own response data. The saved study records will supply the replications; first define how the uncertainty calculation for each fitted item is obtained.

To construct an interval, evaluate the observed information at the estimated item parameters by numerically differentiating the gradient of the negative marginal log likelihood. For an identifiable 2PL model with finite estimates, strictly positive discriminations, nonsingular information and a sufficiently accurate likelihood maximization, the inverse observed information gives a large-sample approximation to the estimator’s sampling covariance. This also assumes adequate numerical integration, a smooth likelihood and independent examinees sampled from the specified population model. This calculation concerns unpenalized item estimation with a fixed ability distribution; its item-only Hessian does not account for additional estimated distribution parameters, and adding a log prior changes the differentiated criterion.

1
2
3
4
5
6
7
8
9
10
irt_calibration_se <- function(data, fit) {
  objective <- irt_objective(data, fit$items, fit$rule, fit$priors)
  u <- irt_pack(fit$items)
  H <- num_hess(objective$fn, u, gr = objective$gr)$hessian
  R <- tryCatch(chol(H), error = function(e)NULL)
  if (is.null(R)) return(list(valid = FALSE, reason = "nonpositive_observed_information",
    information = H))
  V <- chol2inv(R)
  rows <- list()
  offset <- 0L

The Cholesky factorization checks positive definiteness of the observed information. A successful factorization alone checks neither stationarity nor adequate numerical accuracy.

For item $j$, extract the two rows and columns for its slope $a$ and intercept $d$ from this inverse. Write the resulting block as $V_j$. The standard error of $\log a$ is $\sqrt{V_{j,11}}/a$ by the delta method. Form the approximate 95 percent Wald interval on that scale and exponentiate both endpoints to retain positive limits. For difficulty $b=-d/a$, the derivatives with respect to $a$ and $d$ are $d/a^2=-b/a$ and $-1/a$. With this row vector $D_b$, the estimated sampling variance of the difficulty estimate is $D_bV_jD_b^\top$, which includes the covariance between the slope and intercept estimates. Its square root is a standard error in ability units. It describes how the estimated item difficulty varies over repeated samples of examinees, rather than the spread of abilities within the population or one person’s posterior uncertainty.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  for (j in seq_along(fit$items)) {
    item <- fit$items[[j]]
    p <- length(irt_item_pack(item))
    if (item$model == "2PL") {
      b <- -item$d / item$a
      vj <- V[offset + 1:2, offset + 1:2]
      # The packed item coordinates are (slope, intercept).
      se_log_a <- sqrt(vj[1, 1]) / item$a
      Db <- c(-b / item$a, -1 / item$a)
      se_b <- sqrt(drop(Db %*% vj %*% Db))
      rows[[j]] <- data.frame(item = j, a = item$a, b = b, se_log_a = se_log_a,
        se_b = se_b,
        a_lower = exp(log(item$a) - qnorm(.975) * se_log_a), a_upper = exp(log(item$a) +
          qnorm(.975) * se_log_a),
        b_lower = b - qnorm(.975) * se_b, b_upper = b + qnorm(.975) * se_b)
    }
    offset <- offset + p
  }
  list(valid = TRUE, reason = "positive_observed_information", information = H,
    covariance = V,
    items = do.call(rbind, rows))
}

Load the regular 2PL and weak 3PL study records; the first table summarizes the regular study. Retain a replication when its EM fit met the stopping rule and its observed information admitted the factorization.

For each item, subtract its generating value from its average estimate to obtain the estimated bias. If $n$ fits qualify and their estimates for this item have sample standard deviation $s$, the Monte Carlo standard error of the estimated bias is $s/\sqrt n$. Estimated coverage is the fraction of eligible intervals containing the generating value. For coverage $\hat p$ based on $n$ independent replications, the estimated Monte Carlo standard error is $\sqrt{\hat p(1-\hat p)/n}$. If some runs fail these checks, bias and coverage computed this way describe the retained runs; they are not automatically summaries over all assigned replications.

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
study_regular <- readRDS("data/derived/ch10/study-regular.rds")
study_weak <- readRDS("data/derived/ch10/study-weak3PL.rds")
slopes <- c(.7, .9, 1, 1.1, 1.2, .8, 1.3, 1)
difficulty <- seq(-1.5, 1.5, length.out = 8)
regular_ok <- vapply(study_regular$results, function(r)
  isTRUE(r$fit$converged) && isTRUE(r$uncertainty$valid), TRUE)
regular_results <- study_regular$results[regular_ok]
recovery_table <- do.call(rbind, lapply(1:8, function(j) {
  a <- vapply(regular_results, function(r) r$uncertainty$items$a[j], 0.0)
  b <- vapply(regular_results, function(r) r$uncertainty$items$b[j], 0.0)
  ta <- slopes[j]
  tb <- difficulty[j]
  ca <- vapply(regular_results, function(r) with(r$uncertainty$items[j, ], a_lower <=
    ta && ta <= a_upper), TRUE)
  cb <- vapply(regular_results, function(r) with(r$uncertainty$items[j, ], b_lower <=
    tb && tb <= b_upper), TRUE)
  data.frame(item = j, n = length(a), bias_a = mean(a) - ta, MCSE_bias_a = sd(a) /
    sqrt(length(a)),
    RMSE_a = sqrt(mean((a - ta)^2)), coverage_a = mean(ca),
      MCSE_coverage_a = sqrt(mean(ca) * (1 - mean(ca)) / length(a)),
    bias_b = mean(b) - tb, MCSE_bias_b = sd(b) / sqrt(length(b)), RMSE_b = sqrt(mean((b -
      tb)^2)),
    coverage_b = mean(cb), MCSE_coverage_b = sqrt(mean(cb) * (1 - mean(cb)) / length(b)))
}))
print(recovery_table[, c("item", "n", "bias_a", "MCSE_bias_a", "coverage_a", "bias_b",
  "MCSE_bias_b", "coverage_b")], row.names = FALSE)
1
2
3
4
5
6
7
8
9
 item   n      bias_a MCSE_bias_a coverage_a       bias_b MCSE_bias_b coverage_b
    1 200 0.005597498 0.008954298      0.975 -0.038752205 0.020539302      0.960
    2 200 0.002578315 0.009845486      0.975 -0.018830717 0.011930218      0.965
    3 200 0.016755836 0.010899217      0.950 -0.001161747 0.008031340      0.955
    4 200 0.009069866 0.010852812      0.975 -0.007702485 0.006445340      0.955
    5 200 0.002293464 0.011438073      0.960  0.003828965 0.005538842      0.950
    6 200 0.005601525 0.009214939      0.960  0.019345986 0.010134910      0.970
    7 200 0.043358785 0.013358527      0.965 -0.005719337 0.008072471      0.955
    8 200 0.005442876 0.012087235      0.940  0.024440682 0.017585142      0.910

All 200 replications contribute to every row. For item one the estimated discrimination bias is 0.00560 with Monte Carlo standard error 0.00895. Of its 200 intervals, 195 cover the generating discrimination and 192 cover the generating difficulty, giving 0.975 and 0.960. Item seven has the largest estimated discrimination bias, 0.04336, about 3.2 times its Monte Carlo standard error of 0.01336. A separate check changes the integration rule at fixed estimates. Its log likelihood differences measure numerical sensitivity, while coverage Monte Carlo standard errors measure repeated-sample uncertainty in a proportion.

1
2
3
4
print(c(regular_failures = sum(!regular_ok),
  max_coverage_MCSE = max(recovery_table$MCSE_coverage_a, recovery_table$MCSE_coverage_b),
  max_absolute_61_to_121_nll_change = max(abs(vapply(study_regular$results, `[[`, 0.0,
    "refinement")))))
1
2
                 regular_failures                 max_coverage_MCSE max_absolute_61_to_121_nll_change 
                     0.000000e+00                      2.023611e-02                      8.736015e-08 

The largest coverage standard error is 0.02024. Changing from 61 to 121 nodes at the fitted parameters changes the negative log likelihood by at most $8.74\times10^{-8}$ in these replications.

Paired ML and MAP fits in the weak 3PL study

The weak 3PL study returns to the weakly determined lower asymptotes. Each of its 200 samples contains 800 examinees and eight items with a generating lower asymptote of 0.15. ML and MAP fit the same response matrix within each replication. Average the eight estimated lower asymptotes within a fit to obtain one observation per sample. For each method, use the fits that met its stopping rule to estimate the mean and its Monte Carlo standard error. The counts of near-zero lower asymptotes, steep slopes and changes under quadrature refinement use all 200 returned fits per method. The first two counts record a sample once if any of its eight items crosses the threshold. The cutoffs 0.001 for the lower asymptote and 10 for discrimination are chosen descriptive thresholds. They are not tests for a boundary solution or formal definitions of weak identification.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
weak_table <- do.call(rbind, lapply(c("ML", "MAP"), function(method) {
  fits <- lapply(study_weak$results, function(r) if (method == "ML") r$fit else r$modal)
  ok <- vapply(fits, function(f) isTRUE(f$converged), TRUE)
  near_zero <- vapply(fits, function(f) any(vapply(f$items, `[[`, 0.0, "c") < .001), TRUE)
  steep <- vapply(fits, function(f) any(vapply(f$items, `[[`, 0.0, "a") > 10), TRUE)
  refinement <- vapply(study_weak$results, function(r) if (method ==
    "ML") r$refinement else r$modal_refinement, 0.0)
  mean_c <- vapply(fits[ok], function(f) mean(vapply(f$items, `[[`, 0.0, "c")), 0.0)
  data.frame(method = method, runs = length(fits), converged = sum(ok),
    c_below_001 = sum(near_zero),
    a_above_10 = sum(steep), node_change_above_001 = sum(abs(refinement) > .001),
    mean_c = mean(mean_c), bias_mean_c = mean(mean_c) - .15, MCSE_mean_c = sd(mean_c) /
      sqrt(length(mean_c)))
}))
print(weak_table, row.names = FALSE)
1
2
3
 method runs converged c_below_001 a_above_10 node_change_above_001    mean_c bias_mean_c MCSE_mean_c
     ML  200        61         119          1                     0 0.1580625 0.008062494 0.006708054
    MAP  200       150           0          1                     0 0.1791976 0.029197629 0.003265847

ML met the parameter-change rule on 61 samples and MAP on 150. The other 139 ML and 50 MAP fits reached the limit of 500 cycles. Across all 200 fits, at least one lower asymptote fell below 0.001 in 119 ML samples and zero MAP samples. One fit for each method had a slope above 10. For both methods, changing the rule at any returned fit changed the negative response log likelihood by at most 0.001. The method-specific mean lower asymptotes, 0.15806 for ML and 0.17920 for MAP, summarize different subsets. Restricting both means to samples where both methods met their rule ensures that both methods are compared on the same response matrices.

1
2
3
4
5
6
7
8
9
weak_results <- readRDS("data/derived/ch10/study-weak3PL.rds")$results
both <- vapply(weak_results, function(r)
  isTRUE(r$fit$converged) && isTRUE(r$modal$converged), TRUE)
mean_c <- function(fit) mean(vapply(fit$items, `[[`, 0.0, "c"))
print(sapply(c(ML = "fit", MAP = "modal"), function(k) {
  x <- vapply(weak_results[both], function(r) mean_c(r[[k]]), 0.0)
  c(samples = sum(both), mean_c = mean(x), bias_mean_c = mean(x) - .15,
    MCSE_mean_c = sd(x) / sqrt(length(x)))
}))
1
2
3
4
5
                      ML          MAP
samples     59.000000000 59.000000000
mean_c       0.157525604  0.182858222
bias_mean_c  0.007525604  0.032858222
MCSE_mean_c  0.006846418  0.005261946

On the 59 shared samples, the mean errors relative to 0.15 are 0.007526 for ML and 0.032858 for MAP. The MAP prior centers the logit at $-1.5$, corresponding to a lower asymptote of about 0.182. The two Monte Carlo standard errors, 0.006846 and 0.005262, describe the individual mean errors on these same samples.

For these 59 samples, the mean lower asymptote is about 0.02533 higher under MAP, from $0.032858-0.007526$. The standard error of this paired difference is the sample standard deviation of the 59 within-sample MAP minus ML differences divided by $\sqrt{59}$. These summaries describe the jointly retained samples, rather than performance over all 200 assigned samples.

To identify the excluded fits, index the ML convergence indicator. The following sample numbers record the ML fits that reached the cycle limit.

1
print(which(!vapply(weak_results, function(r) isTRUE(r$fit$converged), TRUE)))
1
2
3
4
5
6
7
8
  [1]   1   2   4   5   6   8   9  10  11  12  13  14  15  16  17  18  19  20
 [19]  21  22  23  24  25  26  27  29  30  31  32  35  37  38  40  41  43  44
 [37]  45  47  48  49  52  53  55  56  58  59  60  61  63  64  65  66  67  69
 [55]  70  71  72  73  74  75  76  78  80  82  83  84  88  89  90  91  92  93
 [73]  94  96  98  99 103 104 107 108 109 110 111 113 114 116 117 119 122 123
 [91] 127 128 129 130 132 133 134 135 136 137 139 142 143 144 145 146 148 149
[109] 152 153 155 156 158 159 162 163 165 166 167 168 169 170 172 173 175 176
[127] 177 181 182 183 184 187 189 190 192 194 195 197 200

These 139 sample numbers identify the ML fits excluded by the stopping rule and allow their stored results to be inspected individually.

An ordinal application: attitudes toward science and technology

The recovery studies use known generating items to assess estimation. An observed attitude scale raises a different question: how do its response categories distinguish people at different positions on a proposed trait? The Science extract distributed with mirt contains four items answered by 392 respondents. It comes from the British sample of the 1992 Eurobarometer survey. The items concern everyday benefits (Comfort), the interest of work (Work), opportunities for future generations (Future) and the balance of benefits and harm (Benefit). All four are positively worded. The original codes increase from strong disagreement to strong agreement. The dataset documentation identifies this four-item extract; the original package documentation describes the questions and response scale.

Use scores 0 through 3 in the functions developed above. This changes the category labels by subtracting one; it does not combine responses or treat the distances between categories as equal. The example analyzes complete response vectors and reports their number explicitly. From the book directory, source("code/examples/ch10-application.R") runs this application. Its setup loads the chapter functions; inputs and fitted objects are saved under data/source/ch10 and data/derived/ch10.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# 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(10L)
record_check <- application$record_check
record_review <- application$record_review

data("Science", package = "mirt", envir = environment())
science_names <- c("Comfort", "Work", "Future", "Benefit")
science_raw <- as.matrix(Science[, science_names])
stopifnot(all(is.na(science_raw) | science_raw %in% 1:4))
science_rows <- which(complete.cases(science_raw))
science_Y <- science_raw[science_rows, , drop = FALSE] - 1L
science_counts <- t(vapply(seq_len(ncol(science_Y)), function(j)
  tabulate(science_Y[, j] + 1L, 4L), integer(4)))
dimnames(science_counts) <- list(science_names, paste0("category", 0:3))
print(c(available = nrow(science_raw), analyzed = nrow(science_Y),
        excluded = nrow(science_raw) - nrow(science_Y)))
print(science_counts)
saveRDS(list(raw = science_raw, rows = science_rows, Y = science_Y),
        file.path("data/source/ch10", "ch10-science.rds"))
1
2
3
4
5
6
7
available  analyzed  excluded 
      392       392         0 
        category0 category1 category2 category3
Comfort         5        32       266        89
Work           33        98       206        55
Future         14        72       210        96
Benefit        21       100       193        78

Each row of science_Y represents a respondent and each column an item. The category counts show whether a threshold is informed by many responses or by a small tail of the sample. A rarely selected category can make a threshold imprecise even when the fitted category probabilities appear smooth.

All 392 respondents have complete answers on these four items. Only five strongly disagree with Comfort, whereas 266 agree and 89 strongly agree. This sparse response category should be considered when interpreting the first threshold.

Let $z_i\sim N(0,1)$ describe respondent $i$’s favorable attitude toward science and technology. Conditional on this trait, assume the four answers are independent. For item $j$ and boundary $k=1,2,3$, specify the graded response model

\[\Pr(Y_{ij}\geq k\mid z_i) =\operatorname{logit}^{-1}\{a_j(z_i-b_{jk})\}, \qquad a_j>0,\quad b_{j1}<b_{j2}<b_{j3}.\]

The positive slopes orient larger trait values toward greater agreement. The latent mean and variance fix its location and unit. A threshold $b_{jk}$ is the trait value at which the probability of reaching category $k$ or higher is one half. Each slope is a change in the cumulative log odds per trait standard deviation. Set the cumulative probabilities at boundaries 0 and 4 to one and zero, respectively; subtract adjacent cumulative probabilities to obtain the four category probabilities. This gives sixteen free item parameters: four slopes and twelve thresholds.

Fit the marginal likelihood by EM on 61 equally spaced nodes. Refine that result by direct maximization, then use 121 nodes to examine sensitivity to the integration rule. The latent distribution remains standard normal in all three fits.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
science_start <- irt_start(science_Y, "GRM", K = rep(4L, 4L))
science_data <- irt_data(science_Y, science_start)
science_em <- irt_mml_em(science_data, science_start, irt_rule(61L),
                         control = list(tol = 1e-5, maxit = 1500L))
science_61 <- irt_mml_direct(science_data, science_em$items, irt_rule(61L),
                            control = list(rel_tol = 1e-10, maxit = 3000L))
science_121 <- irt_mml_direct(science_data, science_61$items, irt_rule(121L),
                             control = list(rel_tol = 1e-10, maxit = 3000L))
science_fits <- list(EM61 = science_em, direct61 = science_61,
                     direct121 = science_121)
science_comparison <- do.call(rbind, lapply(names(science_fits), function(name) {
  fit <- science_fits[[name]]
  objective <- irt_objective(science_data, fit$items, irt_rule(121L))
  data.frame(method = name, converged = fit$converged, reason = fit$reason,
    loglik_121 = -objective$fn(irt_pack(fit$items)),
    max_abs_score_121 = max(abs(objective$gr(irt_pack(fit$items)))))
}))
science_parameters <- do.call(rbind, lapply(seq_along(science_names), function(j) {
  item <- science_121$items[[j]]
  data.frame(item = science_names[j], slope = item$a,
             threshold1 = item$cuts[1], threshold2 = item$cuts[2], threshold3 = item$cuts[3])
}))
print(science_comparison, row.names = FALSE)
print(science_parameters, row.names = FALSE)
1
2
3
4
5
6
7
8
9
    method converged                 reason loglik_121 max_abs_score_121
      EM61      TRUE small_parameter_change  -1608.869       0.001077320
  direct61      TRUE              converged  -1608.869       0.001106998
 direct121      TRUE              converged  -1608.869       0.001765811
    item    slope threshold1 threshold2 threshold3
 Comfort 1.040733  -4.672511 -2.5359307  1.4081456
    Work 1.225859  -2.385256 -0.7351197  1.8488550
  Future 2.299991  -2.280119 -0.9644577  0.8553044
 Benefit 1.093893  -3.059684 -0.9063405  1.5427382

The items field carries the fitted item objects from one calculation to the next. In each object, a is the slope and cuts contains the three thresholds in trait units. The comparison evaluates every returned model on the same 121-node rule. Its score column measures proximity to a stationary point of that common criterion; a stopping flag alone does not provide this information. The parameter table should be read together with this calculation before interpreting differences between items.

All three procedures return a log likelihood of -1608.869 at the displayed precision. The final maximum absolute score is about 0.00177. Future has the largest slope, about 2.30, compared with values from 1.04 to 1.23 for the other items. Its third threshold is about 0.855: at this trait value the model assigns probability one half to strong agreement. The corresponding threshold for Work is about 1.849. These locations describe endorsement on the common latent scale, while the slopes describe how rapidly endorsement changes along that scale. The first Comfort threshold, about -4.67, lies far into the lower tail of the assumed trait distribution. Its point estimate alone does not establish precision, especially given the five responses in the lowest category.

Agreement with an item can be summarized in two ways. At a specified trait value, sum the probabilities of categories 2 and 3. For the population proportion, average the category probabilities over the latent distribution. These summaries answer different questions. The following calculations also compare the observed two-item response tables with the tables implied by conditional independence.

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
science_rule <- irt_rule(121L)
science_marginals <- do.call(rbind, lapply(seq_along(science_names), function(j) {
  probabilities <- exp(irt_prob(science_121$items[[j]], science_rule$nodes)$logp)
  data.frame(item = science_names[j], category = 0:3,
    observed = science_counts[j, ] / nrow(science_Y),
    fitted = drop(crossprod(science_rule$weights, probabilities)))
}))
science_traces <- do.call(rbind, lapply(seq_along(science_names), function(j) {
  probabilities <- exp(irt_prob(science_121$items[[j]], c(-1, 0, 1))$logp)
  data.frame(item = science_names[j], trait = c(-1, 0, 1),
    agree_or_strongly_agree = rowSums(probabilities[, 3:4, drop = FALSE]),
    strongly_agree = probabilities[, 4])
}))
science_pair_check <- do.call(rbind, lapply(combn(4L, 2L, simplify = FALSE), function(pair) {
  probabilities <- lapply(pair, function(j)
    exp(irt_prob(science_121$items[[j]], science_rule$nodes)$logp))
  predicted <- crossprod(probabilities[[1]], probabilities[[2]] * science_rule$weights)
  observed <- table(factor(science_Y[, pair[1]], levels = 0:3),
                    factor(science_Y[, pair[2]], levels = 0:3)) / nrow(science_Y)
  data.frame(first = science_names[pair[1]], second = science_names[pair[2]],
             max_cell_probability_gap = max(abs(observed - predicted)))
}))
print(science_marginals, row.names = FALSE)
print(science_traces, row.names = FALSE)
print(science_pair_check, row.names = FALSE)
saveRDS(list(fits = science_fits, parameters = science_parameters,
  marginals = science_marginals, pairs = science_pair_check),
  file.path("data/derived/ch10", "ch10-science.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
    item category   observed     fitted
 Comfort        0 0.01275510 0.01280965
 Comfort        1 0.08163265 0.08343255
 Comfort        2 0.67857143 0.67452496
 Comfort        3 0.22704082 0.22923284
    Work        0 0.08418367 0.08565382
    Work        1 0.25000000 0.24651375
    Work        2 0.52551020 0.52637629
    Work        3 0.14030612 0.14145615
  Future        0 0.03571429 0.03669267
  Future        1 0.18367347 0.18435046
  Future        2 0.53571429 0.53137851
  Future        3 0.24489796 0.24757835
 Benefit        0 0.05357143 0.05474378
 Benefit        1 0.25510204 0.25497640
 Benefit        2 0.49234694 0.48925553
 Benefit        3 0.19897959 0.20102429
    item trait agree_or_strongly_agree strongly_agree
 Comfort    -1               0.8318077     0.07542217
 Comfort     0               0.9333438     0.18762706
 Comfort     1               0.9753966     0.39537577
    Work    -1               0.4195293     0.02953228
    Work     0               0.7111864     0.09394119
    Work     1               0.8935010     0.26103879
  Future    -1               0.4795746     0.01382733
  Future     0               0.9018760     0.12269073
  Future     1               0.9892095     0.58244017
 Benefit    -1               0.4744090     0.05833300
 Benefit     0               0.7293722     0.15609295
 Benefit     1               0.8894694     0.35578691
   first  second max_cell_probability_gap
 Comfort    Work               0.02235649
 Comfort  Future               0.01636578
 Comfort Benefit               0.02482150
    Work  Future               0.01700027
    Work Benefit               0.02409224
  Future Benefit               0.02247909

The first table compares each item’s observed and fitted category proportions. The second gives the conditional probabilities of agreement and strong agreement at $z=-1,0,1$. A large difference between these trait values indicates that the item distinguishes attitudes within this interval. The third table reports the largest absolute cell-probability discrepancy for each pair of items. Small marginal discrepancies can coexist with larger pair discrepancies when the model fails to reproduce an association between answers. These discrepancies are descriptive checks, without a reference distribution that would turn them into significance tests.

For Future, the probability of agreement or strong agreement rises from 0.480 at $z=-1$ to 0.989 at $z=1$; the probability of strong agreement alone rises from 0.014 to 0.582. For Comfort, agreement is already common at $z=-1$, with probability 0.832. Observed and fitted single-item category proportions differ by at most about 0.0044. The largest pairwise discrepancy is larger, about 0.0248 for Comfort and Benefit. Thus the close marginal fit does not eliminate discrepancies in the joint responses.

The same four items can be fitted with mirt. Its graded-response coefficients use cumulative intercepts $d_{jk}=-a_jb_{jk}$. Convert them to the threshold convention above before evaluating the returned items with the book’s likelihood.

1
2
3
4
5
6
7
8
9
10
11
12
science_reference <- mirt::mirt(science_Y, 1L, itemtype = "graded", method = "EM",
  quadpts = 121L, TOL = 1e-6, technical = list(NCYCLES = 2000L), verbose = FALSE)
science_reference_coefficients <- mirt::coef(science_reference, simplify = TRUE, IRTpars = FALSE)$items
science_reference_items <- lapply(seq_along(science_names), function(j) {
  a <- science_reference_coefficients[j, "a1"]
  irt_item("GRM", a = a, cuts = -science_reference_coefficients[j, paste0("d", 1:3)] / a)
})
science_reference_value <- irt_estep(science_data, science_reference_items, science_rule)$value
science_reference_gap <- abs(science_reference_value - science_121$negative_marginal_loglik)
print(data.frame(book_loglik_121 = -science_121$negative_marginal_loglik,
  package_loglik_121 = -science_reference_value, absolute_gap = science_reference_gap))
saveRDS(science_reference, file.path("data/derived/ch10", "ch10-reference.rds"))
1
2
  book_loglik_121 package_loglik_121 absolute_gap
1       -1608.869          -1608.869 8.706786e-07

The likelihood gap between the two implementations is about $8.71\times10^{-7}$ on common nodes and weights. Increasing the final book fit’s evaluation rule from 121 to 241 nodes changes its log likelihood by about $6.24\times10^{-7}$. These results support numerical agreement for this fitted model. They do not establish that the four items measure only one attitude dimension. The scale is short, so individual trait estimates should be accompanied by their conditional uncertainty. Generalization beyond this survey extract also requires attention to its sampling design, which is not represented by this unweighted likelihood.

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