Latent classes, finite mixtures, and nonparametric latent distributions
Respondents may differ in which combinations of answers they tend to give. The proportion of respondents who answer no to each question does not reveal whether the same people tend to answer no across several questions. A latent class model describes the population as a mixture of groups with different response profiles. These groups offer a way to explain how answers occur together. Their interpretation rests on the fitted response patterns and the model’s assumptions, rather than on observed membership in distinct populations. The chapter begins with latent classes for categorical answers, extends the mixture to continuous measurements and to covariates, examines starting values, identification and the number of classes, and ends by estimating a random-intercept distribution as a discrete distribution.
12.1 Latent class models for binary and categorical indicators
Latent class analysis (LCA) is a form of finite mixture modeling with categorical indicators. In the simulated questionnaire LCA6, let $C_i$ be the unobserved class of respondent $i$. Here $C_i$ takes values 1, 2 or 3. Code a yes answer as 1 and a no answer as 0. A class’s response profile gives the probabilities of a yes answer across the six questions. The class proportion $\pi_k=P(C_i=k)$ describes a randomly chosen respondent before any answers are observed, and the proportions sum to one. For indicator $j$, let $\theta_{jk}=P(Y_{ij}=1\mid C_i=k)$ be the conditional probability of a yes answer. The simulation uses these population parameters. The vector lca_mass stores $\pi_k$ in entry $k$, and success[j,k] stores $\theta_{jk}$. The matrix has one row per question and one column per class; these population probabilities do not contain respondents’ inferred classes.
1
2
3
4
5
6
lca_mass <- c(.3, .4, .3)
success <- cbind(
c(.10, .15, .10, .15, .10, .15),
c(.85, .80, .85, .15, .10, .15),
c(.85, .90, .85, .85, .90, .85)
)
Classes 2 and 3 have the same success probability on question one. Questions four through six help distinguish them because the two columns give quite different probabilities on those questions. Each person has one class for the entire questionnaire.
Write $Y_i$ for the six answers from respondent $i$. For a particular pattern $y=(y_1,\ldots,y_6)$, local independence means that its conditional probability within class $k$ is the product of the six probabilities of the recorded answers. Denote this product by $f_k(y)$. Multiplying by $\pi_k$ gives the joint probability of class $k$ and pattern $y$. The three classes are mutually exclusive and exhaustive, so the marginal pattern probability $p(y)$ and the posterior class membership probability, conditional on the pattern at the specified model parameters, are
\[f_k(y)=\prod_{j=1}^6\theta_{jk}^{y_j}(1-\theta_{jk})^{1-y_j},\qquad p(y)=\sum_{k=1}^3\pi_k f_k(y),\qquad P(C_i=k\mid Y_i=y)=\frac{\pi_k f_k(y)}{p(y)}.\]The matrix patterns enumerates the $2^6=64$ possibilities, starting with six zeros. From the book directory, the following calculation traces that row. The function named lca_log_emission() computes the class-conditional log probability of a response pattern by adding the six item contributions. The name denotes this calculation; the model here contains no sequence of transitions between classes. Adding the log class proportions gives the three log joint probabilities in joint. Subtracting their maximum makes the largest exponentiated term one. Adding the maximum back after taking the logarithm recovers $\log p(y)$. The two functions used below are in code/lib/mixtures.R.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
lca_log_emission <- function(Y, probability) {
Y <- as.matrix(Y)
if (is.matrix(probability)) {
success <- probability
probability <- lapply(seq_len(nrow(success)), function(j) rbind(1 - success[j, ], success[j, ]))
}
stopifnot(ncol(Y) == length(probability), nrow(Y) > 0L, length(probability) > 0L)
K <- ncol(probability[[1L]])
out <- matrix(0, nrow(Y), K)
for (j in seq_along(probability)) {
p <- probability[[j]]
observed <- !is.na(Y[, j])
stopifnot(is.matrix(p), ncol(p) == K, all(is.finite(p)), all(p >= 0),
max(abs(colSums(p) - 1)) <= 1e-10, all(Y[observed, j] %in% (seq_len(nrow(p)) - 1L)))
# An omitted indicator contributes log(1) for every class.
out[observed, ] <- out[observed, , drop = FALSE] + log(p[Y[observed, j] + 1L, , drop = FALSE])
}
out
}
A matrix argument gives each item’s success probability in each class; it is turned into one table per item with rows for the answers 0 and 1. For every person and class, out adds $\log\theta_{jk}$ or $\log(1-\theta_{jk})$ for each recorded answer, so entry $(i,k)$ is $\log f_k(y_i)$; an omitted item adds nothing.
1
2
3
4
5
6
7
8
9
10
11
mixture_posterior <- function(log_emission, mass) {
stopifnot(is.matrix(log_emission), all(is.finite(mass)), all(mass >= 0))
if (is.matrix(mass)) {
stopifnot(identical(dim(mass), dim(log_emission)), max(abs(rowSums(mass) - 1)) < 1e-10)
joint <- log_emission + log(mass)
} else {
stopifnot(ncol(log_emission) == length(mass), abs(sum(mass) - 1) < 1e-10)
joint <- sweep(log_emission, 2L, log(mass), "+")
}
mixture_from_log_joint(joint)
}
Entry $(i,k)$ of joint is $\log f_k(y_i)+\log\pi_k$; when mass is a matrix, row $i$ uses its own class probabilities. The one-row calculation below traces the rest of the function, and the returned loglik is the sum of observation_loglik.
1
2
3
4
5
6
7
8
9
10
11
12
13
source("code/lib/mixtures.R")
patterns <- as.matrix(expand.grid(
setNames(rep(list(0:1), 6L), paste0("indicator_", 1:6))
))
log_conditional <- lca_log_emission(patterns, success)
joint <- log_conditional[1L, ] + log(lca_mass)
largest <- max(joint)
log_pattern <- largest + log(sum(exp(joint - largest)))
posterior_zero <- exp(joint - log_pattern)
# The same normalization is performed for every row.
patterns_fit <- mixture_posterior(log_conditional, lca_mass)
stopifnot(abs(sum(exp(patterns_fit$observation_loglik)) - 1) < 1e-12)
For six zeros the largest joint term comes from class 1. Its six conditional zero probabilities have product 0.447697125. Multiplying by the class proportion 0.30 gives 0.13430914. Dividing this by the sum of the three joint terms gives posterior_zero[1L], about 0.99135. Class membership is still uncertain because all three classes can produce this pattern.
The one-row calculation also explains the imported helpers. mixture_posterior() adds the log class proportions to every row of log_conditional and passes the resulting matrix to mixture_from_log_joint(). That helper repeats the largest and log_pattern calculation for each row. The returned observation_loglik contains one log marginal probability per pattern, and each row of posterior contains the three membership probabilities for that pattern. Its first row reproduces posterior_zero. Each posterior row sums to one over classes. The final check instead sums the marginal probabilities over the 64 possible response patterns; that sum is also one.
An indicator with more than two categories changes one factor in the product. If item $j$ has $K_j$ categories coded from $0$ to $K_j-1$, write $q_{jck}=P(Y_{ij}=c\mid C_i=k)$. For a pattern $y$, the within-class product becomes $f_k(y)=\prod_j q_{j,y_j,k}$. All categories are possible outcomes of the same item, so $\sum_c q_{jck}=1$ for each class. In R, a list can accommodate a different number of rows for each item. In its $j$th table, row $c+1$ selects the recorded category and column $k$ selects the class: category_probability[[j]][c + 1, k] is $q_{jck}$. These numbers label categories; the model does not require an ordering or equal distances between them. For the six dichotomous indicators the following calculation builds the item tables and accumulates the conditional log probabilities for all patterns.
1
2
3
4
5
6
7
8
9
category_probability <- lapply(seq_len(nrow(success)), function(j) {
rbind(1 - success[j, ], success[j, ])
})
category_log <- matrix(0, nrow(patterns), length(lca_mass))
for (j in seq_along(category_probability)) {
category_rows <- patterns[, j] + 1L
category_log <- category_log +
log(category_probability[[j]][category_rows, , drop = FALSE])
}
For question one, a zero selects the first row, which gives 0.90, 0.15 and 0.15 across the three classes. This lookup reconstructs log_conditional. If an item had a third category coded 2, its occurrence would select row 3 of that item’s table. The sum over classes would still have three terms.
Pattern frequencies in a simulated sample
The 64 rows above enumerate possible answers, rather than an observed sample. Write $y_i$ for the observed answers of person $i$. In a sample of $n$ independent respondents, a pattern observed $n_y$ times contributes $n_y$ copies of its log probability. Thus the sample log likelihood is $\ell=\sum_y n_y\log p(y)=\sum_{i=1}^n\log p(y_i)$.
The observed frequencies enter when 600 respondents are drawn from the specified population. For each person, the generator draws a class once. It then compares six independent uniform draws with the six probabilities in that class’s column. This is where local independence enters the simulation. Transposing the selected columns arranges the probabilities in the same person-by-item order as the uniform draws.
1
2
3
4
5
6
7
8
9
10
11
12
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(1201)
simulate_lca <- function(n, pi, probability) {
state <- sample.int(length(pi), n, replace = TRUE, prob = pi)
response <- matrix(runif(n * nrow(probability)), n) <
t(probability[, state, drop = FALSE])
list(Y = 1 * response, state = state)
}
lca_input <- simulate_lca(600L, lca_mass, success)
Y <- lca_input$Y
zero_count <- sum(rowSums(Y) == 0)
sample_loglik <- mixture_posterior(lca_log_emission(Y, success), lca_mass)$loglik
In the simulated sample, the all-zero pattern occurred 77 times, so it contributes $77\log p(0,0,0,0,0,0)$ to the sum. Adding the contributions from all 600 rows gives a log likelihood of approximately $-1926.758$ at the generating parameters. The generator also returns lca_input$state, the class memberships drawn in the simulation, for checking how the data were generated. Computing the observed-data likelihood requires only the answers and the proposed parameters.
If the class proportions and item probabilities were unknown, how many quantities would the pattern frequencies have to determine? Within one class, $K_j-1$ probabilities can vary freely for item $j$ because the last probability is one minus the sum of the others. With $R$ classes, the items therefore contribute $R\sum_j(K_j-1)$ parameters and the class proportions contribute another $R-1$. Here that gives $3(6)+2=20$. The 64 pattern probabilities also sum to one, leaving 63 free cell probabilities. The parameter count meets this necessary dimension condition for identification. Exchanging two class proportions along with the corresponding columns of every item table only reorders the terms of $p(y)$ for every pattern. Identifying distinct response profiles up to a permutation of their labels requires more than counting cells and parameters.
The all-zero row shows what the shared class contributes to the observed distribution. In class 1, the probability of six zeros is $0.90^3\,0.85^3=0.447697125$. To compare the mixture with independent answers having the same marginal probabilities, average first averages each item’s success probability over classes. A single column of six such probabilities gives the product for each pattern under independence. The call prints six patterns. Only the first row is reproduced below.
1
2
3
4
5
6
7
8
9
10
11
12
13
average <- drop(success %*% lca_mass)
independent <- exp(lca_log_emission(patterns, matrix(average, ncol = 1L)))
class_probability <- setNames(
as.data.frame(exp(log_conditional)),
paste0("pattern_probability_given_class_", seq_along(lca_mass))
)
pattern_table <- data.frame(
patterns, class_probability,
response_pattern_probability = exp(patterns_fit$observation_loglik),
product_of_marginals = drop(independent),
difference = exp(patterns_fit$observation_loglik) - drop(independent)
)
print(head(pattern_table))
1
2
3
4
5
6
7
8
indicator_1 indicator_2 indicator_3 indicator_4 indicator_5 indicator_6
1 0 0 0 0 0 0
pattern_probability_given_class_1 pattern_probability_given_class_2
1 0.447697125 0.002926125
pattern_probability_given_class_3 response_pattern_probability
1 0.0000050625 0.13548111
product_of_marginals difference
1 0.01387584 0.1216052662
The six indicator_ columns identify the pattern, the three pattern_probability_given_class_ columns give its conditional probabilities, and response_pattern_probability is its marginal probability.
Weighting the first row’s three conditional probabilities by 0.3, 0.4 and 0.3 gives 0.13548111 for six zeros. Multiplying the six marginal zero probabilities gives only 0.01387584. Among 600 respondents, these probabilities imply about 81 all-zero patterns under the mixture and 8 under independence, compared with the 77 observed. The product would describe one person’s answers if they were marginally independent. For a single person, observing a zero favors a class in which other zeros are also likely. That dependence across answers arises even though the six responses are independent within each class. The poLCA package provides latent class models for categorical indicators.
12.2 Posterior class probabilities and EM updates
The first respondent in LCA6 answered yes to the first three questions and no to the last three. How much should this person count toward each class when both the class proportions and the response profiles have to be estimated? Let $z_{ik}$ equal one if respondent $i$ belongs to class $k$ and zero otherwise. Given the answers $y_i$, the conditional expectation of $z_{ik}$ is the posterior class membership probability $\tau_{ik}$. At the current parameters, the joint probability of the answers and class $k$ is $\pi_k f_k(y_i)$. Summing that quantity over the classes gives the probability of the answers, so the E step uses
The first E step below uses mixture_posterior() to apply the log-scale normalization traced in Section 12.1 to the observed questionnaires at the starting parameters. The returned posterior row supplies the weights for that respondent in the next parameter update.
With these probabilities fixed, what class sizes and item frequencies enter the M step? The expected number of people in class $k$ is $N_k=\sum_i\tau_{ik}$. In the expected complete-data log likelihood, the terms containing the class proportions sum to $\sum_k N_k\log\pi_k$. Maximizing subject to $\sum_k\pi_k=1$ makes $\pi_k$ proportional to $N_k$. Since each respondent contributes a total of one across classes, $\sum_k N_k=n$. For a fully observed binary item $j$, let $S_{jk}=\sum_i\tau_{ik}y_{ij}$ be its expected number of yes answers in class $k$. Its contribution to the expected complete-data log likelihood is $S_{jk}\log\theta_{jk}+(N_k-S_{jk})\log(1-\theta_{jk})$. This binomial expression is maximized at the expected fraction of successes. Together the two updates are
\[\pi_k^{\mathrm{new}}=\frac{N_k}{n},\qquad \theta_{jk}^{\mathrm{new}}=\frac{S_{jk}}{N_k}\quad(N_k>0).\]A person answering yes contributes the same fraction to the success count and the class count. A person answering no contributes that fraction only to the class count.
For a categorical item, each answer contributes to the count for its recorded category. Suppose the probability of the missingness pattern depends only on recorded responses and its parameters are distinct from the response parameters. This is the missing-at-random condition together with distinct missingness and response parameters. The likelihood and update helpers below can omit missing items, but the supplied lca_em() fitting loop requires fully observed questionnaires. Under this ignorable mechanism, the E step uses just the items each person answered to evaluate that person’s class probabilities. An omitted item contributes a factor of one because its category probabilities sum to one in every class. Let $O_j$ contain the respondents who answered item $j$. For category $c$ the update is
In lca_update_categories() each item therefore has its own set of respondents and its own denominators.
1
2
3
4
5
6
7
8
9
10
11
lca_update_categories <- function(Y, weights, categories) {
lapply(seq_len(ncol(Y)), function(j) {
observed <- !is.na(Y[, j])
W <- weights[observed, , drop = FALSE]
exposure <- colSums(W)
if (any(exposure <= 0)) stop(sprintf("No effective observations for indicator %d", j))
# The denominator uses only people who answered indicator j.
indicator <- outer(Y[observed, j], seq_len(categories[j]) - 1L, "==")
sweep(crossprod(indicator, W), 2L, exposure, "/")
})
}
For item j, observed selects these respondents and W contains their rows of posterior probabilities. Each column of indicator marks one category. The entry in row $c+1$, column $k$ of crossprod(indicator, W) is the expected count for that category and class. Dividing by exposure[k], the positive sum of column $k$ of W, gives the new probability. With all six items observed, lca_em() can use the same class denominator for every item. Here exposure[k] is an expected respondent count among those who answered this item, not an observation duration. A zero denominator supplies no information for that item and class in this update.
Fitting the LCA6 questionnaires
For the 600 complete questionnaires, the fit starts with three equal class proportions and randomly generated category probabilities. Using seed 1202 fixes this particular start. Applying the E and M steps to lca_fit$start reconstructs the first update from those starting parameters. The fit uses lca_em() in code/lib/mixtures.R, shown in two parts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
lca_em <- function(Y, n_classes, probs_start = NULL, n_starts = 1L, max_iter = 1000L, tol = 1e-10) {
y <- as.matrix(Y) + 1
N <- nrow(y)
J <- ncol(y)
K <- apply(y, 2, max)
R <- n_classes
huge_value <- .Machine$double.xmax
item_lik <- function(probs) {
lik <- matrix(huge_value, N, R)
for (k in 1:J) lik <- lik * t(probs[[k]][, y[, k], drop = FALSE])
lik
}
indicators <- lapply(1:J, function(k) outer(y[, k], 1:K[k], "==") * 1)
ones <- matrix(1, N, 1)
if (R == 1) {
# One class: the category proportions, no iterations and no random draws.
probs <- lapply(seq_len(J), function(k) { n_k <- sum(y[, k] > 0); matrix(vapply(seq_len(K[k]), function(c) sum(y[, k] == c) / n_k, 0), 1) })
log_lik <- sum(log(item_lik(probs)) - log(huge_value))
return(list(model = list(mass = 1, probability = lapply(probs, t)), loglik = log_lik,
posterior = matrix(1, N, 1), iterations = 1, converged = TRUE, reason = "converged",
attempts = log_lik, restarts = 0L, start = NULL))
}
The answers are recoded as categories $1,\ldots,K_j$. The function item_lik() multiplies, for every person and class, the probabilities of the recorded categories, starting from the largest representable number so that a long product does not fall below the smallest; the log likelihood later subtracts the logarithm of that starting value. With one class the estimates are the observed category proportions and no iteration is needed.
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
best <- list(log_lik = -Inf)
attempts <- numeric(0)
restarts <- 0L
runs <- vector("list",n_starts)
for (rep_i in seq_len(n_starts)) {
error <- TRUE
first_run <- TRUE
while (error) {
error <- FALSE
prior <- matrix(1 / R, N, R)
if (is.null(probs_start) || !first_run || rep_i > 1) {
probs <- lapply(1:J, function(k) {
m <- matrix(runif(R * K[k]), nrow = R, ncol = K[k])
m / rowSums(m)
})
} else probs <- probs_start
probs_init <- probs
if (is.null(runs[[rep_i]])) runs[[rep_i]] <- list(starts=list())
runs[[rep_i]]$starts <- c(runs[[rep_i]]$starts,list(probs_init))
iter <- 1
dll <- Inf; log_lik <- -Inf
# Iterate until the limit, a gain of at most tol, or a numerical error.
while (iter <= max_iter && dll > tol && !error) {
iter <- iter + 1
lik <- item_lik(probs)
denom <- numeric(N)
for (j in 1:R) denom <- denom + prior[, j] * lik[, j]
post_class <- prior * lik / denom
denominator <- drop(crossprod(ones, post_class))
probs <- lapply(1:J, function(k) t(crossprod(indicators[[k]], post_class)) / denominator)
prior <- matrix(colMeans(post_class), nrow = N, ncol = R, byrow = TRUE)
log_lik[iter] <- sum(log(rowSums(prior * item_lik(probs))) - log(huge_value))
dll <- log_lik[iter] - log_lik[iter - 1]
if (is.na(dll)) error <- TRUE
}
if (error) restarts <- restarts + 1L
first_run <- FALSE
}
runs[[rep_i]]$iterations <- iter-1L
runs[[rep_i]]$loglik <- log_lik[-1L]
attempts <- c(attempts, log_lik[iter])
if (log_lik[iter] > best$log_lik) best <- list(log_lik = log_lik[iter], probs = probs, probs_start = probs_init,
posterior = post_class, P = colMeans(post_class), n_iter = iter - 1, converged = dll <= tol)
}
model <- list(mass = best$P, probability = lapply(best$probs, t))
final_posterior <- mixture_posterior(lca_log_emission(Y, model$probability), model$mass)$posterior
list(model = model, loglik = best$log_lik, posterior = final_posterior,
last_estep_posterior = best$posterior, iterations = best$n_iter,
converged = best$converged, reason = if (best$converged) "converged" else "iteration_limit",
attempts = attempts, restarts = restarts, runs=runs,
start = list(mass = rep(1 / R, R), probability = lapply(best$probs_start, t)))
}
Each start draws every class’s category probabilities as uniform numbers divided by their sum, except that a supplied probs_start is used for the first start, and gives the classes equal proportions. In the loop, post_class is $\tau_{ik}$, denominator contains $N_k$, the new category probabilities are the expected counts in each category divided by $N_k$, and every row of prior contains $\pi_k^{\mathrm{new}}=N_k/n$. The loop stops after max_iter iterations or when the log likelihood increases by no more than tol; a value that cannot be computed restarts the attempt from new random probabilities and is counted in restarts. Over n_starts starts the fit with the largest log likelihood is returned, together with the posterior probabilities recomputed by lca_log_emission() and mixture_posterior() at its estimates and the starting values in start.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
source("code/lib/mixtures.R")
Y <- readRDS("data/source/ch12/LCA6.rds")
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1202)
lca_fit <- lca_em(Y,3L)
lca_start <- lca_fit$start
first <- mixture_posterior(lca_log_emission(Y,lca_start$probability),lca_start$mass)
first_update <- list(mass=colMeans(first$posterior),
probability=lca_update_categories(Y,first$posterior,rep(2L,6)))
print(list(person1_response=Y[1,],membership=first$posterior[1,],
expected_class_sizes=colSums(first$posterior),
first_indicator=first_update$probability[[1]],log_likelihood_before=first$loglik,
log_likelihood_after=mixture_posterior(lca_log_emission(Y,first_update$probability),
first_update$mass)$loglik))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$person1_response
[1] 1 1 1 0 0 0
$membership
[1] 0.87753447 0.10102142 0.02144411
$expected_class_sizes
[1] 183.7796 254.3409 161.8795
$first_indicator
[,1] [,2] [,3]
[1,] 0.2425907 0.3284085 0.4996869
[2,] 0.7574093 0.6715915 0.5003131
$log_likelihood_before
[1] -3193.999
$log_likelihood_after
[1] -2297.948
To generate its starting probabilities for each item, lca_em() draws independent uniform values into a table with classes in rows and categories in columns, then divides each entry by its row sum. The returned start transposes these item tables, so a column now contains the category probabilities for one class. The probs_start input uses classes in rows, so a returned start$probability cannot be passed back as that input without transposing each table.
The second row of first_update$probability[[1]] gives the three new probabilities of a yes answer on item one. Where does the first value, 0.7574093, come from? The next calculation counts how often the first person’s pattern occurs. For the item numerator, crossprod() sums the posterior probabilities among everyone who answered yes on that item.
1
2
3
4
5
person1_frequency <- sum(rowSums(sweep(Y,2,Y[1,],"!="))==0)
print(data.frame(class=1:3,pattern_frequency=person1_frequency,
membership=first$posterior[1,],
expected_item1_success=drop(crossprod(Y[,1],first$posterior)),
class_total=colSums(first$posterior)))
1
2
3
4
class pattern_frequency membership expected_item1_success class_total
1 1 96 0.87753447 139.19636 183.7796
2 2 96 0.10102142 170.81320 254.3409
3 3 96 0.02144411 80.99045 161.8795
The 96 people with this pattern each contribute 0.87753 to the class 1 count. The expected class 1 count of 183.7796 gives an updated class proportion of $183.7796/600\approx0.30630$. All 600 questionnaires enter the ratio $139.19636/183.7796\approx0.75741$. The analogous ratios give 0.67159 and 0.50031 for classes 2 and 3. This single update raises the observed-data log likelihood from $-3193.999$ to $-2297.948$. The fit repeats the steps until the log likelihood gain is at most $10^{-10}$ or the run reaches 1,000 iterations. A decrease also meets the gain rule. An undefined gain triggers a fresh random start. The current restart loop has no separate limit on the number of these retries.
1
print(c(iterations=lca_fit$iterations,converged=lca_fit$converged,loglik=lca_fit$loglik))
1
2
iterations converged loglik
59.000 1.000 -1919.502
Here converged equals 1 because the gain rule was met after 59 iterations at $-1919.502$.
The fitting function lca_em() evaluates posterior class probabilities for fully observed questionnaires using scaled products. Its internal function item_lik() starts each class product at .Machine$double.xmax and multiplies by the probability of each recorded category. For each respondent, denom sums those scaled products multiplied by their class proportions. Dividing prior * lik by denom gives post_class, the matrix of posterior probabilities. The numerator and denominator contain the same multiplier, so it cancels in each row. That cancellation is algebraic: a sufficiently long product can still underflow, and a response pattern assigned zero probability by every class has no defined posterior ratio.
Suppose the first respondent were assigned entirely to the most probable class at the starting parameters. This would replace $(0.87753,0.10102,0.02144)$ with $(1,0,0)$. Since this respondent answered yes on item one, the change would add about 0.12247 to both the class 1 numerator and its denominator, and remove this person’s contributions from the other classes. If the E-step probabilities for the other 599 rows remained unchanged, this one change would raise the updated class 1 success probability from 0.75741 to 0.75757. Let $g_i$ be the selected class for each respondent. The complete-data log likelihood for the selected labels and the Q function averaging over the unknown labels are respectively
\[\ell_{\mathrm{class}}(\pi,q;g)= \sum_i\log\{\pi_{g_i}f_{g_i}(y_i)\},\qquad Q(\pi,q)=\sum_i\sum_k\tau_{ik}\log\{\pi_k f_k(y_i)\}.\]Both expressions evaluate candidate proportions $\pi$ and item probabilities $q$. The first credits each answer to its selected class. The second retains the term for every class, multiplied by its E-step probability, which is how uncertainty about membership enters the parameter estimates. The E-step probabilities remain fixed while the candidate parameters vary in Q. The selected labels in the first expression are assignments made from the model, not observed class memberships.
Which class probabilities describe the first respondent after fitting? The returned lca_fit$posterior evaluates the class probabilities under lca_fit$model at the returned estimates. The separate last_estep_posterior preserves the probabilities used in the last parameter update. Evaluating the three class terms directly gives the same fitted conditional probabilities.
1
2
3
4
5
fitted_model <- lca_fit$model
fitted_membership <- mixture_posterior(
lca_log_emission(Y[1, , drop = FALSE], fitted_model$probability),
fitted_model$mass
)$posterior
For the pattern $(1,1,1,0,0,0)$ these probabilities are approximately 0.996132, 0.001174 and 0.002694. Class 1 is the most probable assignment. The other two probabilities describe membership uncertainty at the fitted parameters, without allowing for uncertainty in those estimates. The supplied lca_em() reproduces, with parts adapted, the latent class EM of the poLCA package (code/NOTICE.md), which fits these models by EM.
12.3 Gaussian mixtures and latent profiles
Latent profile analysis (LPA) uses continuous indicators in a finite mixture model. In the observed faithful dataset distributed with R, the first recorded eruption of the Old Faithful geyser lasted 3.60 minutes. The wait until the next eruption was 79 minutes. Under a model with two eruption profiles, how much evidence does this pair of measurements give for each? Let $y_i$ contain the two times for eruption $i$ and let $\pi_k$ be the proportion of eruptions in component $k$. Within a component, suppose the pair has a bivariate normal density $\phi_2(y_i;\mu_k,\Sigma_k)$ with mean vector $\mu_k$ and positive definite covariance matrix $\Sigma_k$. Each pair contributes its mixture density. Treating the pairs as independent gives the sample log likelihood
The two entries of $\mu_k$ are the mean duration and mean waiting time among eruptions in component $k$, each in minutes on the original measurement scale. The diagonal entries of $\Sigma_k$ are the variances of those measurements around their component means, in squared minutes. Larger diagonal entries mean greater variation among eruptions within that profile. Its off-diagonal covariance describes how departures from the two component means vary together; a positive value associates longer durations with longer waiting times within the profile.
An unrestricted positive definite covariance matrix allows duration and waiting time to vary together within the same profile. A diagonal covariance sets their within-component covariance to zero. Under the normal model this makes the measurements conditionally independent, an assumption often used in LPA. Both models allow each component its own variances. Even with diagonal covariances, different component means can produce an association in the pooled measurements. Applied to measurements on people, the model requires independent people and a suitable within-class response distribution. Fitted components alone do not establish that distinct social groups exist. Latent profile models can also allow within-class covariances; conditional independence is a model restriction, not a requirement of every LPA specification.
Once an E step has divided each pair’s two products of mixing proportion and component density by their sum, how do its posterior probabilities $\tau_{ik}$ affect the estimated profiles? Let $N_k=\sum_i\tau_{ik}$, and fix these probabilities throughout the M step. Apart from the term containing the mixing proportions and a constant, the expected complete-data log likelihood for component $k$ is
\[-\frac{N_k}{2}\log|\Sigma_k| -\frac12\sum_i\tau_{ik}(y_i-\mu_k)^\top\Sigma_k^{-1}(y_i-\mu_k).\]Differentiating with respect to $\mu_k$ gives $\Sigma_k^{-1}\sum_i\tau_{ik}(y_i-\mu_k)$. Setting this to zero yields $\hat\mu_k=\sum_i\tau_{ik}y_i/N_k$. At that mean, write $A_k=\sum_i\tau_{ik}(y_i-\hat\mu_k)(y_i-\hat\mu_k)^\top$. Differentiating with respect to the precision matrix gives $(N_k\Sigma_k-A_k)/2$, so the full covariance update is $\hat\Sigma_k=A_k/N_k$. The divisor comes from the coefficient of the log determinant and can be fractional. The proportion update is $N_k/n$. Under the diagonal restriction, the quadratic form separates into one squared residual per axis divided by its variance. Each variance is the corresponding diagonal entry of $A_k/N_k$. These updates require $N_k>0$. For the unrestricted normal component, a positive definite $A_k$ is also needed for a finite covariance maximizer within the allowed positive definite matrices; a singular scatter instead leads toward a singular boundary.
Full and diagonal fits to the geyser data
The 272 rows of faithful record both measurements in minutes, but waiting times vary much more than eruption durations. The R dataset documentation describes the measurements. In scaled_geyser each column is centered at its sample mean and divided by its sample standard deviation. The first pair becomes $(0.09832,0.59602)$, with both measurements above their respective means. The initial partition uses a further transformation. Starting from the book directory, the following calls build the hierarchy and cut it at two groups.
1
2
3
4
5
6
7
8
9
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/gaussian_mixture.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
geyser <- as.matrix(datasets::faithful)
scaled_geyser <- scale(geyser)
geyser_hc <- mixture_agglomerate(scaled_geyser)
geyser_partition <- mixture_agglomerate_partition(geyser_hc,2)
Let $X=UDV^\top$ be the singular value decomposition of the centered, standardized matrix inside mixture_agglomerate(), with singular values $d_j$ on the diagonal of $D$. The rows used for clustering are $XVD^{-1/2}=UD^{1/2}$. The columns are centered, and their cross-product matrix is $D$ because $U^\top U=I$. They are therefore uncorrelated, with sample variances $d_j/(n-1)$, rather than unit sample variances. Starting with one group per observation, the algorithm merges two groups at a time according to its full-covariance criterion. Only the group labels pass from the hierarchy to the two EM fits. The two functions are in code/lib/gaussian_mixture.R.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mixture_agglomerate <- function(data) {
standardized <- scale(data, center = TRUE, scale = TRUE)
k <- min(nrow(standardized), ncol(standardized))
decomposition <- svd(standardized, nu = 0)
rotated <- standardized %*% decomposition$v # principal axes; then unit sum of squares over the variance
Z <- unname(rotated %*% diag(1 / sqrt(decomposition$d), k, k))
n <- nrow(Z); p <- ncol(Z)
start_groups <- seq_len(n)
merges <- n - 1
# Working length of the merge routine's distance store.
work_len <- max(n, (n * (n - 1)) / 2 + 1, 3 * merges)
alpha <- max(mixture_within_ss(Z / sqrt(n * p)), .Machine$double.eps)
out <- mixture_merge_sequence(cbind(Z, 0), n, p, start_groups, n, merges, alpha, 1, work_len)
keep <- seq_len(merges)
list(pairs = t(out$x[keep, 1:2, drop = FALSE]), criteria = out$d[keep], initial = start_groups,
data = Z)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mixture_agglomerate_partition <- function(hc, G) {
initial <- hc$initial
k <- length(unique(initial))
select <- k - G
for (step in seq_len(select)) {
pair <- range(hc$pairs[, step])
initial[initial == pair[2]] <- pair[1]
}
# Each merge joins the larger label into the smaller one. The remaining labels are then
# renumbered 1, 2, ... in order of first appearance, as double values.
#
#
#
as.numeric(match(initial, unique(initial)))
}
In mixture_agglomerate(), Z contains the rows $UD^{1/2}$. The function mixture_merge_sequence() carries out the $n-1$ merges of the translated hierarchical routine and returns, for each merge, the pair of group labels joined and the value of the criterion; alpha is the routine’s lower limit for a within-group sum of squares, taken from mixture_within_ss() of the rescaled rows. To cut the hierarchy at $G$ groups, mixture_agglomerate_partition() replays the first $n-G$ merges, each time relabeling the larger of the two joined labels with the smaller, and then numbers the remaining labels in order of first appearance. Both fits use the standardized duration and waiting measurements. This choice matters for the diagonal model because a covariance diagonal in the rotated axes can have a nonzero off-diagonal entry in the measurement axes.
The two initial groups contain 175 and 97 pairs. The function membership() turns their labels into two indicator columns. The first row is $(1,0)$ because groups are numbered in order of appearance. At the first M step the component proportions are $175/272$ and $97/272$, and each mean is the average of the standardized pairs in that group. The same centered rows give both first-step covariance estimates.
1
2
3
4
5
6
7
8
9
membership <- function(cl) 1*outer(cl,sort(unique(cl)),"==")
start <- membership(geyser_partition)
size <- colSums(start)
first_mean <- sweep(crossprod(start, scaled_geyser), 1L, size, "/")
first_full <- lapply(seq_along(size), function(k) {
residual <- sweep(scaled_geyser, 2L, first_mean[k, ], "-")
crossprod(residual * sqrt(start[, k])) / size[k]
})
first_diagonal <- lapply(first_full, function(S) diag(diag(S)))
Each weighted cross-product retains the sum of squared residuals on each diagonal and the sum of paired residual products off the diagonal. After division by the group size, the full model uses the whole covariance matrix. The diagonal model uses only the two variances. To take the next E step for the first pair, let $h_k$ be its normal density under the updated mean and covariance of component $k$. Its new component 1 probability is $175h_1/(175h_1+97h_2)$, and the remaining probability is assigned to component 2. The two covariance choices can give different probabilities even at this first E step. The following calculation evaluates both normal densities at the first pair and normalizes them separately for each fit. The normalization is mixture_estep() in code/lib/gaussian_mixture.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
mixture_estep <- function(lz, mixing_proportion) {
n <- nrow(lz); G <- ncol(lz)
huge_value <- .Machine$double.xmax
z <- lz
ll <- 0
for (i in 1:n) {
z_max <- -huge_value
for (k in 1:G) {
if (mixing_proportion[k] == 0) { z[i, k] <- 0 } else {
temp <- log(mixing_proportion[k]) + z[i, k]
z_max <- max(z_max, temp)
z[i, k] <- temp
}
}
total <- 0
for (k in 1:G) if (mixing_proportion[k] != 0) {
temp <- z[i, k] - z_max
if (temp >= -708) {
z[i, k] <- exp(temp)
total <- total + z[i, k]
} else z[i, k] <- 0
}
ll <- ll + (log(total) + z_max)
z[i, ] <- (1 / total) * z[i, ]
}
list(z = z, ll = ll)
}
Each entry of lz is a component log density. For person $i$ the function adds $\log\pi_k$, subtracts the largest term, exponentiates, sets terms below $e^{-708}$ and components with $\pi_k=0$ to zero, and divides by the row total; ll adds the logarithms of the row totals plus the largest terms, the log likelihood.
1
2
3
4
5
6
7
8
9
10
first_pair_membership <- function(covariance) {
log_density <- vapply(seq_along(size), function(k) {
S <- covariance[[k]]
d2 <- mahalanobis(scaled_geyser[1L, ], first_mean[k, ], S)
-log(2 * pi) - (log(det(S)) + d2) / 2
}, numeric(1))
mixture_estep(matrix(log_density, nrow = 1L), size / nrow(start))$z
}
next_full <- first_pair_membership(first_full)
next_diagonal <- first_pair_membership(first_diagonal)
Both EM routines repeat the weighted updates on scaled_geyser, starting from the same partition. The full-covariance routine is shown in two parts.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
mixture_em_full <- function(data, z, tol = 1e-5, eps = .Machine$double.eps,
max_iter = .Machine$integer.max, prior = NULL) {
x <- unname(as.matrix(data))
z <- unname(as.matrix(z))
n <- nrow(x); p <- ncol(x); G <- ncol(z)
huge_value <- .Machine$double.xmax
log_2pi_term <- p * 1.837877066409345 / 2
sqrt_eps <- sqrt(max(eps, 0))
ll_prev <- huge_value / 2
mu <- matrix(0, p, G)
U <- array(0, c(p, p, G))
mixing_proportion <- numeric(G)
iter <- 0
repeat {
iter <- iter + 1
z_total <- 1
for (k in 1:G) {
S <- if (is.null(prior)) matrix(0, p, p) else prior$scale_chol
m <- numeric(p)
z_sum <- 0
for (i in 1:n) {
temp <- z[i, k]
z_sum <- z_sum + temp
m <- m + temp * x[i, ]
}
mixing_proportion[k] <- z_sum / n
z_total <- min(z_sum, z_total)
if (z_sum > sqrt_eps) {
m <- (1 / z_sum) * m
for (i in 1:n) {
w <- x[i, ]
w <- w + (-1) * m
w <- sqrt(z[i, k]) * w
j <- 1
if (p > 1) for (j1 in 2:p) {
g <- gm_givens(S[j, j], w[j])
S[j, j] <- g[["r"]]; w[j] <- g[["z"]]
cols <- j1:p
a <- S[j, cols]; b <- w[cols]
S[j, cols] <- g[["c"]] * a + g[["s"]] * b
w[cols] <- g[["c"]] * b - g[["s"]] * a
j <- j1
}
g <- gm_givens(S[p, p], w[p])
S[p, p] <- g[["r"]]; w[p] <- g[["z"]]
}
if (is.null(prior)) {
for (j in 1:p) S[1:j, j] <- (1 / sqrt(z_sum)) * S[1:j, j]
} else {
# The prior mean enters as one more row; then the conjugate scaling and shrinkage.
w <- prior$mean + (-1) * m
const <- z_sum + prior$shrinkage
temp <- (z_sum * prior$shrinkage) / const
w <- sqrt(temp) * w
j <- 1
if (p > 1) for (j1 in 2:p) {
g <- gm_givens(S[j, j], w[j])
S[j, j] <- g[["r"]]; w[j] <- g[["z"]]
cols <- j1:p
a <- S[j, cols]; b <- w[cols]
S[j, cols] <- g[["c"]] * a + g[["s"]] * b
w[cols] <- g[["c"]] * b - g[["s"]] * a
j <- j1
}
g <- gm_givens(S[p, p], w[p])
S[p, p] <- g[["r"]]; w[p] <- g[["z"]]
for (j in 1:p) {
temp <- prior$dof + z_sum + p + 2
S[1:j, j] <- (1 / sqrt(temp)) * S[1:j, j]
}
m <- (z_sum / const) * m
m <- m + (prior$shrinkage / const) * prior$mean
}
} else {
z[1:p, k] <- huge_value
}
mu[, k] <- m
U[, , k] <- S
}
The first part is the M step. For component $k$, z_sum is $N_k$, mixing_proportion[k] is $N_k/n$ and m the weighted mean. Instead of forming $A_k$, the loop over people adds each row $\sqrt{\tau_{ik}}(x_i-m_k)$ to an upper triangular factor S with Givens rotations (gm_givens() returns the rotation that zeroes one entry), so that $S^\top S=A_k$; dividing by $\sqrt{N_k}$ makes $S^\top S=A_k/N_k=\hat\Sigma_k$. Section 12.6 describes the branch for a conjugate prior.
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
if (z_total <= sqrt_eps) return(list(loglik = NA, reason = "component_vanished", iterations = iter,
mixing_proportion = mixing_proportion, mean = mu, cholesky = U, z = z))
rc_min <- huge_value
for (k in 1:G) {
a <- abs(diag(U[, , k]))
rc_min <- min(min(a) / (1 + max(a)), rc_min)
}
if (rc_min <= sqrt_eps) return(list(loglik = NA, reason = "singular_covariance", iterations = iter,
mixing_proportion = mixing_proportion, mean = mu, cholesky = U, z = z))
for (k in 1:G) {
S <- U[, , k]
detlog <- 0
for (j in 1:p) detlog <- detlog + log(abs(S[j, j]))
const <- log_2pi_term + detlog
for (i in 1:n) {
w <- x[i, ] + (-1) * mu[, k]
for (j in 1:p) {
temp <- w[j]
if (j > 1) for (l in 1:(j - 1)) temp <- temp - S[l, j] * w[l]
w[j] <- temp / S[j, j]
}
z[i, k] <- -(const + gm_dot(w, w) / 2)
}
}
ll <- 0
for (i in 1:n) {
z_max <- -huge_value
for (k in 1:G) {
if (mixing_proportion[k] == 0) { z[i, k] <- 0 } else {
temp <- log(mixing_proportion[k]) + z[i, k]
z_max <- max(z_max, temp)
z[i, k] <- temp
}
}
total <- 0
for (k in 1:G) if (mixing_proportion[k] != 0) {
temp <- z[i, k] - z_max
if (temp >= -708) {
z[i, k] <- exp(temp)
total <- total + z[i, k]
} else z[i, k] <- 0
}
ll <- ll + (log(total) + z_max)
z[i, ] <- (1 / total) * z[i, ]
}
err <- abs(ll_prev - ll) / (1 + abs(ll))
ll_prev <- ll
if (!(err > tol && iter < max_iter)) break
}
sigma <- array(vapply(seq_len(G), function(k) crossprod(U[, , k]), numeric(p * p)), c(p, p, G))
# One covariance matrix per component, from its Cholesky factor.
list(loglik = ll, reason = if (iter >= max_iter) "iteration_limit" else "converged",
iterations = iter, error = err, mixing_proportion = mixing_proportion, mean = mu, cholesky = U, sigma = sigma, z = z)
}
The second part stops when a component’s $N_k$ falls to $\sqrt\epsilon$ or when the ratio of the smallest to one plus the largest absolute diagonal entry of a factor falls to $\sqrt\epsilon$. Otherwise it evaluates each log density as $-\tfrac p2\log(2\pi)-\sum_j\log\vert S_{jj}\vert -w^\top w/2$, where $w$ solves $S^\top w=x_i-\mu_k$ by forward substitution, and normalizes the rows as mixture_estep() does. The iterations end when the relative change of the log likelihood, $\vert \ell_{\mathrm{old}}-\ell\vert /(1+\vert \ell\vert )$, is at most tol, $10^{-5}$. The returned sigma contains $S^\top S$ for each component.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
mixture_em_diagonal <- function(data, z, tol = 1e-5, eps = .Machine$double.eps,
max_iter = .Machine$integer.max) {
x <- unname(as.matrix(data)); z <- unname(as.matrix(z))
n <- nrow(x); p <- ncol(x); G <- ncol(z)
huge_value <- .Machine$double.xmax
log_2pi <- 1.837877066409345
sqrt_eps <- sqrt(eps)
ll_prev <- huge_value / 2
mu <- matrix(0, p, G); shape <- matrix(0, p, G); scale <- numeric(G); mixing_proportion <- numeric(G)
iter <- 0
stop_with <- function(reason) list(loglik = NA, reason = reason, iterations = iter)
repeat {
iter <- iter + 1
z_total <- 1
for (k in 1:G) {
shape[, k] <- 0
m <- numeric(p)
total <- 0
for (i in 1:n) {
temp <- z[i, k]
total <- total + temp
m <- m + temp * x[i, ]
z[i, k] <- sqrt(temp)
}
mixing_proportion[k] <- total
z_total <- min(z_total, total)
if (total > sqrt_eps) {
m <- (1 / total) * m
for (j in 1:p) {
ss <- 0
for (i in 1:n) {
temp <- z[i, k] * (x[i, j] - m[j])
ss <- ss + temp * temp
}
shape[j, k] <- shape[j, k] + ss
}
}
mu[, k] <- m
}
if (z_total <= sqrt_eps) return(stop_with("component_vanished"))
eps_min <- huge_value
for (k in 1:G) {
shape_min <- min(shape[, k])
eps_min <- min(shape_min, eps_min)
if (shape_min <= 0) { scale[k] <- 0 } else {
temp <- 0
for (j in 1:p) temp <- temp + log(shape[j, k])
temp <- temp / p
if (temp > 709) return(stop_with("singular_covariance"))
temp <- if (temp > -708) exp(temp) else 0
scale[k] <- temp / mixing_proportion[k]
eps_min <- min(temp, eps_min)
if (temp <= eps) return(stop_with("singular_covariance"))
shape[, k] <- (1 / temp) * shape[, k]
}
}
mixing_proportion <- (1 / n) * mixing_proportion
if (eps_min <= eps) return(stop_with("component_vanished"))
if (min(scale) <= eps) return(stop_with("singular_covariance"))
for (k in 1:G) if (min(shape[, k]) <= eps) return(stop_with("singular_covariance"))
lz <- matrix(0, n, G)
for (k in 1:G) {
const <- p * (log_2pi + log(scale[k]))
for (i in 1:n) {
ss <- 0
for (j in 1:p) {
temp <- x[i, j] - mu[j, k]
ss <- ss + (temp * temp) / shape[j, k]
}
lz[i, k] <- -(const + (ss / scale[k])) / 2
}
}
e <- mixture_estep(lz, mixing_proportion)
z <- e$z
ll <- e$ll
err <- abs(ll_prev - ll) / (1 + abs(ll))
ll_prev <- ll
if (!(err > tol && iter < max_iter)) break
}
sigma <- array(vapply(seq_len(G), function(k) diag(scale[k] * shape[, k], p), numeric(p * p)), c(p, p, G))
# One diagonal covariance matrix per component.
list(loglik = ll, reason = if (iter >= max_iter) "iteration_limit" else "converged",
iterations = iter, error = err, mixing_proportion = mixing_proportion, mean = mu, scale = scale, shape = shape,
sigma = sigma, z = z)
}
The diagonal routine computes the same proportions and means and, for each axis $j$, the weighted sum of squares $a_{jk}$, the $j$th diagonal entry of $A_k$. It stores these as a scale, the geometric mean of the $a_{jk}$ divided by $N_k$, and a shape vector with product one, so that scale times shape is $a_{jk}/N_k$, the diagonal update above. Its E step uses mixture_estep(). The comparison reports the likelihood on both the standardized and original measurement scales.
1
2
3
4
5
6
7
8
9
10
11
12
full <- mixture_em_full(scaled_geyser,membership(geyser_partition))
diagonal <- mixture_em_diagonal(scaled_geyser,membership(geyser_partition))
gmm_model <- function(fit) list(mass=fit$mixing_proportion,mean=t(fit$mean),
covariance=lapply(seq_along(fit$mixing_proportion),function(k) fit$sigma[,,k]))
full$model <- gmm_model(full)
diagonal$model <- gmm_model(diagonal)
jacobian <- sum(log(attr(scaled_geyser,"scaled:scale")))
print(data.frame(model=c("full","diagonal"),
start_sizes=paste(table(geyser_partition),collapse="/"),
iterations=c(full$iterations,diagonal$iterations),
loglik_standardized=c(full$loglik,diagonal$loglik),
loglik_measured=c(full$loglik,diagonal$loglik)-nrow(geyser)*jacobian))
1
2
3
model start_sizes iterations loglik_standardized loglik_measured
1 full 175/97 3 -384.4590 -1130.264
2 diagonal 175/97 3 -402.0012 -1147.806
Both fits stopped after three iterations. Each routine stops for a relative log likelihood change $\vert \ell_{\rm old}-\ell\vert /(1+\vert \ell\vert )\le 10^{-5}$ or reports a failure if a component vanishes or its covariance becomes numerically singular. The stopping test measures an absolute relative change and can also accept a small likelihood decrease.
In mixture_em_full() the full covariance supplies an upper triangular Cholesky factor for computing the log determinant and the squared Mahalanobis distance. In mixture_em_diagonal() the two squared residuals are scaled by their respective variances.
Why does the comparison table give two log likelihoods for each fit? If $z_j=(y_j-\bar y_j)/s_j$, a rectangle of area $dy_1\,dy_2$ in the original measurements has area $dy_1\,dy_2/(s_1s_2)$ after standardization. Its probability is the same in either description. The density per unit area and the log likelihood for $n$ independent pairs therefore satisfy
\[f_Y(y)=\frac{f_Z(z)}{s_1s_2},\qquad \ell_Y=\ell_Z-n\log(s_1s_2).\]The sample standard deviations, 1.14137 and 13.59497 minutes, give $\log(s_1s_2)\approx2.741931$ per pair. The subtraction across 272 pairs is 745.8051. On the standardized scale the full and diagonal fits give $-384.4590$ and $-402.0012$. In minutes they give $-1130.264$ and $-1147.806$. On either scale the full fit gains about 17.54 log likelihood units by allowing a within-component covariance for each profile. Changing units shifts both log likelihoods by the same amount. The stored scalar jacobian is $\log\vert \det(\partial y/\partial z)\vert =\log(s_1s_2)$, not the Jacobian matrix. This change-of-units calculation treats the observed centering and scaling constants as fixed for evaluating both fitted densities.
The fitted profiles
The full fit attains the higher likelihood, so its components are examined here. In that fit, transposing fit$mean puts components in rows, so each mean can be read beside its mixing proportion, stored in mass, and its covariance.
1
print(full$model)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$mass
[1] 0.6440718 0.3559282
$mean
[,1] [,2]
[1,] 0.7026618 0.6673415
[2,] -1.2715053 -1.2075914
$covariance
$covariance[[1]]
[,1] [,2]
[1,] 0.13035532 0.06049512
[2,] 0.06049512 0.19491479
$covariance[[2]]
[,1] [,2]
[1,] 0.05317702 0.02811771
[2,] 0.02811771 0.18236419
The fitted within-component covariances are both positive, 0.06050 and 0.02812. Within either fitted component, longer eruptions are associated with longer subsequent waits. The first row of mean also puts both times above their sample means. To express the two mean times in minutes, multiply each fitted coordinate by its sample standard deviation and add its sample mean. The squared Mahalanobis distance uses the standardized residual $r$ of the first pair from each component mean and that component’s covariance $S$.
1
2
3
4
5
6
7
8
9
10
11
original_means <- sweep(sweep(full$model$mean,2,attr(scaled_geyser,"scaled:scale"),"*"),2,
attr(scaled_geyser,"scaled:center"),"+")
print(do.call(rbind,lapply(seq_along(full$model$mass),function(k) {
S <- full$model$covariance[[k]]
ev <- eigen(S,symmetric=TRUE,only.values=TRUE)$values
r <- drop(scaled_geyser[1,]-full$model$mean[k,])
data.frame(component=k,mixing_proportion=full$model$mass[k],
eruption=original_means[k,1],
waiting=original_means[k,2],min_eigenvalue=min(ev),max_eigenvalue=max(ev),
first_squared_Mahalanobis=drop(crossprod(r,solve(S,r))))
})))
1
2
3
4
5
6
component mixing_proportion eruption waiting min_eigenvalue max_eigenvalue
1 1 0.6440718 4.289781 79.96955 0.09406654 0.2312036
2 2 0.3559282 2.036523 54.47989 0.04732249 0.1882187
first_squared_Mahalanobis
1 3.063998
2 42.241058
The more frequent component, with proportion 0.64407, has mean eruption and waiting times of 4.2898 and 79.96955 minutes. The other, with proportion 0.35593, has means of 2.0365 and 54.47989 minutes. The eigenvalues are variances along each component’s principal directions on the standardized scale. Even the directions of least variation have positive variances, 0.094067 and 0.047322 respectively. Allowing for the spread and orientation of each component puts the first pair at squared distances of 3.0640 and 42.2411 from the two means.
For the first pair, how much of the fitted mixture density comes from each component? The shorter squared distance favors the first component. Each component’s contribution to the mixture density also depends on its covariance determinant and its mixing proportion. For squared distance $d_k^2$ and standardized covariance $S_k$, the component density is $\exp(-d_k^2/2)/(2\pi\sqrt{\vert S_k\vert })$. The function named gmm_log_emission() computes the class-conditional normal log density for each pair; here too, its name refers only to the conditional response calculation.
1
2
3
4
5
6
7
8
9
10
gmm_log_emission <- function(Y, model) {
out <- matrix(0, nrow(Y), length(model$mass))
for (k in seq_along(model$mass)) {
R <- chol(model$covariance[[k]])
centered <- sweep(Y, 2L, model$mean[k, ])
white <- forwardsolve(t(R), t(centered))
out[, k] <- -ncol(Y) / 2 * log(2 * pi) - sum(log(diag(R))) - colSums(white^2) / 2
}
out
}
With $R$ the upper Cholesky factor of $S_k$, white solves $R^\top w=y-\mu_k$, so colSums(white^2) is $d_k^2$ and sum(log(diag(R))) is $\tfrac12\log\vert S_k\vert $. The function mixture_posterior() (Section 12.1) combines these log densities with the log proportions. Element one selects the eruption lasting 3.60 minutes.
1
2
3
4
source("code/lib/mixtures.R")
common_log_density <- function(model)
mixture_posterior(gmm_log_emission(scaled_geyser,model),model$mass)$observation_loglik
common_log_density(full$model)[1L]
At that pair the two standardized component densities are about 0.2332204 and $1.1335\times10^{-9}$. Multiplying by their fitted proportions gives 0.1502107 and $4.0345\times10^{-10}$. Their sum has logarithm $-1.895716$. The same pair contributes $-1.895716-2.741931\approx-4.637647$ to the log likelihood in minutes. The supplied mixture EM and agglomeration functions are translated from the clustering and EM routines of the mclust package (code/NOTICE.md), which fits Gaussian mixtures with full or diagonal component covariances.
12.4 Mixture regression and covariates for class membership
How can the expected response change when neither of two regression lines moves? Suppose each of $n$ independently sampled people has one continuous response $y_i$, two observed covariates $x_i$ and $w_i$, and an unobserved class $C_i$. In class $k$ the response is normal with mean $\mu_{ik}=\beta_{0k}+\beta_{1k}x_i$ and residual standard deviation $\sigma_k$. The response intercept $\beta_{0k}$ is the mean at $x=0$ within that class. The response slope $\beta_{1k}$ is the change in that mean, in response units, for a one-unit increase in $x$. The residual variance $\sigma_k^2$ measures the remaining spread around the class’s line among people at the same $x$, in squared response units. It is constant over $x$ within a class but may differ between classes.
The covariate $w_i$ enters a separate regression for the probability of belonging to that class. Assume that class membership depends on $w_i$ alone once both covariates are given. Let $\pi_{ik}=P(C_i=k\mid x_i,w_i)=P(C_i=k\mid w_i)$ and write $v_i=(1,w_i)^\top$. The membership regression has its own coefficient vector $\gamma_k$ for each of $K$ classes. Taking class 1 as the reference fixes its intercept and slope at zero. The baseline-category multinomial logit gives
\[\log\frac{\pi_{ik}}{\pi_{i1}}=v_i^\top\gamma_k\quad(k=2,\ldots,K),\qquad \pi_{ik}=\frac{\exp(v_i^\top\gamma_k)} {\sum_{h=1}^K\exp(v_i^\top\gamma_h)},\qquad \gamma_1=0.\]These probabilities describe class membership before the response is observed. Write $\gamma_k=(\gamma_{0k},\gamma_{1k})^\top$. The membership intercept $\gamma_{0k}$ is the log probability ratio of class $k$ to class 1 at $w=0$. A one-unit increase in $w$ adds $\gamma_{1k}$ to that log ratio, multiplying the probability ratio by $\exp(\gamma_{1k})$. With more than two classes, a positive slope means that this ratio increases; the probability of class $k$ itself also depends on the slopes for the other classes. For two classes the ratio is the odds of class 2, and its probability is the inverse logit of its linear predictor.
The following simulation from the book directory uses a different intercept and slope for each response line. It generates 500 people, first drawing the two covariates and then drawing the class and response for each person.
1
2
3
4
5
6
7
8
9
10
11
12
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/mixtures.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(1204)
x <- rnorm(500); w <- rnorm(500)
state <- 1L + (runif(500) < plogis(-.3+.7*w))
response <- rnorm(500,ifelse(state==1L,-1+.5*x,2-.7*x),c(.6,.8)[state])
The two generating lines are $-1+0.5x$ and $2-0.7x$, with residual standard deviations 0.6 and 0.8. Increasing $x$ raises the first mean and lowers the second. Increasing $w$ raises the log odds of class 2 relative to class 1 by 0.7 per unit. The fit uses response, x and w. Only the simulation needs the class labels in state.
What does a person’s response add to the class probabilities? Conditional on the two covariates, the joint density for $y_i$ and class $k$ is the class probability $\pi_{ik}$ before observing the response, times the normal density at the recorded response. Summing over classes gives the observed response density $f_i$. Bayes’ formula then gives the E-step probability
\[f_i=\sum_{h=1}^K\pi_{ih}\,\phi(y_i;\mu_{ih},\sigma_h^2),\qquad \tau_{ik}=P(C_i=k\mid y_i,x_i,w_i) =\frac{\pi_{ik}\,\phi(y_i;\mu_{ik},\sigma_k^2)}{f_i}.\]The likelihood conditions on the covariates, so the sample log likelihood sums $\log f_i$ over people. For the first simulated person the generating parameters supply both terms of the ratio. The prior probability of class 2 depends on this person’s $w_i$ alone. The conditional densities use the two means at this person’s $x_i$. The word prior here qualifies class membership before observing $y_i$; it does not specify a prior distribution for the regression coefficients.
1
2
3
4
5
6
prior2 <- plogis(-.3 + .7 * w)
log_density <- cbind(
dnorm(response, -1 + .5 * x, .6, log = TRUE),
dnorm(response, 2 - .7 * x, .8, log = TRUE)
)
at_generating <- mixture_posterior(log_density, cbind(1 - prior2, prior2))
For the first row, $w_i=-1.278$ gives prior probability 0.2325 for class 2. At $x_i=-0.079$, the two means are about $-1.039$ and 2.055. The observed response, $-1.514$, is much closer to the first. Accounting for the two residual standard deviations gives at_generating$posterior[1, 2] of about 0.0000148. This calculation uses specified population parameters. An E step during fitting uses the estimates at that iteration.
Fixing the posterior probabilities gives a regression problem within each class. Write $u_i=(1,x_i)^\top$, let $X$ have rows $u_i^\top$, and put $r_{ik}=y_i-u_i^\top\beta_k$ and $N_k=\sum_i\tau_{ik}$. The Q function averages the complete-data log likelihood over the unknown class indicators. Up to a constant, class $k$ contributes the Gaussian term
\[Q_k=-\frac{N_k}{2}\log \sigma_k^2- \frac{1}{2\sigma_k^2}\sum_i\tau_{ik}r_{ik}^2.\]The derivative of $Q_k$ with respect to $\beta_k$ vanishes when $\sum_i\tau_{ik}u_i r_{ik}=0$. These are the least-squares normal equations for a design and response whose rows have been multiplied by $\sqrt{\tau_{ik}}$. Write $s=\sigma_k^2$. At the updated coefficients the derivative with respect to $s$ is $-N_k/(2s)+\sum_i\tau_{ik}r_{ik}^2/(2s^2)$. Setting it to zero gives the maximum likelihood (ML) residual variance $\sum_i\tau_{ik}r_{ik}^2/N_k$. The weighted QR calculation in mixreg_em() can be traced for class 1 using the probabilities just evaluated.
1
2
3
4
5
6
7
8
9
10
X <- cbind(1, x)
tau1 <- at_generating$posterior[, 1L]
root_tau <- sqrt(tau1)
weighted_qr <- qr(X * root_tau, tol = 1e-7, LAPACK = FALSE)
beta1 <- qr.coef(weighted_qr, response * root_tau)
active <- root_tau > 0
residual <- numeric(length(response))
residual[active] <- qr.resid(weighted_qr, response * root_tau)[active] / root_tau[active]
ml_variance <- sum(tau1 * residual^2) / sum(tau1)
adjusted_sd <- sqrt(ml_variance * nrow(X) / (nrow(X) - weighted_qr$rank))
The QR decomposition supplies the rank of the weighted design and the regression coefficients. Its residual is on the weighted response scale, so division by the square root of a positive weight recovers $r_{ik}$. If $\tau_{ik}=0$, that row contributes nothing to the residual sum of squares. The fitting routine divides each weighted squared residual by the mean weight $N_k/n$ and divides the sum by $n-\operatorname{rank}_k$. Its variance is therefore the ML value multiplied by $n/(n-\operatorname{rank}_k)$, and its reported standard deviation is the square root. With 500 rows and two linearly independent design columns that multiplier is $500/498$.
Because the adjusted variance can differ from the maximizer of $Q_k$, the usual EM argument does not guarantee an increase in the observed-data log likelihood at every iteration. This adjustment is not restricted maximum likelihood and does not by itself make the mixture variance estimator unbiased. The calculation also requires positive total class weight and positive residual degrees of freedom; rank deficiency can leave coefficients undetermined.
Updating the membership regression
The same posterior probabilities also determine the class-membership regression. If the class labels were observed, person $i$ would contribute $\log\pi_{ik}$ for the observed class. Taking the conditional expectation replaces each class indicator by $\tau_{ik}$. For free coefficients $\gamma_2,\ldots,\gamma_K$ and fixed $\gamma_1=0$, the membership part of the Q function is
\[Q_C(\gamma)=\sum_i\sum_k\tau_{ik}\log\pi_{ik}(\gamma) =\sum_i\left[\sum_{k=2}^K\tau_{ik}v_i^\top\gamma_k -\log\sum_{h=1}^K\exp(v_i^\top\gamma_h)\right].\]Each person supplies one multinomial observation divided among the classes in fractional amounts. Differentiating for class $k$ gives $\sum_i v_i(\tau_{ik}-\pi_{ik})$. To evaluate the negative membership Q function and its gradient at a zero start, fix the posterior probabilities above. Each of the two classes then has probability one half.
1
2
3
4
5
membership_design <- cbind(1, w)
fraction <- at_generating$posterior
probability_at_zero <- matrix(.5, nrow(fraction), 2L)
negative_q <- -sum(fraction * log(probability_at_zero))
gradient <- crossprod(membership_design, probability_at_zero - fraction)[, 2L]
At this start each person contributes $\log 2$ to the quantity being minimized. The two entries of gradient are the derivatives for the class 2 intercept and slope.
The supplied multinom_weights_fit() implements this membership fit. Its response matrix Y contains the fractions and its design matrix contains the intercept and membership covariate. It reconstructs the zero coefficient column for the reference class and subtracts the largest linear predictor in each row before exponentiating. Its function fn sums negative log class probabilities weighted by Y, giving the negative membership part of the Q function. For a row with total one, its gradient uses the fitted fractions minus the supplied fractions. For a grouped row, gr multiplies the fitted probabilities by the row total before subtracting the supplied counts.
The function passes the negative membership Q function and its gradient to bfgs() with zero starting values on each call. The inner optimization allows up to 100 iterations with absolute tolerance $10^{-4}$ and relative tolerance $10^{-8}$. BFGS denotes the Broyden-Fletcher-Goldfarb-Shanno quasi-Newton method. The outer mixture routine uses the returned coefficients without checking whether this inner fit met its stopping criterion.
For positive finite probabilities, fn and its gradient give the stated criterion and derivative. If a class probability becomes numerically zero despite a positive entry in Y, the implementation returns the fixed value 1000 from fn while retaining the ordinary gradient formula; those two quantities no longer describe the same function.
A zero partial derivative for one membership slope need not give a zero Newton increment for that slope. Consider a constructed three-class example. At $w=-1,0,1$ the expected class counts are $(6,3,1)$, $(3,4,3)$ and $(1,3,6)$ respectively. Start with all coefficients zero. Each row of ten then has fitted counts $(10/3,10/3,10/3)$. Across the three rows the fitted and supplied totals agree at ten for each class. Both partial derivatives of the membership Q function with respect to the free intercepts vanish. The block of its negative Hessian coupling intercepts and slopes is also zero here because the probabilities are constant and the row totals times $w$ sum to zero.
For each slope, the corresponding derivative weights each count discrepancy by $w$. The middle row drops out, giving $3-3=0$ for class 2 and $6-1=5$ for class 3.
At equal probabilities each free class indicator has variance $(1/3)(2/3)=2/9$. The two indicators have covariance $0-(1/3)^2=-1/9$ because a person belongs to only one class. For the negative Hessian of the slopes, each row multiplies this covariance matrix by its count $n_i$ and by $w_i^2$. Since $\sum_i n_i w_i^2=20$, the slope equations for one Newton step are
\[\frac{1}{9} \begin{pmatrix}40&-20\\-20&40\end{pmatrix} \begin{pmatrix}\Delta_2\\\Delta_3\end{pmatrix} =\begin{pmatrix}0\\5\end{pmatrix}.\]The code evaluates the membership criterion before and after this joint step. The local block evaluates three covariate settings separately from the simulated sample. In membership_q(), logsumexp() supplies the log denominator for each row. In the block, q_slope_gradient and negative_q_slope_hessian are the right side and the matrix of the slope equations, and slope is their solution $(\Delta_2,\Delta_3)$.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
local({
w <- c(-1, 0, 1)
counts <- rbind(c(6, 3, 1), c(3, 4, 3), c(1, 3, 6))
membership_q <- function(slope) {
eta <- cbind(0, outer(w, slope))
sum(counts * (eta - apply(eta, 1, logsumexp)))
}
probability <- matrix(1 / 3, 3, 3)
q_slope_gradient <- colSums(w * (counts - rowSums(counts) * probability))[2:3]
negative_q_slope_hessian <- sum(rowSums(counts) * w^2) * (diag(2) / 3 - 1 / 9)
slope <- solve(negative_q_slope_hessian, q_slope_gradient)
updated <- exp(c(0, slope)) / sum(exp(c(0, slope)))
print(list(q_slope_gradient = q_slope_gradient, negative_q_slope_hessian = negative_q_slope_hessian, slope_change = slope,
q_before = membership_q(c(0, 0)), q_after = membership_q(slope),
probability_at_w1 = updated))
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$q_slope_gradient
[1] 0 5
$negative_q_slope_hessian
[,1] [,2]
[1,] 4.444444 -2.222222
[2,] -2.222222 4.444444
$slope_change
[1] 0.75 1.50
$q_before
[1] -32.95837
$q_after
[1] -29.04564
$probability_at_w1
[1] 0.1316016 0.2786007 0.5897977
The first equation requires $\Delta_2=\Delta_3/2$. Thus both slopes rise, by 0.75 and 1.50, while the intercepts remain at zero for this step. At $w=1$ the three updated probabilities are proportional to $1$, $\exp(0.75)$ and $\exp(1.50)$. The membership Q function increases from $-32.95837$ to $-29.04564$. Both slopes enter the same logit denominator, so a change in the class 3 slope also changes the fitted probabilities for class 2.
Fitting the simulated mixture regression
The response and membership updates now combine in one EM routine. For the 500 simulated people, mixreg_em() fits two response lines and models the log odds of class 2 relative to class 1. The call uses the random stream after the seed-1204 data draws. Each iteration fits the membership regression and the two response regressions, then recalculates the posterior class probabilities. The routine is mixreg_em() in code/lib/mixtures.R.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
mixreg_em <- function(y, X, W, k = 2L, cluster = NULL, maxit = 200L, tolerance = 1e-6,
min_prior = 0.05) {
X <- unname(as.matrix(X)); W <- unname(as.matrix(W))
N <- length(y)
if (is.null(cluster)) cluster <- sample(seq_len(k), size = N, replace = TRUE)
component_ids <- seq_len(k)
post <- matrix(0.1, N, k)
for (K in seq_len(k)) post[cluster == K, K] <- 0.9
row_log_sum_exp <- function(m) {
pick <- max.col(m, "first"); M <- m[cbind(seq_along(pick), pick)]
M + log(rowSums(exp(m - M)))
}
# Starting weights: the starting posteriors normalized on the log scale.
post_scaled <- exp(log(post) - row_log_sum_exp(log(post)))
ll_best <- -Inf
converged <- FALSE
history <- numeric(0)
for (iter in seq_len(maxit)) {
prior <- multinom_weights_fit(W, post_scaled)$fitted
nok <- which(colMeans(prior) < min_prior)
if (length(nok)) {
keep <- setdiff(seq_len(k), nok)
if (!length(keep)) stop("all components removed below the minimum prior")
component_ids <- component_ids[keep]
prior <- prior[,keep,drop=FALSE]
prior <- prior / rowSums(prior)
post_scaled <- post_scaled[,keep,drop=FALSE]
empty <- rowSums(post_scaled) == 0
post_scaled[empty,] <- prior[empty,,drop=FALSE]
post_scaled <- post_scaled / rowSums(post_scaled)
k <- length(keep)
}
components <- lapply(seq_len(k), function(K) {
w <- post_scaled[, K]
wts <- sqrt(w)
decomposition <- qr(X * wts, tol = 1e-7, LAPACK = FALSE)
coef <- qr.coef(decomposition, y * wts)
residuals <- numeric(N)
active <- wts > 0
residuals[active] <- qr.resid(decomposition, y * wts)[active] / wts[active]
dof <- nrow(X) - decomposition$rank; list(coef = coef, sigma = sqrt(sum(w * residuals^2 / mean(w)) / dof))
})
lpu <- matrix(sapply(components, function(cc) dnorm(y, mean = X %*% cc$coef, sd = cc$sigma,
log = TRUE)), nrow = N)
lpu <- log(prior) + lpu
post_scaled <- exp(lpu - row_log_sum_exp(lpu))
llh_old <- ll_best
ll_best <- sum(row_log_sum_exp(lpu))
history <- c(history, ll_best)
if (abs(ll_best - llh_old) / (abs(ll_best) + 0.1) < tolerance) { converged <- TRUE; break }
}
membership_fit <- multinom_weights_fit(W, post_scaled)
density <- matrix(vapply(components,function(cc)
dnorm(y,drop(X %*% cc$coef),cc$sigma,log=TRUE),numeric(N)),nrow=N)
final_joint <- density + log(membership_fit$fitted)
final_loglik <- row_log_sum_exp(final_joint)
final_posterior <- exp(final_joint - final_loglik)
returned_loglik <- sum(final_loglik)
list(model = list(beta = do.call(cbind,lapply(components,`[[`,"coef")), sd = sapply(components, `[[`, "sigma"),
membership_coefficients = membership_fit$coefficients), component_ids=component_ids, loglik = ll_best, returned_loglik=returned_loglik, posterior = final_posterior,
last_estep_posterior = post_scaled, iterations = iter,
converged = converged, reason = if (converged) "converged" else "iteration_limit",
history = history, cluster_start = cluster)
}
Without cluster, each person is assigned a random component, which receives starting weight 0.9 and each other component 0.1 before the rows are normalized. In each iteration multinom_weights_fit() fits the multinomial membership regression on $W$ to the current posterior probabilities and returns each person’s fitted class probabilities in prior; min_prior is the cutoff of 0.05 for removing a component, described below. Each response regression is weighted least squares with weights $\tau_{ik}$, computed by the QR decomposition of the rows multiplied by $\sqrt{\tau_{ik}}$, and its standard deviation is the square root of $\sum_i\tau_{ik}r_{ik}^2/\bar\tau_k$ divided by $n$ minus the rank. The E step adds the log prior probabilities to the normal log densities and normalizes each row with row_log_sum_exp() (Section 4.7). The loop stops when the relative change of the log likelihood, divided by its absolute value plus 0.1, is below tolerance. The membership regression is then refitted to the last posterior probabilities, and returned_loglik and posterior are recomputed with it.
1
2
3
4
reg <- mixreg_em(response,cbind(1,x),cbind(1,w))
print(c(iterations=reg$iterations,converged=reg$converged,
last_E_loglik=reg$loglik,returned_loglik=reg$returned_loglik,
start_sizes=tabulate(reg$cluster_start,2)))
1
2
3
4
iterations converged last_E_loglik returned_loglik start_sizes1
20.000 1.000 -789.628 -789.628 260.000
start_sizes2
240.000
The routine assigns each row to a random starting class, gives that class a starting membership fraction of 0.9 and the other a fraction of 0.1, and normalizes each row. The initial assignment put 260 people in class 1 and 240 in class 2. Both components survived.
The outer stopping rule is $\vert \ell-\ell_{\rm old}\vert /(\vert \ell\vert +0.1)<10^{-6}$, with a limit of 200 iterations. This run met the rule at iteration 20. Its last E step gave $-789.62802219$. The routine then fitted the membership coefficients once more to those posterior probabilities, with both response regressions and standard deviations fixed. The log likelihood evaluated at the returned coefficients is $-789.62801010$. Both appear as $-789.628$ at the precision of the printout.
On each iteration the BFGS membership fit first converts the current fractions into prior probabilities conditional on $w$. A component whose mean prior probability over people is below 0.05 is removed. The routine retains the original identifiers of surviving components and renormalizes their prior probabilities and current membership fractions within each row. The 0.05 cutoff is a chosen deletion rule, not a test that the population proportion is zero. If a class is removed, both the number of components and the reference class used by subsequent membership regressions must be tracked.
The weighted QR regressions then update the response coefficients and residual standard deviations. Adding the logarithms of these prior probabilities to the resulting normal log densities gives lpu in the supplied implementation. The logarithm of the sum of the exponentiated entries in each row is that person’s contribution to the observed-data log likelihood, and subtracting these row values before exponentiating gives the next posterior probabilities.
The fitted population parameters are in reg$model. Its fields separate the response regressions from the class-membership regression.
| Field | Model quantity |
|---|---|
beta[, k] | Response intercept and slope $(\beta_{0k},\beta_{1k})^\top$ for class $k$ |
sd[k] | Residual standard deviation $\sigma_k$, with the stated variance adjustment |
membership_coefficients[, k-1] | Coefficients $\gamma_k$ of class $k$ relative to class 1, for $k>1$ |
Each row of a coefficient matrix follows its own supplied design: cbind(1,x) for the response and cbind(1,w) for membership. The reference vector $\gamma_1=0$ is omitted from membership_coefficients. The stored reg$posterior contains probabilities recalculated at the returned reg$model. The separate last_estep_posterior retains the probabilities preceding the extra membership-coefficient fit. Both describe membership conditional on observed responses.
For a new person whose $x$ and $w$ are known, each fitted line supplies one conditional mean. Before the response is observed, the conditional means are averaged with the fitted class probabilities given $w$. The predicted marginal mean is $\sum_k\pi_k(w)\mu_k(x)$. Crossing two values of each covariate varies one with the other fixed.
1
2
3
4
5
6
7
8
9
setting <- expand.grid(x=c(-1,1),w=c(-1,1))
# Rows are covariate settings; columns give the fitted mean for each class.
means <- cbind(1,setting$x) %*% reg$model$beta
second_class_probability <- plogis(drop(cbind(1,setting$w) %*%
reg$model$membership_coefficients))
print(data.frame(setting,first_mean=means[,1],second_mean=means[,2],
second_class_probability=second_class_probability,
marginal_mean=(1-second_class_probability)*means[,1]+
second_class_probability*means[,2]))
1
2
3
4
5
x w first_mean second_mean second_class_probability marginal_mean
1 -1 -1 -1.4589839 2.593407 0.2907695 -0.28067240
2 1 -1 -0.4351065 1.232297 0.2907695 0.04972339
3 -1 1 -1.4589839 2.593407 0.5797373 0.89033818
4 1 1 -0.4351065 1.232297 0.5797373 0.53154920
In rows 1 and 3, $x=-1$ fixes the two component means at $-1.4590$ and 2.5934. Raising $w$ from $-1$ to 1 increases the probability of class 2 from 0.2908 to 0.5797. More probability on the higher line raises the marginal mean from $-0.2807$ to 0.8903. In rows 2 and 4, at $x=1$, the two means are $-0.4351$ and 1.2323. The same change in class probabilities now raises the marginal mean from 0.0497 to 0.5315. At each value of $x$ the change in marginal mean equals the probability shift times the gap between the two fitted lines. That gap is smaller at $x=1$. Once the response is observed, its density under each line also informs the person’s posterior class probabilities. These comparisons describe the fitted conditional associations and marginal means; a causal interpretation requires assumptions beyond this mixture specification.
The supplied mixreg_em() reproduces, with parts adapted, the EM of the flexmix package for this model (code/NOTICE.md), which fits mixture regressions with covariates for class membership.
12.5 Starting partitions, k-means implementation, and different fitted mixtures
Two analysts fit the same mixture to the same observations. If both runs meet their stopping rules, what would tell them whether they returned the same fitted distribution? The starting memberships determine which observations contribute most to each component’s first parameter update. In the three-class questionnaire fit, seed 1202 fixed the random item tables. Dividing the independent uniform draws for each item and class by their sum gives starting category probabilities. Together with equal class proportions, they determine each respondent’s first posterior class probabilities.
For the two continuous measurements in faithful, the hierarchy supplied a partition. For a k-means start, two distinct measurement pairs are drawn as centers. Seed 1205 fixes the sequence for a single run, a best-of-five search and five further runs. The following setup standardizes the measurements and converts a vector of group labels into a membership matrix. Each row represents one observation, with a one in its assigned class column and zeros elsewhere.
1
2
3
4
5
6
7
8
9
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/mixtures.R")
source("code/lib/gaussian_mixture.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
geyser <- as.matrix(datasets::faithful)
scaled_geyser <- scale(geyser)
membership <- function(cl) 1*outer(cl,sort(unique(cl)),"==")
The k-means criterion
How does k-means decide which observations belong together? Its criterion is the total within-cluster sum of squares about the group means, also called centroids. Here a cluster is a group formed by partitioning the measurements; it is not an observed sampling cluster or an inferred latent class. For fixed centers, assigning each point to the nearest center minimizes its contribution to the criterion. For fixed assignments, differentiating a group’s sum of squares with respect to a proposed center $a$ gives $2n(a-c)$, where $c$ is the group mean. Thus the group mean minimizes its sum of squares.
Moving one point changes two such means. Within a group, expanding $\sum_i\lVert x_i-c\rVert^2$ gives $\sum_i\lVert x_i\rVert^2-n\lVert c\rVert^2$. Removing $x$ from group $h$ changes its centroid to $(n_hc_h-x)/(n_h-1)$, while adding $x$ to group $k$ gives $(n_kc_k+x)/(n_k+1)$. Substituting these centroids into the sum of squares gives the reduction and the increase, respectively,
\[R_h=\frac{n_h}{n_h-1}\lVert x-c_h\rVert^2\quad(n_h>1),\qquad A_k=\frac{n_k}{n_k+1}\lVert x-c_k\rVert^2.\]For example, if $n_h=3$ and the squared distance to $c_h$ is 0.8, removal saves 1.2. If $n_k=5$ and the squared distance to $c_k$ is 1.2, addition costs 1.0. Transferring the point lowers the total by 0.2.
In the supplied Hartigan-Wong routine kmeans_hw(), n_ratio1 and n_ratio2 contain the removal and addition multipliers. The optimal-transfer stage searches eligible destinations and moves the point when the smallest addition cost is below the removal saving. Each transfer updates both centroids, both counts and their multipliers. A point in a singleton group is not reassigned. The quick-transfer stage rechecks the point against its stored alternative when its current group or that alternative has recently changed. With two groups there is only one alternative per point. Optimal transfer is the algorithm’s name for this stage of considering individual moves; it does not certify the best partition among all possible partitions.
Euclidean distance on these standardized measurements combines two differences expressed in sample standard deviations. Two eruptions one sample standard deviation apart in duration and identical in waiting time have squared distance one. A difference of one standard deviation in waiting time contributes the same amount.
For a survey item on travel mode, coding bus, train and car as 1, 2 and 3 gives bus and car a squared distance of four. Interchanging the codes for train and car reduces it to one while preserving every answer. The questionnaire model can use the category probabilities directly. K-means is used here only to construct starting groups. Its sum-of-squares criterion is different from the observed-data likelihood subsequently used to fit the mixture.
Two partitions of 33 points
To see how different partitions can persist through EM, consider 33 fixed measurements along a line. Nine run from $-6.4$ to $-5.6$, eleven from $-0.4$ to $0.4$, and thirteen from 4.6 to 5.4, equally spaced within each set. A two-component normal mixture must describe these three sets with two means and two variances. The left_apart partition gives the first nine points their own component and pools the other 24. The right_apart partition pools the first 20 points and sets the last 13 apart.
1
2
3
4
cloud <- matrix(c(seq(-6.4,-5.6,length.out=9),seq(-.4,.4,length.out=11),
seq(4.6,5.4,length.out=13)),ncol=1)
cloud_partitions <- list(left_apart=c(rep(1,9),rep(2,24)),
right_apart=c(rep(1,20),rep(2,13)))
Both fits start with definite assignments. After the first weighted mean and variance updates, each point can contribute to either component according to its posterior probability. The fits use mixture_em_univariate() in code/lib/gaussian_mixture.R.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
mixture_em_univariate <- function(data, z, tol = 1e-5, eps = .Machine$double.eps,
max_iter = .Machine$integer.max) {
x <- as.numeric(data); z <- unname(as.matrix(z))
n <- length(x); G <- ncol(z)
huge_value <- .Machine$double.xmax
log_2pi <- 1.837877066409345
sqrt_eps <- sqrt(eps)
ll_prev <- huge_value / 2
mu <- numeric(G); sigma_sq <- numeric(G); mixing_proportion <- numeric(G)
iter <- 0
repeat {
iter <- iter + 1
z_total <- 1
for (k in 1:G) {
total <- 0; sum_mu <- 0
for (i in 1:n) {
temp <- z[i, k]
total <- total + temp
sum_mu <- sum_mu + temp * x[i]
}
mixing_proportion[k] <- total / n
z_total <- min(total, z_total)
if (total > sqrt_eps) {
sum_mu <- sum_mu / total
mu[k] <- sum_mu
sigma_sq_k <- 0
for (i in 1:n) {
temp <- x[i] - sum_mu
temp <- temp * temp
sigma_sq_k <- sigma_sq_k + z[i, k] * temp
z[i, k] <- temp
}
sigma_sq[k] <- sigma_sq_k / total
}
}
if (z_total <= sqrt_eps) return(list(loglik = NA, reason = "component_vanished", iterations = iter))
if (min(sigma_sq) <= eps) return(list(loglik = NA, reason = "singular_covariance", iterations = iter,
mean = mu, variance = sigma_sq, mixing_proportion = mixing_proportion))
for (k in 1:G) {
const <- log_2pi + log(sigma_sq[k])
z[, k] <- -(const + (z[, k] / sigma_sq[k])) / 2
}
e <- mixture_estep(z, mixing_proportion)
z <- e$z
ll <- e$ll
err <- abs(ll_prev - ll) / (1 + abs(ll))
ll_prev <- ll
if (!(err > tol && iter < max_iter)) break
}
list(loglik = ll, reason = if (iter >= max_iter) "iteration_limit" else "converged",
iterations = iter, error = err, mixing_proportion = mixing_proportion, mean = mu, variance = sigma_sq, z = z)
}
Its M step is the calculation of univariate_gaussian_mstep() in Section 4.1, and its E step applies mixture_estep() above to the normal log densities. It stops when a component’s expected count falls to $\sqrt\epsilon$, when a variance falls to $\epsilon$, or when the relative change of the log likelihood is at most $10^{-5}$.
The fitted means show which points each fit groups together. Sorting the two means within each run makes their comparison independent of the component labels. Sorting means alone is enough for this display; a comparison of complete parameter sets must apply the same permutation to proportions, variances and posterior columns.
1
2
3
4
basins <- lapply(cloud_partitions,function(cl) mixture_em_univariate(cloud,membership(cl)))
print(do.call(rbind,lapply(basins,function(f) c(means=sort(f$mean),loglik=f$loglik,
min_variance=min(f$variance),smallest_expected_class_size=min(colSums(f$z)),
iterations=f$iterations))))
1
2
3
4
5
6
means1 means2 loglik min_variance
left_apart -6.000160 2.704205 -75.99203 0.06662752
right_apart -2.650775 5.000724 -72.72116 0.06194648
smallest_expected_class_size iterations
left_apart 8.988034 2
right_apart 12.867764 3
The first run takes two iterations and puts the means near $-6.0002$ and 2.7042. The second takes three and puts them near $-2.6508$ and 5.0007. Their smallest variances are 0.06663 and 0.06195, and their smallest expected counts are 8.988 and 12.868. Each column of f$z contains one component’s posterior probabilities for all 33 points. Their sum is that component’s expected count, and min(colSums(f$z)) picks the smaller of the two.
The narrow component is near $-6$ in the first fit and near 5 in the second. Each fit assigns appreciable membership to both components and estimates positive variances. These are distinct returned fits without a vanishing class or a collapsed variance; these checks alone do not establish that either is a local likelihood maximum. Isolating the rightmost set gives the higher observed-data log likelihood, $-72.72116$ compared with $-75.99203$.
Random starts for the geyser data
Returning to the standardized geyser data, seed 1205 fixes the sequence of random centers. The first partition starts a two-component fit with full covariances.
The supplied k-means routine has a default outer limit of ten passes and returns a fault code when a transfer or iteration limit is reached. An empty group after the initial assignments triggers an error. The routine is kmeans_hw() in code/lib/mixtures.R, the Hartigan-Wong algorithm of kmeans(), shown in four parts.
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
kmeans_hw <- function(x, centers, max_iter = 10L, nstart = 1L) {
x <- unname(as.matrix(x))
M <- nrow(x); N <- ncol(x)
big_value <- 1.0000000150474662e+30
one_run <- function(C) {
K <- nrow(C)
imax <- as.integer(min(.Machine$integer.max, 50 * M))
best_c <- integer(M); second_c <- integer(M); D <- numeric(M)
for (i in 1:M) {
best_c[i] <- 1L; second_c[i] <- 2L
dt <- numeric(2)
for (l_idx in 1:2) for (j in 1:N) { diff_a <- x[i, j] - C[l_idx, j]; dt[l_idx] <- dt[l_idx] + diff_a * diff_a }
if (dt[1] > dt[2]) { best_c[i] <- 2L; second_c[i] <- 1L; dt <- dt[2:1] }
if (K >= 3) for (l in 3:K) {
db <- 0
skip <- FALSE
for (j in 1:N) {
diff_c <- x[i, j] - C[l, j]
db <- db + diff_c * diff_c
if (db >= dt[2]) { skip <- TRUE; break }
}
if (skip) next
if (db >= dt[1]) { dt[2] <- db; second_c[i] <- l } else {
dt[2] <- dt[1]; second_c[i] <- best_c[i]; dt[1] <- db; best_c[i] <- l
}
}
}
nc <- integer(K)
C[] <- 0
for (i in 1:M) { l <- best_c[i]; nc[l] <- nc[l] + 1L; C[l, ] <- C[l, ] + x[i, ] }
if (any(nc == 0)) stop("empty cluster: try a better set of initial centers")
n_ratio1 <- numeric(K); n_ratio2 <- numeric(K); updated_c <- integer(K); last_step <- integer(K); live_until <- integer(K)
for (l in 1:K) {
n_l <- nc[l]
C[l, ] <- C[l, ] / n_l
n_ratio2[l] <- n_l / (n_l + 1)
n_ratio1[l] <- if (n_l > 1) n_l / (n_l - 1) else big_value
updated_c[l] <- 1L
last_step[l] <- -1L
}
transfer <- function(i, l1, l2) {
n_l1 <- nc[l1]; n_minus <- n_l1 - 1; n_l2 <- nc[l2]; n_plus <- n_l2 + 1
for (j in 1:N) {
C[l1, j] <<- (C[l1, j] * n_l1 - x[i, j]) / n_minus
C[l2, j] <<- (C[l2, j] * n_l2 + x[i, j]) / n_plus
}
nc[l1] <<- nc[l1] - 1L; nc[l2] <<- nc[l2] + 1L
n_ratio2[l1] <<- n_minus / n_l1
n_ratio1[l1] <<- if (n_minus > 1) n_minus / (n_minus - 1) else big_value
n_ratio1[l2] <<- n_plus / n_l2
n_ratio2[l2] <<- n_plus / (n_plus + 1)
best_c[i] <<- l2; second_c[i] <<- l1
}
The first part assigns each point to its nearest center and records the second nearest in second_c, then replaces each center by the mean of its points. Moving point $x_i$ from cluster $l_1$, of size $n_1$, to cluster $l_2$, of size $n_2$, changes the within-cluster sum of squares by $\tfrac{n_2}{n_2+1}\Vert x_i-c_{l_2}\Vert ^2-\tfrac{n_1}{n_1-1}\Vert x_i-c_{l_1}\Vert ^2$; n_ratio1 and n_ratio2 contain the two size factors, with a very large number in place of the first for a cluster of one point. The function transfer() moves a point and updates both centers, sizes and factors.
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
n_since <- 0L
fault <- 0L
converged <- FALSE
for (ij in 1:max_iter) {
# Optimal-transfer stage.
for (l in 1:K) if (updated_c[l] == 1L) live_until[l] <- M + 1L
for (i in 1:M) {
n_since <- n_since + 1L
l1 <- best_c[i]; l2 <- second_c[i]; ll <- l2
if (nc[l1] != 1L) {
if (last_step[l1] != 0L) {
de <- 0
for (j in 1:N) { df <- x[i, j] - C[l1, j]; de <- de + df * df }
D[i] <- de * n_ratio1[l1]
}
diff_a <- 0
for (j in 1:N) { db <- x[i, j] - C[l2, j]; diff_a <- diff_a + db * db }
r2 <- diff_a * n_ratio2[l2]
for (l in 1:K) {
if ((i >= live_until[l1] && i >= live_until[l]) || l == l1 || l == ll) next
rr <- r2 / n_ratio2[l]
diff_c <- 0
out <- FALSE
for (j in 1:N) {
diff_d <- x[i, j] - C[l, j]
diff_c <- diff_c + diff_d * diff_d
if (diff_c >= rr) { out <- TRUE; break }
}
if (out) next
r2 <- diff_c * n_ratio2[l]
l2 <- l
}
if (r2 >= D[i]) {
second_c[i] <- l2
} else {
n_since <- 0L
live_until[l1] <- M + i; live_until[l2] <- M + i
last_step[l1] <- i; last_step[l2] <- i
transfer(i, l1, l2)
}
}
if (n_since == M) break
}
if (n_since == M) { converged <- TRUE; break }
for (l in 1:K) { updated_c[l] <- 0L; live_until[l] <- live_until[l] - M }
In the optimal-transfer stage, D[i] is the reduction from removing $x_i$ from its cluster and r2 the smallest increase from adding it to another cluster. The point moves when r2 is below D[i]. Clusters changed during the last $M$ steps are in the live set (live_until), and a point is compared with a cluster outside the live set only when its own cluster is live. A full pass of $M$ points without a move ends the fit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# Quick-transfer stage.
n_quiet <- 0L; n_steps <- 0L
done <- FALSE
repeat {
for (i in 1:M) {
n_quiet <- n_quiet + 1L
n_steps <- n_steps + 1L
if (n_steps >= imax) { fault <- 4L; done <- TRUE; break }
l1 <- best_c[i]; l2 <- second_c[i]
if (nc[l1] != 1L) {
if (n_steps <= last_step[l1]) {
diff_a <- 0
for (j in 1:N) { db <- x[i, j] - C[l1, j]; diff_a <- diff_a + db * db }
D[i] <- diff_a * n_ratio1[l1]
}
if (n_steps < last_step[l1] || n_steps < last_step[l2]) {
r2 <- D[i] / n_ratio2[l2]
diff_d <- 0
out <- FALSE
for (j in 1:N) {
de <- x[i, j] - C[l2, j]
diff_d <- diff_d + de * de
if (diff_d >= r2) { out <- TRUE; break }
}
if (!out) {
n_quiet <- 0L; n_since <- 0L
updated_c[l1] <- 1L; updated_c[l2] <- 1L
last_step[l1] <- n_steps + M; last_step[l2] <- n_steps + M
transfer(i, l1, l2)
}
}
}
if (n_quiet == M) { done <- TRUE; break }
}
if (done) break
}
if (fault == 4L) break
if (K == 2) { converged <- TRUE; break }
last_step[] <- 0L
}
if (!converged && fault == 0L) { fault <- 2L; ij <- max_iter + 1L }
# Recompute the centers and the within-cluster sums of squares from the final partition.
C[] <- 0
within <- numeric(K)
for (i in 1:M) C[best_c[i], ] <- C[best_c[i], ] + x[i, ]
for (j in 1:N) {
for (l in 1:K) C[l, j] <- C[l, j] / nc[l]
for (i in 1:M) { diff_a <- x[i, j] - C[best_c[i], j]; within[best_c[i]] <- within[best_c[i]] + diff_a * diff_a }
}
list(cluster = best_c, centers = C, within_ss = within, size = nc, iter = ij, fault = fault)
}
The quick-transfer stage considers only each point’s two recorded clusters and repeats until $M$ consecutive steps produce no move; more than $50M$ steps give fault 4. Reaching max_iter passes without convergence gives fault 2. The centers and within-cluster sums of squares are then recomputed from the final assignments.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if (length(centers) == 1L) {
k <- centers
cn <- NULL
# One start by default; the set of distinct rows supplies further and repeated starts.
C <- if (nstart == 1L) x[sample.int(M, k), , drop = FALSE]
if (any(duplicated(C)) || nstart >= 2L) {
cn <- unique(x)
C <- cn[sample.int(nrow(cn), k), , drop = FALSE]
}
} else {
C <- as.matrix(centers)
cn <- NULL
k <- nrow(C)
}
storage.mode(C) <- "double"
Z <- one_run(C)
best <- sum(Z$within_ss); extra <- if (nstart >= 2L && !is.null(cn)) seq_len(nstart - 1L) else integer(0)
for (i in extra) {
trial <- one_run(cn[sample.int(nrow(cn), k), , drop = FALSE]); trial_ss <- sum(trial$within_ss)
if (trial_ss < best) { Z <- trial; best <- trial_ss }
}
Z$total_within_ss <- best
Z
}
With a number of clusters in centers, the start draws that many rows at random, from the distinct rows when the draw contains duplicates or when nstart is two or more. Further starts are drawn from the distinct rows, and the run with the smallest total within-cluster sum of squares is returned.
1
2
3
4
set.seed(1205)
km <- kmeans_hw(scaled_geyser,2L)
kmeans_fit <- mixture_em_full(scaled_geyser,membership(km$cluster))
print(kmeans_fit[c("iterations","loglik","reason")])
1
2
3
4
5
6
7
8
$iterations
[1] 4
$loglik
[1] -384.459
$reason
[1] "converged"
That fit met the relative-change stopping rule in four iterations.
Continuing the random sequence, the best-of-five k-means call retains the partition with the smallest total within-cluster sum of squares. Five further calls each pass a single partition to EM. The saved hierarchical fit full supplies the comparison on the same data and covariance model.
1
2
3
4
5
6
7
8
9
10
11
12
13
full <- readRDS("data/derived/ch12/fits.rds")$geyser
km_best <- kmeans_hw(scaled_geyser,2L,nstart=5L)
random_fits <- lapply(seq_len(5L),function(i) {
part <- kmeans_hw(scaled_geyser,2L)
list(partition=part,fit=mixture_em_full(scaled_geyser,membership(part$cluster)))
})
print(data.frame(start=c("hierarchical","k-means","k-means best of 5",
paste0("k-means run ",1:5)),
within_ss=c(NA,km$total_within_ss,km_best$total_within_ss,
vapply(random_fits,function(r) r$partition$total_within_ss,0)),
loglik=c(full$loglik,kmeans_fit$loglik,
mixture_em_full(scaled_geyser,membership(km_best$cluster))$loglik,
vapply(random_fits,function(r) r$fit$loglik,0))))
1
2
3
4
5
6
7
8
9
start within_ss loglik
1 hierarchical NA -384.459
2 k-means 79.2834 -384.459
3 k-means best of 5 79.2834 -384.459
4 k-means run 1 79.2834 -384.459
5 k-means run 2 79.2834 -384.459
6 k-means run 3 79.2834 -384.459
7 k-means run 4 79.2834 -384.459
8 k-means run 5 79.2834 -384.459
The eleven internal k-means starts comprise one, then five, then five more. Seven partitions are used as EM starting assignments because only the winner of the best-of-five call is retained. Each of those seven has a reported within-cluster sum of squares of 79.2834. The NA in the hierarchical row means that k-means supplied no sum of squares for that start. All eight EM runs reach a log likelihood of $-384.459$ at the displayed precision.
For a given model and dataset, the comparison records the starting rule, any random seed, convergence status and attained log likelihood for every EM run. Among runs meeting the stopping rule without boundary or covariance failures, the preferred run has the highest attained observed-data log likelihood. For the 33 fixed points this selects right_apart by about 3.27 log likelihood units. For the geyser fits, comparing the estimated profiles also requires aligning their component labels.
This selection identifies the highest finite likelihood among the examined admissible fits. Another start can return a higher value, and the unrestricted normal-mixture likelihood can be unbounded, so a global maximum need not exist.
The supplied kmeans_hw() is translated from the Hartigan-Wong algorithm (AS 136) and the start-up of kmeans() in the stats package (code/NOTICE.md), and mclust fits Gaussian mixtures.
12.6 Identification, boundary probabilities, degenerate covariances, and label switching
Suppose two analysts report different proportions for class 1. Do their questionnaire models predict different response patterns? Write $f_k(y)$ for the probability of the six answers $y$ given class $k$, and $\pi_k$ for its proportion. For any permutation $s$ of the class indices, the marginal probability satisfies
\[\sum_{k=1}^3\pi_{s(k)}f_{s(k)}(y)=\sum_{k=1}^3\pi_k f_k(y).\]Label switching refers here to permutation of the class labels, which reorders the same three products without changing the distribution. A model is identifiable up to labels if every parameter vector giving the same response distribution can be obtained by such a permutation. If two classes have identical item probabilities, their combined proportion multiplies one common profile. Even with fixed labels, any division of that proportion gives the same response distribution.
The label symmetry can be checked numerically on the LCA6 questionnaires. From the book directory, recreate the 600 questionnaires with seed 1201. Each column of success specifies one class’s six yes probabilities.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
source("code/lib/mixtures.R")
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1201)
lca_mass <- c(.3,.4,.3)
success <- cbind(c(.10,.15,.10,.15,.10,.15),
c(.85,.80,.85,.15,.10,.15),
c(.85,.90,.85,.85,.90,.85))
simulate_lca <- function(n, pi, probability) {
state <- sample.int(length(pi),n,replace=TRUE,prob=pi)
response <- matrix(runif(n*nrow(probability)),n) < t(probability[,state,drop=FALSE])
list(Y=1*response,state=state)
}
lca_input <- simulate_lca(600L,lca_mass,success)
Y <- lca_input$Y
The calculation first evaluates all 64 patterns at the generating values and fits the model to Y with seed 1202. Reversing the class columns and their proportions then tests the same symmetry at both sets of parameters.
1
2
3
4
5
6
7
8
9
10
11
patterns <- as.matrix(expand.grid(setNames(rep(list(0:1),6L), paste0("indicator_",1:6))))
patterns_fit <- mixture_posterior(lca_log_emission(patterns,success),lca_mass)
set.seed(1202)
lca_fit <- lca_em(Y,3L)
reversed <- lapply(lca_fit$model$probability,function(p) p[,
rev(seq_len(ncol(p))),drop=FALSE])
print(c(max_pattern_change=max(abs(patterns_fit$observation_loglik -
mixture_posterior(lca_log_emission(patterns,success[,3:1]),
rev(lca_mass))$observation_loglik)),
same_fitted_loglik=mixture_posterior(lca_log_emission(Y,reversed),
rev(lca_fit$model$mass))$loglik))
1
2
max_pattern_change same_fitted_loglik
8.881784e-16 -1.919502e+03
Across the 64 patterns, the largest absolute change in a generating log probability was about $8.9\times10^{-16}$, consistent with rounding when the sum is evaluated in reverse order. The second number uses the observed answers in Y and the estimated probabilities. The reversed fit gave the same total log likelihood of $-1919.502$ as the original fit.
To compare the questionnaire profiles across fits, match columns by their item response probabilities and apply the same permutation to the proportions. A high probability of yes across all six items describes the same response profile whether it appears in the first or the third column. Marginal pattern probabilities and the total log likelihood can be compared directly because their calculation sums over classes. The reversal of the questionnaire columns verifies this symmetry.
Boundary probabilities
Identification can also fail at the edge of the parameter space. A zero mixing proportion removes a class from every response-pattern probability. A zero item probability excludes that class only for patterns containing that response category. Consider first a mixing proportion. With $\pi_1>0$ fixed, the log odds $\log(\pi_k/\pi_1)$ tend to $-\infty$ as $\pi_k$ tends to zero. With $\pi_k>0$ fixed, they tend to $+\infty$ as the reference proportion $\pi_1$ tends to zero.
For an item success probability $\theta$, the logit is $\log\lbrace \theta/(1-\theta)\rbrace $, with limits $-\infty$ at zero and $+\infty$ at one. Set the first item’s success probability to zero in class 1. What happens for a respondent who answers yes only to that item?
1
2
3
4
5
6
at_boundary <- success
at_boundary[1,1] <- 0
pattern <- matrix(c(1,0,0,0,0,0),nrow=1)
print(data.frame(class=1:3,first_success=at_boundary[1,],
posterior=drop(mixture_posterior(lca_log_emission(pattern,at_boundary),
lca_mass)$posterior)))
1
2
3
4
class first_success posterior
1 1 0.00 0.000000000
2 2 0.85 0.998704104
3 3 0.85 0.001295896
The class 1 term is zero despite its proportion of 0.30. In each of the other classes, the first yes has probability 0.85. The five no answers distinguish them. Including the mixing proportions, the joint probabilities for the observed pattern are 0.00663255 for class 2 and 0.00000860625 for class 3. Dividing each by their sum gives the posterior probabilities in the table. A respondent who answered no to the first question could still belong to class 1.
An unbounded likelihood for normal mixtures
For a continuous response, concentrating a component on one observation can increase the likelihood without bound. Take the same 33 measurements in three groups along the real line. In this two-component normal mixture, the narrow component has mean $x_1=-6.4$, the first observation, standard deviation $\sigma$ and mixing proportion 0.1. The other component has mean zero, variance 25 and mixing proportion 0.9. Write $\phi(x;\mu,v)$ for the normal density with mean $\mu$ and variance $v$. At the first observation the mixture density is
\[g_\sigma(x_1)=\frac{0.1}{\sqrt{2\pi}\,\sigma}+0.9\,\phi(x_1;0,25).\]At each other point $x_i$, the mixture density is at least $0.9\,\phi(x_i;0,25)>0$ for every $\sigma$. The sum of the other 32 log densities therefore has a finite lower bound, while $\log g_\sigma(x_1)$ tends to positive infinity. The five fixed standard deviations below show how the data log likelihood changes along this path.
1
2
3
4
5
6
7
8
cloud <- matrix(c(seq(-6.4,-5.6,length.out=9),seq(-.4,.4,length.out=11),
seq(4.6,5.4,length.out=13)),ncol=1)
scales <- 10^(-c(1,2,4,8,16))
print(data.frame(sd=scales,
first_point_density=.1*dnorm(cloud[1],cloud[1],scales)+.9*dnorm(cloud[1],0,5),
loglik=vapply(scales,function(s) mixture_posterior(cbind(
dnorm(cloud,cloud[1],s,log=TRUE),
dnorm(cloud,0,5,log=TRUE)),c(.1,.9))$loglik,0.0)))
1
2
3
4
5
6
sd first_point_density loglik
1 1e-01 4.305948e-01 -94.10083
2 1e-02 4.021075e+00 -95.09109
3 1e-04 3.989739e+02 -90.49374
4 1e-08 3.989423e+06 -81.28348
5 1e-16 3.989423e+14 -62.86280
Narrowing the first component from 0.1 to 0.01 reduced its contribution to the mixture density at neighboring observations enough for the total to fall from $-94.10$ to $-95.09$. The next three totals rose to $-90.49$, $-81.28$ and $-62.86$. At $\sigma=10^{-16}$ the narrow component’s density at its center is about $3.99\times10^{15}$. Its mixing proportion explains why the displayed mixture density there is about $3.99\times10^{14}$. The limiting argument concerns arbitrarily small scales and allows the initial decrease.
Recognizing covariance collapse in mixture fits
In a fitted mixture, examine which observations contribute to a large increase in the log likelihood. If $\tau_{ik}$ is the current posterior probability of class $k$ for observation $i$, then $N_k=\sum_i\tau_{ik}$ is its expected class size. A component concentrated on one or two observations can have a small $N_k$. In several dimensions, a small eigenvalue of its covariance indicates little spread along the corresponding direction, even if each variable separately has appreciable variance. Inspect those eigenvalues on comparable measurement scales. If the log likelihood rises sharply while an eigenvalue approaches zero, inspect the observations with high posterior probability for that component. Concentration on just a few observations can account for the gain. A small expected count by itself also occurs for a genuinely rare response profile. A zero eigenvalue is a singular limit outside the positive definite covariance model.
The first two rows of the standardized faithful data give an example in two dimensions. Put both in class 1 and all other rows in class 2. Relative to their common mean, the first two rows have deviations $d$ and $-d$. Their sample covariance with divisor two is $dd^\top$, of rank at most one. Compare this start with the partition from the hierarchy, fitting each with and without a conjugate prior.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/gaussian_mixture.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
geyser <- as.matrix(datasets::faithful)
scaled_geyser <- scale(geyser)
geyser_hc <- mixture_agglomerate(scaled_geyser)
geyser_partition <- mixture_agglomerate_partition(geyser_hc,2)
membership <- function(cl) 1*outer(cl,sort(unique(cl)),"==")
full <- mixture_em_full(scaled_geyser,membership(geyser_partition))
# The first class contains two observations in the two-dimensional response space.
tiny <- c(1,1,rep(2,nrow(scaled_geyser)-2))
singular <- mixture_em_full(scaled_geyser,membership(tiny))
For component $k$, let $\bar y_k$ be its mean weighted by posterior class probabilities and $T_k=\sum_i\tau_{ik}(y_i-\bar y_k)(y_i-\bar y_k)^\top$ its weighted scatter. Write $p$ for the number of measurements and $G$ for the number of components. The conjugate prior is normal for each component mean given its covariance matrix and inverse Wishart for that covariance matrix.
Here mixture_conjugate_prior() takes the overall mean $m_0$, a positive constant $c=0.01$ controlling the prior variance of each component mean (called shrinkage in the function), degrees of freedom $\nu=p+2$ and scale matrix $S_0=(1/G)^{2/p}S_y$, where $S_y$ is the sample covariance of the standardized pairs. Specifically, the conditional prior covariance of the component mean is $\Sigma_k/c$, and the inverse-Wishart log density contains $-\operatorname{tr}(S_0\Sigma_k^{-1})/2$.
The updates with the prior target the joint posterior mode of the mean and covariance, not the posterior mean or the marginal mode of the covariance. These prior settings depend on the observed data. With $\delta_k=\bar y_k-m_0$, the two updates are
\[\begin{aligned} \mu_k^{\rm ML}&=\bar y_k, & \Sigma_k^{\rm ML}&=T_k/N_k,\\ \mu_k^{\rm prior}&=(N_k\bar y_k+c m_0)/(N_k+c), & \Sigma_k^{\rm prior}&= \frac{S_0+T_k+[N_k c/(N_k+c)]\,\delta_k\delta_k^\top} {N_k+\nu+p+2}. \end{aligned}\]For the first class of tiny, both assigned observations have membership probability one. Use these rows to compare the two covariance updates. The default conjugate prior comes from mixture_conjugate_prior() in code/lib/gaussian_mixture.R.
1
2
3
4
5
6
mixture_conjugate_prior <- function(data, G) {
p <- ncol(data)
covariance <- if (nrow(data) <= p) diag(apply(data,2,var),nrow=p,ncol=p) else var(data)
list(shrinkage = 0.01, mean = colMeans(data), dof = p + 2,
scale_chol = chol((1 / G)^(2 / p) * covariance))
}
In the returned list, shrinkage is $c$, mean is $m_0$, dof is $\nu$ and scale_chol is the upper Cholesky factor of $S_0$; when there are no more rows than columns, $S_y$ is replaced by the diagonal matrix of sample variances.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
first_class <- scaled_geyser[tiny == 1, , drop = FALSE]
n_k <- nrow(first_class)
m <- colMeans(first_class)
scatter <- crossprod(sweep(first_class, 2L, m))
ml_covariance <- scatter / n_k
prior <- mixture_conjugate_prior(scaled_geyser, 2)
c0 <- prior$shrinkage
delta <- m - prior$mean
prior_covariance <- (crossprod(prior$scale_chol) + scatter +
(n_k * c0 / (n_k + c0)) * tcrossprod(delta)) /
(n_k + prior$dof + ncol(first_class) + 2)
# Check the Cholesky factor returned at the end of the unpenalized M step.
a <- abs(diag(singular$cholesky[,,1]))
singular_first <- min(a) / (1 + max(a)) <= sqrt(.Machine$double.eps)
The Cholesky factor that mixture_em_full() builds from the weighted deviations (Section 12.3) starts from zero without the prior. With the prior it starts from scale_chol, the Cholesky factor of $S_0$, and includes one further row proportional to $\delta_k$ before dividing by the square root of the new divisor. The positive definite $S_0$ supplies spread in the direction missing from the two centered rows.
The routine checks each Cholesky factor before computing a normal density. If its smallest absolute diagonal divided by one plus its largest absolute diagonal is at most the square root of machine epsilon, the routine reports singular_covariance. The two-point component meets this condition. That protection requires a positive definite prior scale; forming scale_chol can itself fail if the sample covariance used to construct it is singular. Compare the stopping records for all four fits.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fit_with_conjugate_prior <- mixture_em_full(scaled_geyser,membership(tiny),
prior=mixture_conjugate_prior(scaled_geyser,2))
hierarchical_fit_with_conjugate_prior <-
mixture_em_full(scaled_geyser,membership(geyser_partition),
prior=mixture_conjugate_prior(scaled_geyser,2))
print(data.frame(start=c("two-point class","two-point class","hierarchical",
"hierarchical"),
prior=c("none","conjugate","none","conjugate"),
reason=c(singular$reason,fit_with_conjugate_prior$reason,
full$reason,hierarchical_fit_with_conjugate_prior$reason),
iterations=c(singular$iterations,
fit_with_conjugate_prior$iterations,full$iterations,
hierarchical_fit_with_conjugate_prior$iterations),
loglik=c(singular$loglik,fit_with_conjugate_prior$loglik,
full$loglik,hierarchical_fit_with_conjugate_prior$loglik)))
1
2
3
4
5
start prior reason iterations loglik
1 two-point class none singular_covariance 1 NA
2 two-point class conjugate converged 21 -384.7040
3 hierarchical none converged 3 -384.4590
4 hierarchical conjugate converged 4 -384.7045
The two-point start stopped at the first unpenalized M step, before a log likelihood could be computed. Its row therefore shows NA. The unpenalized hierarchical fit met its stopping rule in three iterations. With the prior, the two-point start met the same rule in 21 iterations and the hierarchy in four. Their values of $-384.7040$ and $-384.7045$ can be read on the same data scale as the unpenalized hierarchical value of $-384.4590$.
With the conjugate prior, the M step maximizes the expected complete-data log likelihood plus the log prior density, so the intended target is a maximum a posteriori (MAP) estimate of the component parameters. The convergence check still uses the relative change in the observed-data log likelihood, and the table reports that likelihood at the resulting estimates. The reported likelihoods omit the log prior. They compare density fit to the same data, but neither rank the penalized objective nor establish that its maximum has been reached; that objective and its stopping diagnostics need separate evaluation.
The mclust package fits Gaussian mixtures with a conjugate prior on the component parameters.
12.7 Comparing numbers of classes with AIC and BIC
Would a fourth response profile help explain the answers to the six questionnaire items? Adding a class gives the model more ways to assign probability to the observed patterns. To judge whether the gain warrants the extra parameters, fit each candidate to the same respondents. Let $\ell$ denote the observed-data log likelihood at the fitted parameters, $p$ the number of free parameters and $n$ the number of independent respondents. The Akaike information criterion (AIC) and the Bayesian information criterion (BIC) are
\[\mathrm{AIC}=-2\ell+2p,\qquad \mathrm{BIC}=-2\ell+p\log n.\]For each criterion, a smaller value is preferred because the increase in twice the maximized log likelihood offsets more of the parameter penalty. With 600 respondents, each additional parameter costs 2 units of AIC and $\log(600)\approx6.40$ units of BIC. Each person supplies one joint response pattern. Its probability contributes once to the likelihood, so the sample size for BIC is the number of questionnaires.
How many parameters does another profile add? In a locally independent model for six dichotomous items, each class needs six success probabilities. Once a success probability is specified, its complement gives the probability of a no answer on that item. For $K$ classes, choosing $K-1$ mixing proportions determines the last one because the proportions sum to one. The count is $p=(K-1)+6K$. Moving from one through four classes gives 6, 13, 20 and 27 free parameters.
For comparison, a Gaussian mixture for $d$ measurements with a separate unrestricted covariance matrix in each class needs $d$ means, $d$ variances and $d(d-1)/2$ distinct covariances per class. Its parameter count is $(K-1)+K\lbrace d+d(d+1)/2\rbrace $. Thus two classes for two continuous measurements require eleven parameters, whereas two classes for the six dichotomous items require thirteen. These are the nominal counts for the specified models. Zero class proportions or identical component distributions can destroy identification; substituting the counts into AIC or BIC does not remove that problem.
Fitting one to four classes
The rows of Y contain the answers of the 600 simulated respondents. From the book directory, load the responses and lca_em(). Fit one through four classes, using eight starts for each model with more than one class. Set seed 1207 once so that successive runs use successive draws. In the code, K is the number of classes and k is the parameter count.
1
2
3
4
5
6
7
8
9
10
11
12
13
source("code/lib/mixtures.R")
Y <- readRDS("data/source/ch12/LCA6.rds")
RNGkind("Mersenne-Twister","Inversion","Rejection")
set.seed(1207)
class_search <- lapply(1:4,function(K) {
best <- lca_em(Y,K,n_starts=if (K==1L) 1L else 8L)
k <- (K-1L)+K*ncol(Y)
ll <- best$loglik
list(best=best,row=data.frame(K=K,k=k,attempted=length(best$attempts),
converged=best$converged,iterations=best$iterations,loglik=ll,
AIC=-2*ll+2*k,BIC=-2*ll+k*log(nrow(Y))))
})
print(do.call(rbind,lapply(class_search,function(x)x$row)))
1
2
3
4
5
K k attempted converged iterations loglik AIC BIC
1 1 6 1 TRUE 1 -2349.635 4711.271 4737.652
2 2 13 8 TRUE 61 -2057.069 4140.138 4197.298
3 3 20 8 TRUE 62 -1919.502 3879.005 3966.943
4 4 27 8 FALSE 1000 -1915.492 3884.984 4003.701
With one class, lca_em() calculates the six observed proportions of yes answers directly. These are the maximum likelihood estimates. The ones under attempted and iterations record this single evaluation, which requires no random start. For each larger model, the function sets the initial class proportions equal, draws uniform random numbers for each item’s class-by-category table and divides each class row by its sum. It retains whichever of its eight runs ends with the highest log likelihood. The criteria and convergence status in that row refer to this same run. Selection uses the terminal likelihood without first excluding runs that failed to meet the gain tolerance.
The log likelihood increased at each successive class count. For three classes, the gain in observed-data log likelihood fell below the tolerance of $10^{-10}$ at iteration 62. For four classes, the gain in the retained run still exceeded that tolerance at iteration 1,000. Its log likelihood and criteria describe the estimates at that stopping point.
The code calculates the criteria before rounding the log likelihood. For three classes, $\ell\approx-1919.50228457$ and $p=20$, giving $-2\ell+40\approx3879.005$ for AIC and $-2\ell+20\log(600)\approx3966.943$ for BIC. Moving from three classes to four improved the log likelihood by about 4.01, reducing $-2\ell$ by about 8.02. That gain falls short of both additional penalties, 14 for AIC and $7\log(600)\approx44.78$ for BIC. Both criteria therefore select three classes among these four fitted candidates. The ranking concerns the runs obtained from these starts, including the unfinished four-class fit. Further optimization of the unfinished fit can change its criteria, so the displayed ranking is provisional.
How many respondents does each retained class represent? For each retained fit, sum the membership probabilities evaluated at the returned parameters down each class column to obtain its expected number of respondents. For example, a respondent with a posterior membership probability of 0.8 contributes 0.8 to that class total.
1
print(lapply(class_search,function(x) colSums(x$best$posterior)))
1
2
3
4
5
6
7
8
9
10
11
[[1]]
[1] 600
[[2]]
[1] 199.5923 400.4077
[[3]]
[1] 176.6068 179.6588 243.7344
[[4]]
[1] 185.9872 129.9291 108.9629 175.1207
The expected sizes show how membership is distributed across the fitted profiles. In the two-class fit, they were 199.59 and 400.41 respondents. With three classes, they were 176.61, 179.66 and 243.73, and with four they were 185.99, 129.93, 108.96 and 175.12. In each fit, they sum to 600 before rounding because each person’s posterior probabilities sum to one.
How much did the random starts differ for the same class count? The entries of start_logliks give the final log likelihoods in run order. The second quantity is the smallest conditional probability of any response category across all items and classes in the retained fit.
1
2
print(lapply(class_search,function(x) list(start_logliks=x$best$attempts,
smallest_probability=min(unlist(x$best$model$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
25
26
27
28
29
30
31
32
33
[[1]]
[[1]]$start_logliks
[1] -2349.635
[[1]]$smallest_probability
[1] 0.3466667
[[2]]
[[2]]$start_logliks
[1] -2057.069 -2057.069 -2057.069 -2057.069 -2057.069 -2057.069 -2057.069
[8] -2057.069
[[2]]$smallest_probability
[1] 0.06460622
[[3]]
[[3]]$start_logliks
[1] -1919.502 -1919.502 -1919.502 -1919.502 -1919.502 -1919.502 -1919.502
[8] -1919.502
[[3]]$smallest_probability
[1] 0.06639469
[[4]]
[[4]]$start_logliks
[1] -1915.492 -1915.492 -1916.831 -1915.492 -1916.138 -1915.492 -1915.492
[8] -1915.492
[[4]]$smallest_probability
[1] 1.759706e-138
At the printed precision, all eight two-class runs ended at $-2057.069$ and all eight three-class runs at $-1919.502$. Assign ll3 <- class_search[[3]]$best$attempts. Then which.max(ll3) gives 7, and -diff(sort(ll3,decreasing=TRUE)[1:2]) gives its lead over start 8, only $3.18\times10^{-12}$. The fitted likelihoods are practically tied, although the unrounded values determine which run supplies the row.
At four classes, the eighth run was retained. Six runs ended at $-1915.492$ to three decimals. Starts 3 and 5 ended at $-1916.831$ and $-1916.138$. In the retained four-class fit, row 1 and column 3 of class_search[[4]]$best$model$probability[[3]] give a probability of about $1.76\times10^{-138}$ for a no answer on item 3 in class 3. For one, two and three classes, the smallest conditional category probabilities were about 0.347, 0.0646 and 0.0664. The four-class estimate is close to the boundary for this particular answer at the iteration limit. Even the class with the near-zero item probability has an expected size of about 109.
Could the drop in $-2\ell$ be compared with a chi-square distribution on seven degrees of freedom to test for the extra class? Under a three-class model, a four-class representation can give the additional class a mixing proportion of zero. That value lies on the boundary of the allowed proportions. Multiplication by zero removes its response profile from every pattern probability. Its six item probabilities are unidentified under the null hypothesis because any values for them give the same likelihood. The usual chi-square calibration of the likelihood ratio statistic requires regular, identified parameters and does not apply here. The poLCA package fits latent class models for categorical responses.
12.8 Nonparametric maximum likelihood with mass point updates and directional derivatives
Three of the 80 simulated clusters in GLMM80 recorded eight failures in eight trials. How much can those response patterns reveal about the lower tail of the intercept distribution? Each cluster has eight observations at known covariate values. The normal random-intercept model describes variation between clusters with a mean and a variance.
Suppose instead that, independently of the covariate design, the cluster-specific intercept has distribution $G=\sum_{k=1}^K\pi_k\delta_{a_k}$, where $\delta_{a_k}$ places probability one at $a_k$, $K$ counts the mass points, and the nonnegative masses $\pi_k$ sum to one. Nonparametric maximum likelihood estimation (NPMLE) of the mixing distribution does not fix its number of support points in advance. A discrete fitted distribution is represented by the intercept values $a_k$ (mass points or support points) and their probabilities $\pi_k$. Estimating the finite-dimensional slope $\beta$ alongside the unspecified distribution $G$ makes the whole model semiparametric; discreteness of the estimate does not establish that the population has finitely many types. The intercept is shared within a cluster, and the slope $\beta$ is common to all clusters.
Given intercept $a$, write $p_{ij}(a)=\operatorname{logit}^{-1}(a+\beta x_{ij})$ for the probability of success at covariate $x_{ij}$ on observation $j$ in cluster $i$. Thus $a$ is the cluster’s log odds of success at $x=0$. Within a cluster, a one-unit increase in $x$ adds $\beta$ to the log odds and multiplies the odds by $\exp(\beta)$. The masses $\pi_k$ describe the population distribution of these baseline log odds across clusters. Conditional independence within a cluster gives the following probability for its observed response pattern $y_i$. Averaging over its unknown intercept gives its marginal probability, and independent clusters give the sample log likelihood
\[f_i(a)=\prod_j p_{ij}(a)^{y_{ij}}\{1-p_{ij}(a)\}^{1-y_{ij}},\qquad L_i=\sum_k\pi_k f_i(a_k),\qquad \ell(G,\beta)=\sum_{i=1}^N\log L_i.\]The sample log likelihood is a sum of $N=80$ independent cluster terms. In the normal model, the cluster-specific intercept is the sum of a population intercept and a centered random effect. In the discrete model, each mass point is already a cluster-specific intercept. Adding a separate constant to the linear predictor would allow an equal shift of all locations in the opposite direction.
From the book directory, read the observed outcomes, cluster identifiers and covariates. The function rilogit_data() in code/lib/npmle.R prepares these observations for the grouped likelihood calculation.
1
2
3
4
5
6
rilogit_data <- function(x) {
groups <- sort(x[, 1])
# Attributes ui (the group labels in increasing order) and gi (the number of rows of
# each group).
structure(x, ui = unique(groups), gi = tabulate(groups))
}
It returns the matrix with two attributes: the cluster labels in increasing order (ui) and the number of rows of each cluster (gi). The columns of its returned matrix grouped identify the cluster, the number of successes, the number of trials and the covariate. Each row represents one trial. Here location means the intercept value at which probability mass is placed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/result.R")
source("code/lib/logit.R")
source("code/lib/line_search.R")
source("code/lib/quasi_newton.R")
source("code/lib/newton.R")
source("code/lib/glm.R")
source("code/lib/npmle.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
glmm_observed <- readRDS("data/source/ch09/GLMM80-binary.rds")
grouped <- rilogit_data(cbind(group=as.integer(factor(glmm_observed$id)),
yi=glmm_observed$y,ni=1,x1=glmm_observed$x))
Updating masses and choosing support points
Given a cluster’s responses, the joint probability of its pattern and intercept $a_k$ is $\pi_k f_i(a_k)$. Dividing by $L_i$ gives the posterior mass-point probability $\tau_{ik}$. A mass update also needs to assess a possible location whose current mass is zero. Set $S_{ik}=f_i(a_k)/L_i$, so that $\tau_{ik}=\pi_k S_{ik}$. A new location can have a large ratio even though its current posterior probability is zero. The entries of $S$ are likelihood ratios and need not lie between zero and one; they are not posterior probabilities. With the locations and the common slope fixed, replace the current mass vector $\pi$ by a trial vector $q$ with nonnegative entries that sum to one. For cluster $i$, the ratio of its trial probability to its current probability is $(Sq)_i$. Since $(S\pi)_i=1$, the exact change in log likelihood and its quadratic approximation around $\pi$ satisfy
\[\begin{aligned} \ell(q)-\ell(\pi)&=\sum_i\log (Sq)_i,\\ u_i&=(Sq)_i-1,\\ \sum_i\log(1+u_i)&\ \approx\ \sum_i(u_i-\tfrac12 u_i^2) =\tfrac N2-\tfrac12\lVert Sq-2\mathbf1\rVert^2 . \end{aligned}\]Here $\mathbf1$ is the vector of $N$ ones. Maximizing the quadratic amounts to minimizing that squared residual subject to the constraints on $q$. Each cluster enters the least-squares problem once, with weight one. The quadratic is only a local approximation, so a proposed mass update must also be checked against the actual log likelihood. A proposed step can give zero mass to a location and thereby reduce the number of points.
Which location should enter that calculation? With the common slope still fixed, put a fraction $\epsilon$ of the population at a trial location $a$, multiplying every existing mass by $1-\epsilon$. Under $G_\epsilon=(1-\epsilon)G+\epsilon\delta_a$, the marginal probability of cluster $i$ becomes $(1-\epsilon)L_i+\epsilon f_i(a)$. Dividing by $L_i$ and differentiating the log at $\epsilon=0$ from the right gives the directional derivative
\[D_G(a)=\left.\frac{d}{d\epsilon}\ell(G_\epsilon,\beta)\right|_{0+} =\sum_{i=1}^N\left\{\frac{f_i(a)}{L_i}-1\right\}.\]A cluster with $f_i(a)>L_i$ contributes a positive term to $D_G(a)$ because the trial intercept predicts its response pattern better than the current mixture does. A positive sum means that a sufficiently small transfer to $a$ improves the log likelihood. For the negative mean log likelihood, the derivative of the same transfer is $-D_G(a)/N$. At fixed slope the log likelihood is concave in $G$, since each cluster probability is linear in $G$ and the logarithm is concave. For any trial distribution $H$, the directional derivative toward $H$ is the average of $D_G(a)$ under $H$. Concavity gives $\ell(H,\beta)-\ell(G,\beta)\leq\int D_G(a)\,dH(a)$. If $D_G(a)\leq0$ everywhere, the gain toward any $H$ is therefore nonpositive. Together with the possibility of improving at any point where the derivative is positive, this characterizes a maximizing distribution at this slope. Moreover,
\[\sum_k\pi_kD_G(a_k)=\sum_i\left\{\frac{\sum_k\pi_k f_i(a_k)}{L_i}-1\right\}=0.\]At an exact maximum, each location with positive mass must therefore have derivative zero. A numerical search can evaluate the condition at fitted points and candidate locations. The differentiation in $D_G(a)$ is with respect to transferred mass $\epsilon$, with $a$ fixed. Searching for its maxima as a function of $a$ uses a different derivative, $dD_G(a)/da$. The identities above concern the exact probabilities; probability clipping, a denominator floor or a cap on $S$ can change them.
Implementing and inspecting the fit
A derivative search for new locations and a constrained update of the masses form the algorithm implemented below. The first iteration of npmle_cnmms() needs both a slope and an intercept distribution. The supplied constructor represents $G$ with two vectors: pt[k] is the intercept value $a_k$ and pr[k] is the probability mass $\pi_k$ at that value.
1
2
3
4
5
6
7
8
9
10
11
12
npmle_distribution <- function(pt, pr = 1, sort = TRUE) {
if (length(pt) == 0) return(structure(list(pt = numeric(0), pr = numeric(0)), class = "disc"))
if (length(pr) == 0) pr <- 1
# Points and masses are recycled to the longer length; masses are scaled to sum to one.
k <- max(length(pt), length(pr))
pt <- rep(pt, length.out = k)
pr <- rep(pr, length.out = k)
ord <- if (sort) order(pt) else seq_len(k)
d <- list(pt = pt[ord], pr = pr[ord] / sum(pr))
# (a mixing distribution of class "disc")
structure(d, class = "disc")
}
The constructor normalizes the masses and, by default, sorts the points while preserving the correspondence between each mass and its point. A call with sort=FALSE preserves their order when forming a proposal that changes only the masses. The next three code blocks form one definition of npmle_cnmms(). They use the likelihood, nonnegative least-squares and line-search functions loaded from code/lib/npmle.R. Begin with the slope from an ordinary binomial regression and equal masses on ten locations chosen from the observed cluster proportions.
1
2
3
4
5
6
7
8
9
10
npmle_cnmms <- function(x, maxit = 1000, tol = 1e-6, grid = 100) {
# Start: the slope of the binomial GLM with one intercept, and masses on a grid of 10 points.
start_fit <- irls(make_glm(cbind(1, x[, -(1:3), drop = FALSE]),
x[, 2], "binomial", x[, 3]))
beta <- rep(unname(start_fit$par)[-1], length.out = ncol(x) - 3)
mix <- npmle_distribution(rilogit_grid(x, beta, grid = 10), NULL)
attr(mix, "ll") <- npmle_loglik(mix, x, beta, attr = TRUE)
grad_max <- Inf
convergence <- 1
history <- list()
Iteratively reweighted least squares fits an ordinary binomial regression with an intercept. Removing the first coefficient from start_fit$par gives the initial slope. For each cluster, rilogit_grid() computes its observed proportion of successes and clips it to the interval from 0.0001 to 0.9999 before taking its logit. Write $h_i$ for this logit. The lower endpoint is the smallest $h_i-\max_j(\beta x_{ij})$ across clusters. The upper endpoint is the largest $h_i-\min_j(\beta x_{ij})$. Ten equally spaced locations between these endpoints receive equal initial masses. This initialization requires a finite binomial regression fit.
The call to npmle_loglik() returns the sample log likelihood at the supplied distribution and slope. With attr=TRUE, its log_d attribute contains the cluster log contributions used in the next ratio calculation. Internally, rilogit_log_density() returns the conditional cluster log terms in ld, with clusters in rows and support points in columns. These terms omit binomial coefficients, which are one for the Bernoulli responses here. Its which=c(1,0,0) requests log terms without coefficient or location derivatives. The evaluator clips success probabilities and adds a floor of $10^{-100}$ to each scaled mixture probability before taking its logarithm, so these are the implemented likelihood quantities.
The next block searches for candidate locations at the current slope, adds them with zero mass, and updates the masses by constrained least squares and a line search.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
for (i in 1:maxit) {
mix1 <- mix; ll1 <- attr(mix1, "ll"); log_d1 <- attr(ll1, "log_d")
cand <- npmle_derivative_maxima(x, beta, mix, grid = rilogit_grid(x, beta, grid),
tol = -Inf)
grad_max <- cand$grad_max
# The candidate points, largest derivative first, enter with zero mass.
n_new <- length(cand$pt)
new_pt <- cand$pt[order(cand$grad, decreasing = TRUE)][1:n_new]
mix <- npmle_distribution(c(mix$pt, new_pt), c(mix$pr, rep(0, n_new)))
# Each column of S: one location's group probabilities over the incoming mixture
# densities.
log_dens <- rilogit_log_density(x, beta, mix$pt, c(1, 0, 0))$ld
S <- exp(log_dens - log_d1); S <- pmin(S, 1e100)
# Masses by least squares under nonnegativity and unit sum, then a line search
# toward them.
mass_point_gradient <- colSums(S - 1); refine_jointly <- max(mass_point_gradient) < 1e10
r <- nnls_sum(S, 2, s = 1)
target <- npmle_distribution(mix$pt, r$x / sum(r$x), sort = FALSE)
mix <- npmle_line_search(mix, beta, target, beta, x, which = c(1, 0, 0))$mix
At each iteration, mix1 stores the incoming distribution. Recompute a grid of 100 locations with the current slope. To search for local maxima of $D_G(a)$ strictly between the two ends of the current grid, npmle_derivative_maxima() looks for intervals where $dD_G(a)/da$ changes from positive to negative, then refines the candidate intercept within each interval. A nonpositive location derivative at the left endpoint or a nonnegative one at the right makes that endpoint a candidate. The value used to assess a candidate is $D_G(a)$ itself.
Append all candidates with zero mass, so the cluster denominators still come from mix1. Each column of log_dens now contains the conditional log probabilities at one location. Subtract the incoming cluster log probabilities and exponentiate to form $S$. The argument which = c(1, 0, 0) in the line search varies masses at the current locations and slope. A finite grid with strict sign-change checks can miss a stationary point lying exactly on a grid value or multiple turning points within one interval.
Completing the square above explains the 2 in nnls_sum(S, 2, s = 1). For a unit sum, nnls_sum() subtracts the response vector from each column of the least-squares matrix and appends a row of ones. It solves the transformed problem with the Lawson and Hanson nonnegative least-squares routine, then divides the coefficients by their sum. The normalized coefficients r$x / sum(r$x) define the proposed masses, the distribution target. A proposed probability vector requires a successful least-squares solution with a positive coefficient sum.
The mass-only line search first tries the full proposal. The Armijo condition asks for at least 0.33 times the increase predicted by the first derivative along the trial step. If the actual log likelihood gain falls short, the search halves the step toward the current masses. This call uses the default bracketed=FALSE.
Finish the update by removing zero-mass locations, jointly refining the remaining distribution and slope when the derivative condition permits, and merging nearby locations whose merger loses sufficiently little log likelihood. The last block also records the iteration and applies the stopping rule.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
attr(mix, "ll") <- npmle_loglik(mix, x, beta, attr = TRUE)
mix <- npmle_simplify(mix, beta, x, tol = 0)
# Joint BFGS refinement of masses, locations and slope, then merging of close points.
if (refine_jointly) {
joint <- npmle_bfgs(mix, beta, x, which = c(1, 1, 1))
beta <- joint$beta
mix <- npmle_simplify(joint$mix, beta, x, tol = 0.01 * tol)
}
history[[i]] <- list(points = cand$pt, directional = cand$grad, grad_max = grad_max,
mass_points = mix$pt, mass = mix$pr, beta = beta, loglik = attr(mix, "ll")[1])
# Stop when the largest incoming derivative is small and the update gained at most tol.
if (grad_max < 1e-3 && attr(mix, "ll")[1] <= ll1[1] + tol) {
convergence <- 0
break
}
}
# A last merge, with a tolerance relative to the size of the log likelihood.
final_tol <- max(0.1 * tol, 1e-16 * abs(attr(mix, "ll")[1]))
mix <- npmle_simplify(mix, beta, x, tol = final_tol)
list(mass_points = mix$pt, mass = mix$pr, beta = beta, loglik = attr(mix, "ll")[1],
iterations = i, converged = convergence == 0, history = history, final_beta = beta)
}
After the mass step, npmle_simplify() with zero tolerance removes locations with zero mass. If the largest column sum of $S-1$ is below $10^{10}$, the BFGS update jointly refines the surviving masses, locations and slope. Inside npmle_bfgs(), the call to npmle_line_search() requests bracketing with bracketed=TRUE. Joint refinement can move a location beyond the grid that supplied the candidates. Neighboring locations can then be merged at their mass-weighted mean if the log likelihood loss is at most $10^{-8}$.
The history stores the incoming candidate derivatives alongside the updated distribution. The loop stops when the largest incoming candidate derivative is strictly below $10^{-3}$ and the gain from the beginning to the end of the update is at most $10^{-6}$, or when it exhausts 1,000 iterations. A separate final call to npmle_simplify() uses the larger of one tenth of the log likelihood tolerance and $10^{-16}$ times the absolute log likelihood. The returned field final_beta repeats the value of beta after this loop. To obtain the starting slope use the coefficient from start_fit above.
A likelihood decrease also satisfies the gain condition. The derivative used for stopping belongs to the incoming distribution and slope; the code does not repeat the full derivative search after the final update and merge.
Fitting the model to grouped produces an iteration record that separates candidate locations from the distribution after each update. The returned distribution gives the possible intercepts and their estimated population probabilities.
1
2
discrete <- npmle_cnmms(grouped)
print(discrete[c("beta", "mass_points", "mass", "loglik")])
1
2
3
4
5
6
7
8
9
10
11
$beta
[1] 0.7253005
$mass_points
[1] -23.9920515 -0.3195839 1.1629738
$mass
[1] 0.02900533 0.83243670 0.13855797
$loglik
[1] -420.2836
The fitted common slope was 0.7253005. The mass-weighted mean $\sum_k\pi_k a_k$ estimates the population mean of the cluster-specific intercept, measured in log odds at $x=0$. The mean of these log-odds intercepts is not the logit of the population mean success probability. The next call repeats the fitted parameters and adds the iteration count, stopping indicator and this mean. Only those final fields are reproduced below.
1
2
3
4
print(list(beta=discrete$beta,mass_points=discrete$mass_points,mass=discrete$mass,
loglik=discrete$loglik,
iterations=discrete$iterations,converged=discrete$converged,
weighted_mean=sum(discrete$mass_points*discrete$mass)))
1
2
3
4
5
6
7
8
$iterations
[1] 3
$converged
[1] TRUE
$weighted_mean
[1] -0.8007914
Only about 2.9 percent of the fitted population is at $-23.99$, yet this point contributes about $0.02900533(-23.99205)=-0.696$ to the mean. The other two contributions are about $-0.266$ and $0.161$, bringing the mean to $-0.80079$.
The iteration record distinguishes the candidates considered at the start of each update from the fitted distribution at its end.
1
2
3
4
5
6
7
print(do.call(rbind,lapply(seq_along(discrete$history),function(i) {
step <- discrete$history[[i]]
data.frame(iteration=i,new_points=length(step$points),
max_candidate_loglik_directional_derivative=step$grad_max,
number_of_mass_points=length(step$mass_points),smallest_mass=min(step$mass),
beta=step$beta,loglik=step$loglik)
})))
1
2
3
4
5
6
7
8
iteration new_points max_candidate_loglik_directional_derivative
1 1 1 5.158678e+02
2 2 3 1.446361e+02
3 3 3 8.262998e-06
number_of_mass_points smallest_mass beta loglik
1 2 0.22828919 0.7173392 -421.9001
2 3 0.02900539 0.7253005 -420.2836
3 3 0.02900533 0.7253005 -420.2836
In the history, new_points counts candidates at the beginning of the update, including any that coincide with an existing point, and number_of_mass_points counts locations with positive mass at its end. The first iteration found a candidate at $-0.22794$ with $D_G(a)=515.87$. It ended with two mass points, slope 0.71734 and log likelihood $-421.9001$. The second iteration shows why candidate locations must be distinguished from the locations after joint refinement.
1
2
3
4
d <- discrete
print(do.call(rbind,lapply(seq_along(d$history),function(i)
data.frame(iteration=i,point=d$history[[i]]$points,
recorded=d$history[[i]]$directional))))
1
2
3
4
5
6
7
8
iteration point recorded
1 1 -0.22794114 5.158678e+02
2 2 -9.92757952 1.446361e+02
3 2 0.09868555 1.605872e-01
4 2 9.92757952 6.150723e+00
5 3 -9.93554091 -1.115727e-02
6 3 -0.31958651 8.262998e-06
7 3 1.16296359 -3.085782e-05
At the second iteration the candidates were $-9.928$, $0.0987$ and $9.928$, with derivatives about 144.64, 0.1606 and 6.151. At the end of that update, discrete$history[[2L]]$mass_points gives $-23.99205$, $-0.31958$ and $1.16297$. The corresponding discrete$history[[2L]]$mass entries are 0.02900539, 0.83243653 and 0.13855808. These are locations and masses after joint refinement, when the slope was 0.72530 and the log likelihood was $-420.2836$. In iteration three, two candidates had negative derivatives and the largest derivative was $8.262998\times10^{-6}$. Subtracting the second history log likelihood from the third gives a gain of about $4.89\times10^{-12}$. At four decimal places the totals agree. At full precision the gain satisfies the $10^{-6}$ tolerance.
To compare the fitted mean with the population intercept under normal mixing, load the discrete distribution and the normal model fitted by adaptive quadrature to the same observations.
1
2
3
4
source("code/lib/stability.R")
d <- readRDS("data/derived/ch12/fits.rds")$discrete
normal_fit <- readRDS("data/derived/ch09/fits.rds")$adaptive
obs <- readRDS("data/source/ch09/GLMM80-binary.rds")
In the normal model, the random deviation has mean zero, so the first fixed coefficient, normal_fit$beta[1L], gives the population intercept of $-0.19120$. In the discrete fit, over 97 percent of the fitted mass lies at the other two locations, both above the mean of $-0.80079$. The mean depends strongly on how far left the small mass lies.
Checking the support and lower tail
With the returned masses, locations and slope fixed, evaluate the direction toward a trial intercept. The estimator clips the conditional probabilities to the interval from $10^{-10}$ to $1-10^{-10}$ before taking logs. The diagnostic below instead computes the log probabilities directly from the linear predictors. The estimator’s analytic derivatives use binomial residual formulas with the clipped probabilities, without differentiating the clipping operation. Outside the unclipped range they are therefore not derivatives of its clipped log likelihood. The finite-difference check concerns the directly evaluated probabilities, not that modified criterion.
1
2
3
4
5
6
7
8
9
10
11
12
13
group_terms <- function(a,beta) {
eta <- outer(obs$x*beta,a,"+")
rowsum(-log1pexp((1-2*obs$y)*eta),obs$id,reorder=FALSE)
}
derivatives <- function(step,points) {
joint <- sweep(group_terms(step$mass_points,step$beta),2,log(step$mass),"+")
log_marginal <- apply(joint,1,logsumexp)
ratio <- exp(group_terms(points,step$beta)-log_marginal)-1
# log1p gives the actual change in log likelihood when epsilon mass is inserted.
eps <- 1e-8
data.frame(candidate=points,directional=colSums(ratio),
finite_difference=colSums(log1p(eps*ratio))/eps)
}
group_terms() sums stable Bernoulli log probabilities by cluster with log1pexp(). In derivatives(), log_marginal contains the log marginal probability of each cluster pattern. For each candidate column, ratio contains $r_i=f_i(a)/L_i-1$. Summing that column gives the directional derivative. Summing $\log(1+\epsilon r_i)$ and dividing by $\epsilon$ gives the actual change per unit of transferred mass.
Evaluate the same fitted distribution at 331 trial locations. The two printed rows pick the largest derivative on the central part of this grid and on the full grid.
1
2
3
4
grid <- seq(-25,8,length.out=331L)
search <- derivatives(d,grid)
print(rbind(original=search[which.max(ifelse(abs(grid)<=5,search$directional,-Inf)),],
expanded=search[which.max(search$directional),]))
1
2
3
candidate directional finite_difference
original -0.3 -1.364301e-03 -1.364337e-03
expanded -25.0 3.811375e-05 2.784707e-05
At $a=-0.3$ the derivative is $-1.364301\times10^{-3}$, close to the finite difference $-1.364337\times10^{-3}$ for $\epsilon=10^{-8}$. The row labeled original restricts the wider grid, whose spacing is 0.1, to locations between $-5$ and 5. On the 331-point grid from $-25$ to 8, small positive values extend into the far-left tail, reaching a maximum of $3.81\times10^{-5}$ at $-25$.
A finer search examines the central interval again. Evaluating the fitted mass points themselves tests the equality condition directly at those locations.
1
2
3
fine <- derivatives(d,seq(-5,5,by=.001))
print(list(fine_max=fine[which.max(fine$directional),],
derivative_at_mass_points=derivatives(d,d$mass_points)))
1
2
3
4
5
6
7
8
9
$fine_max
candidate directional finite_difference
6164 1.163 -3.667614e-07 -1.467149e-06
$derivative_at_mass_points
candidate directional finite_difference
1 -23.9920515 3.810822e-05 2.784155e-05
2 -0.3195839 -1.266954e-06 -1.305265e-06
3 1.1629738 -3.657862e-07 -1.466121e-06
Searching that interval with spacing 0.001 gives a maximum of $-3.67\times10^{-7}$ at 1.163. At the three fitted locations the derivatives are about $3.81\times10^{-5}$, $-1.27\times10^{-6}$ and $-3.66\times10^{-7}$.
Both grid maxima are below the numerical tolerance of $10^{-3}$. These finite grids do not verify the inequality at every possible location or establish joint optimality in the slope. A forward difference at positive $\epsilon$ is a secant slope, not the derivative at zero: its first correction is $-\epsilon\sum_i r_i^2/2$. Thus a difference from a small positive derivative need not be rounding error.
To see which clusters inform the far-left point, condition on each observed response pattern and inspect the posterior probability of that point for clusters with no successes.
1
2
3
4
5
joint <- sweep(group_terms(d$mass_points,d$beta),2,log(d$mass),"+")
posterior <- exp(joint-apply(joint,1,logsumexp))
no_success <- tapply(obs$y, obs$id, sum) == 0
print(list(clusters_without_success = sum(no_success), far_point = min(d$mass_points),
posterior_on_far_point = posterior[no_success, which.min(d$mass_points)]))
1
2
3
4
5
6
7
8
9
$clusters_without_success
[1] 3
$far_point
[1] -23.99205
$posterior_on_far_point
33 41 49
0.7734758 0.7734758 0.7734758
For clusters 33, 41 and 49, moving the intercept farther left raises the probability of each observed failure. Once all eight failures have probabilities near one, further decreases in the intercept change their product very little. For each of these clusters, the posterior probability of the most negative point is 0.7734758, compared with its population mass of 0.02900533. Their outcomes help locate mass in the lower tail while giving little precision about how far left the point lies. The reported $-23.99205$ is a finite numerical value, not evidence that the likelihood maximum is attained at a finite intercept; a limiting mass point as the intercept tends to $-\infty$ remains a possibility. Evaluating more candidate locations with those estimates fixed leaves open where a refit under a different search limit would place the point.
Predicting responses in a new cluster
For a new cluster with no observed responses, average the conditional success probability over the population distribution of intercepts. There is no response pattern on which to condition its membership probabilities. At a given covariate $x$, discrete mixing gives $\sum_k\pi_k\operatorname{logit}^{-1}(a_k+\beta x)$. For the normal fit, let $\alpha$ be its population intercept, $\beta_{\rm n}$ its slope and $\sigma$ its random-intercept standard deviation. Integration averages $\operatorname{logit}^{-1}(\alpha+\beta_{\rm n}x+\sigma z)$ over a standard normal variable $z$. The first calculation below uses the fitted masses in d. The second uses normal_fit$beta for the intercept and slope and the square root of normal_fit$G[1] for the standard deviation. The argument rel.tol of stats::integrate() specifies the requested relative integration tolerance.
1
2
3
4
5
x <- c(-1,0,1)
new_site <- vapply(x,function(xj)sum(d$mass*plogis(d$beta*xj+d$mass_points)),0.0)
normal <- vapply(x,function(xj) integrate(function(z)plogis(sum(c(1,xj)*normal_fit$beta)+
sqrt(normal_fit$G[1])*z)*dnorm(z),-Inf,Inf,rel.tol=1e-10)$value,0.0)
print(data.frame(x, discrete=new_site, normal=normal))
| $x$ | Discrete mixing | Normal mixing |
|---|---|---|
| -1 | 0.30081 | 0.30067 |
| 0 | 0.45583 | 0.45605 |
| 1 | 0.61986 | 0.61992 |
The table shows the probabilities to five decimal places. At $x=0$, both models predict a success probability of about 0.456. The remote intercept contributes almost zero success probability at each of these three covariate values, even though its contribution to the mean log odds was substantial. The two fitted distributions give similar population predictions over these settings. The supplied npmle_cnmms() is adapted from cnmms() of nspmix, and its nonnegative least squares is translated from the Lawson-Hanson routine as modified in lsei (code/NOTICE.md); nspmix estimates mixing distributions for random-intercept logistic regression models by nonparametric maximum likelihood.
12.9 Checking mixture estimates and sensitivity to the latent distribution
This section checks the chapter’s fitted mixtures from several directions. The first two comparisons evaluate the book’s Gaussian mixture and mixture-regression fits against mclust and flexmix fits to the same observations. A simulation study then measures how well the latent class estimates recover known survey profiles, and an observed survey of candidate evaluations applies the same methods when the number of classes is unknown. The last comparison returns to the 80 binary clusters of Section 12.8 and asks which conclusions depend on the assumed intercept distribution.
Comparing Gaussian mixture densities
Exchanging two class labels leaves the likelihood unchanged as long as each class takes its mixing proportion and its response distribution with it. Let $z_i$ contain the standardized duration of eruption $i$ and the standardized waiting time until the next eruption. For this pair, the marginal density is $\pi_1 f_1(z_i)+\pi_2 f_2(z_i)$. Exchanging the two terms gives the same density for that eruption, and the same is true for every other eruption. This identity makes it possible to compare the two full-covariance Gaussian fits before deciding which class to call first. Use the same 272 duration and waiting-time pairs in both fits.
The section script prepares the standardized measurements and fits the two-class model. In mclust, the specification VVV allows each class its own covariance matrix. The external mclust result stores its proportions in reference_gmm$parameters$pro. The code below copies them to reference_model$mass, the field used by the common density calculation. The book’s Gaussian fitter returns mixing_proportion; gmm_model() in Section 12.3 places those proportions in full$model$mass for the same calculation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
source("code/practice/12.3.R")
source("code/lib/mixtures.R")
suppressPackageStartupMessages(library(mclust))
reference_gmm <- Mclust(scaled_geyser, G=2L, modelNames="VVV", verbose=FALSE)
reference_model <- list(
mass=reference_gmm$parameters$pro, mean=t(reference_gmm$parameters$mean),
covariance=lapply(1:2, function(k) reference_gmm$parameters$variance$sigma[,,k])
)
common_log_density <- function(model)
mixture_posterior(gmm_log_emission(scaled_geyser, model), model$mass)$observation_loglik
book_log_density <- common_log_density(full$model)
reference_log_density <- common_log_density(reference_model)
c(book=book_log_density[1L], mclust=reference_log_density[1L])
max(abs(book_log_density - reference_log_density))
Transposing the means puts one class in each row, and taking a slice of the covariance array gives the matrix for that row. For each pair, common_log_density() passes the class-conditional log densities and the class proportions to mixture_posterior() (Section 12.1).
The first pair gives $-1.8957163$ under both fits. Across the 272 pairs, the largest absolute difference between the saved columns is about $3.0\times10^{-14}$. The book’s Gaussian mixture EM is adapted from mclust (code/NOTICE.md), so this agreement checks the adaptation (Section E.3). Checking each pair also rules out an apparent agreement in the total produced by differences of opposite signs. Here, the two stored fits already put the longer-eruption class first.
Comparing mixtures of regressions
For regression coefficients, order the classes by their response intercepts. What density do the two regression implementations assign to the response of the same person? The section script compares the saved book fit for 500 people with two flexmix fits. The book fit used a class-removal threshold of 0.05 and retained both classes. The comparison fits use a threshold of zero. One starts with groups defined by whether the response exceeds its median. The other randomly assigns each person to one of two classes using seed 120924.
For each fit, membership_comparison() puts the smaller response intercept first, carrying the response slope and residual SD with it. If this changes the baseline class, membership_comparison() negates both membership coefficients. Reversing the ratio of two class probabilities reverses the sign of its logarithm. The sign reversal applies to two classes. With more classes, changing the reference requires subtracting the new reference coefficient vector from every class coefficient vector. With those labels fixed, the contribution of each person to the log likelihood is
By default, membership_comparison() reads the responses and covariates from data/source/ch12/regression.rds and the book model from the regression entry in data/derived/ch12/fits.rds. Run the script from the book directory. Its first two displays come from comparison$details$book[1L, ] and comparison$summary.
1
source("code/practice/12.9.R")
1
2
method row y mean1 mean2 p2 log_density
book 1 -1.513776 -0.9874592 1.966577 0.2573039 -1.097073
Inside the section script’s membership_comparison(), the two columns of mixing contain the class probabilities given $w_i$, and the two columns of means contain the response means at $x_i$. For each class, log_joint adds the log mixing probability to the normal log density evaluated with that class’s mean and SD. Applying logsumexp() to the two log joint densities gives $\ell_i$.
For person 1, the probability of the second class is 0.25730 before the response is observed. The two classes predict means of $-0.98746$ and $1.96658$. The observed response of $-1.51378$ lies much closer to the first mean. Averaging the two response densities with these class probabilities gives a marginal log density of $-1.09707$. Summing the same calculation over all 500 people gives the common column.
1
2
3
4
5
6
7
8
method common native converged sd1 sd2 intercept1
book -789.6280 -789.6280 TRUE 0.6165429 0.8430762 -0.9470452
response_split -789.6282 -789.6282 TRUE 0.6164825 0.8432527 -0.9471220
random -789.6282 -789.6282 TRUE 0.6165246 0.8432379 -0.9470716
slope1 intercept2 slope2 membership_intercept membership_slope
0.5119387 1.912852 -0.6805553 -0.2849775 0.6066724
0.5119189 1.912604 -0.6807705 -0.2847303 0.6066888
0.5119645 1.912632 -0.6807903 -0.2847984 0.6067058
At the returned coefficients the three sums are $-789.6280$, $-789.6282$ and $-789.6282$. The native column records each fit’s last E-step value. For the book fit the two values are $-789.628010$ and $-789.628022$ before rounding to four decimals. The last two columns describe how membership varies with the covariate. At $w=0$, the fitted log odds of the second class are about $-0.285$ under each fit. A one-unit increase in $w$ raises those log odds by about $0.607$, with the second class defined by its larger intercept at $x=0$. The book’s EM for this model is adapted from flexmix (code/NOTICE.md), so the agreement of the three sums checks that adaptation, although the two comparison fits start from their own partitions (Section E.3).
Recovering survey profiles across samples
How closely do the estimated survey profiles recover the probabilities used to generate responses? The simulation study of parameter estimation drew 200 independent LCA6 samples of 600 respondents each, with the same three class proportions and the same six item probabilities in each class.
In the simulated survey, the generating profiles provide a reference. The function align_three_classes() tries all six orders of the three estimated profiles and selects the order that minimizes the sum of squared differences from the generating success probabilities across all six items and three classes. It applies that order to the class proportions as well. A proportion can then be compared with the generating proportion for the response profile it accompanies. The generating profiles are available only in this simulation; they are not an available matching reference in an ordinary survey. This matching rule compares the estimated profiles, not the respondents’ unobserved true memberships.
For each sample, the simulation study fitted the model from four random starting tables and selected the run with the largest terminal log likelihood. Its attempts field records all four terminal likelihoods, which show how much the terminal likelihood varied across starting tables for the same respondents. If the retained run does not meet the gain stopping rule, the code marks that sample valid=FALSE and excludes it from the bias calculation; a smaller-likelihood run may have met the rule. Only the retained fit supplies a stopping reason for each sample. Thus, 800 starts yield 200 recorded stopping reasons and at most 200 sets of estimates. The section script reads these records and assembles the estimates as follows.
1
2
3
4
study <- readRDS("data/derived/ch12/recovery-records.rds")
usable <- vapply(study, function(r) r$valid, logical(1))
estimates <- do.call(rbind, lapply(study[usable], function(r)
c(r$aligned$mass, r$aligned$probability)))
Read across a row of estimates in generating-class order. The first three entries estimate the population class proportions. The next six give the success probabilities for the six items in the first class. Two more sets of six give the corresponding probabilities in the second and third classes. Without the alignment, two samples with nearly identical fitted profiles could put the high-success profile in different columns. Averaging down a column would then combine answers to different questions.
For each of the 21 columns, estimate bias by subtracting the generating value from the mean estimate. Its Monte Carlo standard error measures how precisely the simulated samples determine that mean difference. Compute the SD down the column. With $m$ usable samples, the Monte Carlo standard error is that SD divided by $\sqrt{m}$. Each row represents a whole survey of 600 respondents, so the variation down a column already includes the effects of drawing different respondents and observing different answers. With failures, these summaries would describe the retained subset, and the Monte Carlo standard error would not account for the omitted samples or certify that numerical fitting error is negligible. Here are the generating profiles and the calculations behind the final display of the section script.
1
2
3
4
5
6
7
8
9
10
probability <- cbind(c(.10, .15, .10, .15, .10, .15),
c(.85, .80, .85, .15, .10, .15),
c(.85, .90, .85, .85, .90, .85))
truth <- c(.3, .4, .3, probability)
recovery <- data.frame(
parameter=c(paste0("mass", 1:3), as.vector(outer(1:6, 1:3, paste, sep=":"))),
failures=sum(!usable), usable=sum(usable), truth=truth,
bias=colMeans(estimates) - truth, MCSE=apply(estimates, 2L, sd) / sqrt(sum(usable))
)
print(recovery, 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
parameter failures usable truth bias MCSE
mass1 0 200 0.30 -1.187145e-03 0.001875038
mass2 0 200 0.40 1.501032e-03 0.002171480
mass3 0 200 0.30 -3.138871e-04 0.001689358
1:1 0 200 0.10 4.501836e-05 0.002623113
2:1 0 200 0.15 -1.467209e-03 0.002624097
3:1 0 200 0.10 -2.762282e-03 0.002473870
4:1 0 200 0.15 2.359997e-03 0.001940650
5:1 0 200 0.10 6.228125e-04 0.001765129
6:1 0 200 0.15 -2.660161e-03 0.002149313
1:2 0 200 0.85 -2.315821e-03 0.002505480
2:2 0 200 0.80 -5.092628e-04 0.002652224
3:2 0 200 0.85 2.274897e-03 0.002286818
4:2 0 200 0.15 -2.417441e-03 0.002303477
5:2 0 200 0.10 -1.622704e-03 0.002097551
6:2 0 200 0.15 5.404076e-04 0.002271078
1:3 0 200 0.85 3.201981e-03 0.001951359
2:3 0 200 0.90 -2.069379e-03 0.001881143
3:3 0 200 0.85 1.481483e-03 0.001991218
4:3 0 200 0.85 8.773633e-04 0.002639489
5:3 0 200 0.90 1.236009e-03 0.002309324
6:3 0 200 0.85 -1.858585e-03 0.002324329
All 200 retained runs met the gain rule in the recorded output. The divisor for the standard error is therefore $\sqrt{200}$ for every parameter.
The estimated first-class proportion, in row mass1, averaged about $0.29881$ when the generating proportion was $0.30$. The estimated bias of $-0.00119$ is smaller in magnitude than its Monte Carlo standard error of $0.00188$. In the item rows, the first number identifies the item and the second its class. The largest absolute bias relative to its Monte Carlo standard error occurs for item 1 in class 3. Its generating probability is $0.85$, and the mean estimate exceeds it by $0.00320$, about $1.64$ times the standard error of $0.00195$. Even this largest discrepancy is estimated with appreciable simulation uncertainty. That standard error describes how precisely repeated surveys under these generating profiles determine the mean difference from the generating value. To describe variation in the estimate from a single survey of this size, use the between-survey SD itself. A small estimated bias relative to its Monte Carlo standard error does not prove unbiasedness; the 21 ratios are descriptive summaries, not a simultaneous test.
Candidate evaluations in an observed survey
The simulated survey profiles have known classes. Real candidate evaluations instead require both the profiles and their number to be inferred. The election data in poLCA contain 1,785 records from the 2000 American National Election Study; 1,311 have complete responses on the twelve candidate evaluations. Six traits were rated for Al Gore and the same six for George W. Bush. Responses range from 1, describing a trait extremely well, to 4, describing it not well at all. The dataset documentation provides the source and coding.
Use the twelve ratings as categorical indicators. The trait prefixes identify morality, caring, knowledge, leadership, dishonesty and intelligence; suffixes G and B identify the two candidates. The supplied columns are factors with text labels. Match each label to the explicitly ordered four-category vector before subtracting one to obtain the scores used by the book’s likelihood functions. All candidate models use the same complete cases. Thus likelihood differences reflect different class counts on the same observations, rather than changing samples. Complete-case analysis can change the composition of the survey sample; the following unweighted analysis describes the retained extract.
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
# 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(12L)
record_check <- application$record_check
record_review <- application$record_review
data("election", package = "poLCA", envir = environment())
election_traits <- c("MORAL", "CARES", "KNOW", "LEAD", "DISHON", "INTEL")
election_names <- c(paste0(election_traits, "G"), paste0(election_traits, "B"))
election_categories <- c("1 Extremely well", "2 Quite well", "3 Not too well", "4 Not well at all")
election_raw <- vapply(election_names, function(name) {
labels <- as.character(election[[name]])
codes <- match(labels, election_categories)
if (any(!is.na(labels) & is.na(codes))) stop(paste("Unrecognized response label in", name))
codes
}, integer(nrow(election)))
stopifnot(all(is.na(election_raw) | election_raw %in% 1:4))
election_rows <- which(complete.cases(election_raw))
election_Y <- election_raw[election_rows, , drop = FALSE] - 1L
print(c(available = nrow(election_raw), analyzed = nrow(election_Y),
excluded = nrow(election_raw) - nrow(election_Y)))
print(data.frame(indicator = election_names,
missing = colSums(is.na(election_raw)),
analyzed_first_category = colMeans(election_Y == 0)), row.names = FALSE)
saveRDS(list(source = election[, election_names], coding = election_categories,
raw = election_raw, rows = election_rows, Y = election_Y),
file.path("data/source/ch12", "ch12-election.rds"))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
available analyzed excluded
1785 1311 474
indicator missing analyzed_first_category
MORALG 122 0.25781846
CARESG 99 0.15942029
KNOWG 56 0.27231121
LEADG 92 0.14797864
DISHONG 154 0.08771930
INTELG 49 0.28604119
MORALB 176 0.20900076
CARESB 101 0.09992372
KNOWB 66 0.15942029
LEADB 104 0.16323417
DISHONB 200 0.04271548
INTELB 73 0.19374523
The reported missing counts concern the original extract, while the first-category proportions concern the analyzed rows. The explicit label matching does not depend on the factor’s internal level numbers, and an unknown nonmissing label stops the calculation. election_rows records the original row numbers. This permits every fitted posterior vector to be connected to its source response vector.
The analysis retains 1,311 of the 1,785 records and excludes 474 with at least one missing evaluation, about 26.6 percent of the extract. The missing count for a single indicator does not equal this exclusion count because a record can be incomplete on several indicators. The fitted profiles and proportions below refer to the retained respondents.
For respondent $i$, let $C_i\in\lbrace 1,\ldots,K\rbrace $ denote an unobserved class with probabilities $\pi_k$. For indicator $j$, let $\theta_{jck}=\Pr(Y_{ij}=c\mid C_i=k)$, where $c=0,1,2,3$. These are unrestricted categorical probabilities: the model does not impose an equal-interval score or a cumulative link. Under local independence,
\[p(y_i)=\sum_{k=1}^K\pi_k\prod_{j=1}^{12}\theta_{j,y_{ij},k}, \qquad \sum_k\pi_k=1,\quad \sum_{c=0}^3\theta_{jck}=1.\]A class represents a profile of probabilities across all twelve ratings. It does not assign one fixed answer to everyone in that class. The nominal free-parameter count is $(K-1)+12K(4-1)=37K-1$. Compare one through four classes with AIC and BIC, using twelve initializations for each multi-class fit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
election_fits <- lapply(1:4, function(K) {
set.seed(120400L + K)
lca_em(election_Y, n_classes = K, n_starts = 12L,
max_iter = 5000L, tol = 1e-8)
})
election_comparison <- do.call(rbind, lapply(1:4, function(K) {
fit <- election_fits[[K]]
parameters <- K - 1L + K * sum(rep(4L - 1L, ncol(election_Y)))
data.frame(classes = K, parameters = parameters, loglik = fit$loglik,
AIC = -2 * fit$loglik + 2 * parameters,
BIC = -2 * fit$loglik + parameters * log(nrow(election_Y)),
converged = fit$converged, iterations = fit$iterations,
minimum_mass = min(fit$model$mass),
starts_near_best = sum(abs(fit$attempts - fit$loglik) < .01),
attempted_starts = length(fit$attempts))
}))
print(election_comparison, row.names = FALSE)
election_K <- election_comparison$classes[which.min(election_comparison$BIC)]
election_selected <- election_fits[[election_K]]
1
2
3
4
5
6
7
8
9
10
classes parameters loglik AIC BIC converged iterations minimum_mass starts_near_best
1 36 -18647.31 37366.62 37553.05 TRUE 1 1.0000000 1
2 73 -17344.92 34835.85 35213.88 TRUE 219 0.4571992 12
3 110 -16714.66 33649.32 34218.96 TRUE 164 0.2607812 12
4 147 -16350.59 32995.18 33756.42 TRUE 117 0.1680368 3
attempted_starts
1
12
12
12
The one-class model estimates the marginal category proportions directly. For the other models, starts_near_best counts initializations ending within 0.01 log likelihood units of the best attained solution. It measures repetition of that solution within this search, without proving global optimality. The iteration limit and convergence flag should be examined together. minimum_mass identifies a small fitted class whose profile may have little effective information.
The code selects the smallest BIC among these four candidates for a worked interpretation. This is a comparison over a specified candidate set. It does not establish that the population has exactly that many types. Boundary category probabilities, residual associations and numerical instability can all complicate this interpretation.
Among the four candidates, the four-class model has the smallest BIC, 33756.42, compared with 34218.96 for three classes. Its smallest fitted class proportion is about 0.168. Three of its twelve initializations end within 0.01 log likelihood units of the best attained value; all twelve do so for the two- and three-class fits. Since four is also the largest class count examined, this comparison does not establish that additional classes would be unnecessary.
Favorable-rating profiles of the four classes
To interpret the profiles, calculate the probability of a favorable rating. For the five positively worded traits this is the probability of original codes 1 or 2. For dishonesty it is the probability of codes 3 or 4, because weak endorsement of dishonesty is favorable. This reversal concerns the displayed summary; the model itself still uses all four original categories.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# A favorable response means scores 0/1 on positive traits, 2/3 on dishonesty.
election_favorable <- t(vapply(seq_along(election_names), function(j) {
rows <- if (startsWith(election_names[j], "DISHON")) 3:4 else 1:2
colSums(election_selected$model$probability[[j]][rows, , drop = FALSE])
}, numeric(election_K)))
election_order <- order(colMeans(election_favorable[1:6, , drop = FALSE]) -
colMeans(election_favorable[7:12, , drop = FALSE]), decreasing = TRUE)
election_profiles <- data.frame(indicator = election_names,
election_favorable[, election_order, drop = FALSE], check.names = FALSE)
names(election_profiles)[-1] <- paste0("class", seq_len(election_K))
election_posterior <- election_selected$posterior[, election_order, drop = FALSE]
election_mass <- election_selected$model$mass[election_order]
election_certainty <- apply(election_posterior, 1L, max)
election_entropy <- -rowSums(election_posterior * log(pmax(election_posterior, .Machine$double.xmin)))
election_uncertain <- order(election_certainty)[seq_len(min(5L, nrow(election_Y)))]
print(data.frame(class = seq_len(election_K), proportion = election_mass), row.names = FALSE)
print(election_profiles, row.names = FALSE)
print(data.frame(source_row = election_rows[election_uncertain],
maximum_posterior = election_certainty[election_uncertain],
entropy = election_entropy[election_uncertain],
election_posterior[election_uncertain, , drop = FALSE]), row.names = FALSE)
print(quantile(election_certainty, c(0, .25, .5, .75, 1)))
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
class proportion
1 0.2081311
2 0.1680368
3 0.3712907
4 0.2525414
indicator class1 class2 class3 class4
MORALG 0.89057028 1.0000000 0.7534508 0.4076078
CARESG 0.81242474 0.9003454 0.5910004 0.1851584
KNOWG 0.90659289 0.9894882 0.8872892 0.5942577
LEADG 0.77719951 0.9459861 0.5688254 0.1620554
DISHONG 0.91088467 0.8639872 0.7855317 0.3919150
INTELG 0.91072955 0.9947917 0.8938289 0.6501944
MORALB 0.32288502 0.8273875 0.7676153 0.9392883
CARESB 0.07594892 0.4331759 0.4603685 0.8691498
KNOWB 0.10676527 0.9125603 0.7894508 0.9349948
LEADB 0.12224993 0.7357204 0.7550128 0.9546126
DISHONB 0.55319357 0.7595078 0.8323579 0.8927663
INTELB 0.16613508 0.9719436 0.8263793 0.9644226
source_row maximum_posterior entropy X1 X2 X3 X4
826 0.3894118 1.0763305 4.489876e-05 3.744688e-01 0.2360745 0.38941184
291 0.4252478 1.0787900 1.032283e-04 4.252478e-01 0.2608154 0.31383356
713 0.4496423 1.2561857 1.043079e-01 2.658596e-01 0.1801902 0.44964230
793 0.4627851 1.0427171 4.627851e-01 1.241393e-56 0.3414915 0.19572331
863 0.4778065 0.9215215 4.628520e-04 4.778065e-01 0.4404906 0.08124001
0% 25% 50% 75% 100%
0.3894118 0.8964072 0.9864572 0.9985937 1.0000000
The first table gives class proportions. The profile table gives favorable-rating probabilities, with one column per class. Classes are displayed in descending order of the average Gore-minus-Bush favorable-rating difference. This convention makes the labels reproducible; it does not impose political identities on the fitted classes. Similar evaluations of both candidates can produce profiles that do not follow a simple partisan ordering.
The displayed class proportions are approximately 0.208, 0.168, 0.371 and 0.253. Class 1 rates Gore favorably and Bush less favorably: for caring, the favorable probabilities are 0.812 and 0.076. Class 4 shows the reverse pattern on that trait, with probabilities 0.185 and 0.869. Classes 2 and 3 give favorable ratings to both candidates on several traits, so their profiles require more than opposing partisan labels. For class 2, Gore’s morality probability rounds to 1.0000000. Such extreme probabilities warrant attention to the category counts and boundary behavior; the printed value is not evidence of certain responses in a population class.
The next table shows five respondents with the smallest maximum posterior class probabilities. source_row refers to the original extract, and the remaining class columns show their entire posterior vectors. Entropy is $-\sum_k w_{ik}\log w_{ik}$, where $w_{ik}=\Pr(C_i=k\mid y_i)$; larger entropy indicates more diffuse membership probabilities at a given class count. Neither these vectors nor their largest entries are observed memberships. A subsequent analysis using a single assigned class would discard this uncertainty.
The median maximum posterior probability is about 0.986, but the smallest is only 0.389. For source row 826, the probabilities for displayed classes 2, 3 and 4 are about 0.374, 0.236 and 0.389. Assigning this respondent to class 4 would conceal substantial uncertainty. In this table, X1 through X4 refer to the same displayed class order as the profile table.
Pairwise margins and a continuation in poLCA
Local independence can be examined through two-indicator margins. For categories $c,d$ on indicators $j,l$, the model implies $\sum_k\pi_k\theta_{jck}\theta_{ldk}$. Compare these probabilities with the empirical proportions on the same complete cases.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
election_pairs <- do.call(rbind, lapply(combn(ncol(election_Y), 2L, simplify = FALSE), function(pair) {
first <- election_selected$model$probability[[pair[1]]]
second <- election_selected$model$probability[[pair[2]]]
fitted <- sweep(first, 2L, election_selected$model$mass, "*") %*% t(second)
observed <- table(factor(election_Y[, pair[1]], levels = 0:3),
factor(election_Y[, pair[2]], levels = 0:3)) / nrow(election_Y)
data.frame(first = election_names[pair[1]], second = election_names[pair[2]],
max_cell_probability_gap = max(abs(observed - fitted)))
}))
election_pairs <- election_pairs[order(election_pairs$max_cell_probability_gap, decreasing = TRUE), ]
print(head(election_pairs, 10L), row.names = FALSE)
saveRDS(list(fits = election_fits, comparison = election_comparison,
selected_classes = election_K, class_order = election_order, profiles = election_profiles,
posterior = election_posterior, pair_diagnostics = election_pairs),
file.path("data/derived/ch12", "ch12-election.rds"))
1
2
3
4
5
6
7
8
9
10
11
first second max_cell_probability_gap
KNOWB INTELB 0.07220406
KNOWG INTELG 0.07083505
CARESG LEADG 0.06391046
MORALG DISHONG 0.04739384
CARESB LEADB 0.04601111
KNOWB LEADB 0.03990498
MORALG LEADG 0.03988757
MORALG CARESG 0.03867811
MORALB LEADB 0.03599341
MORALB CARESB 0.03566969
The table lists the ten pairs with the largest absolute cell-probability discrepancy. Closely related evaluations of the same candidate may remain associated within a class, but the observed discrepancy alone does not establish that explanation. It identifies pairs to inspect. Adding classes can also absorb residual dependence, so a smaller BIC should be considered together with these margins and the substantive profiles.
The largest discrepancies concern knowledge and intelligence for Bush, about 0.0722, and the same two traits for Gore, about 0.0708. Caring and leadership for Gore follow at about 0.0639. Even the selected four-class model therefore leaves visible discrepancies in these bivariate margins. A high posterior classification probability describes certainty within the fitted model and does not resolve these discrepancies.
Finally, pass the selected class probabilities to poLCA as starting values and continue estimation on the identical data. This comparison avoids class-label alignment by comparing likelihoods.
1
2
3
4
5
6
7
8
9
10
11
election_formula <- as.formula(paste0("cbind(", paste(election_names, collapse = ","), ") ~ 1"))
election_reference <- poLCA::poLCA(election_formula,
data = as.data.frame(election_Y + 1L), nclass = election_K,
probs.start = lapply(election_selected$model$probability, t),
nrep = 1L, maxiter = 5000L, tol = 1e-8, verbose = FALSE, graphs = FALSE, calc.se = FALSE)
election_recomputed <- mixture_posterior(
lca_log_emission(election_Y, election_selected$model$probability), election_selected$model$mass)
election_reference_gap <- abs(election_selected$loglik - election_reference$llik)
print(data.frame(book_loglik = election_selected$loglik, package_loglik = election_reference$llik,
absolute_gap = election_reference_gap))
saveRDS(election_reference, file.path("data/derived/ch12", "ch12-reference.rds"))
1
2
book_loglik package_loglik absolute_gap
1 -16350.59 -16350.59 2.773959e-09
The package continuation changes the attained log likelihood by only about $2.77\times10^{-9}$. This supports agreement in the likelihood calculation and the attained solution after continuation. Because the reference call begins from the selected fit, it is not an independent search for a better maximum. The twelve initializations remain a separate part of the numerical assessment. Both implementation agreement and repeated initializations concern estimation; neither establishes local independence or error-free classification.
Sensitivity to the cluster-intercept distribution
Return to the 80 clusters examined in Section 12.8. Which conclusions depend on the assumed distribution of their intercepts? The conditional slope is $0.72124$ with a normal distribution and $0.72530$ with the estimated discrete distribution. In each model, it gives the change in log odds for a one-unit increase in $x$ within a cluster.
The difference between the population means of the cluster-specific intercepts is more conspicuous. The normal fit gives $-0.19120$ and the discrete fit gives $-0.80079$. A mass of about $0.029$ at an intercept near $-24$ contributes about $-0.696$ to that last mean.
The log likelihoods are $-422.0517$ and $-420.2836$, respectively. The first value negates the printed negative marginal log likelihood approximated by seven-point adaptive quadrature. Before interpreting their likelihood gap, evaluate both fits with a common, stable probability calculation and check the normal integral at higher quadrature orders. The displayed values use different numerical approximations and are not a calibrated likelihood-ratio test.
To predict a response in a new cluster, average success probabilities over the fitted population. The calculation below reproduces, from the saved fits, the predictions tabulated at the end of Section 12.8 for the same three covariate values. The far-left intercept contributes almost zero probability at each of them. For the discrete fit, multiply each conditional probability by the mass at its intercept and add the products. For the normal fit, integrate the conditional probability over a standard normal variable, scaling it by the fitted random-intercept SD.
1
2
3
4
5
6
7
8
d <- readRDS("data/derived/ch12/fits.rds")$discrete
normal_fit <- readRDS("data/derived/ch09/fits.rds")$adaptive
x <- c(-1, 0, 1)
new_site <- vapply(x, function(xj) sum(d$mass * plogis(d$beta*xj + d$mass_points)), 0.0)
normal <- vapply(x, function(xj) integrate(function(z)
plogis(sum(c(1, xj)*normal_fit$beta) + sqrt(normal_fit$G[1])*z) * dnorm(z),
-Inf, Inf, rel.tol=1e-10)$value, 0.0)
max(abs(new_site - normal))
At $x=-1$, $0$ and $1$, the probabilities under normal mixing are approximately $0.30067$, $0.45605$ and $0.61992$. The corresponding discrete-mixture predictions are $0.30081$, $0.45583$ and $0.61986$. The largest absolute difference, about $0.000213$, occurs at $x=0$. At these settings the two distributions predict nearly the same fraction of successes despite their different mean cluster-specific intercepts. The agreement demonstrated here is limited to these three covariate values; it does not establish equality of the mixing distributions or of predictions throughout the covariate range.