The EM algorithm and its extensions
A missing measurement leaves several possible versions of a person’s complete record. Those versions can imply different means and associations, even though they agree on everything observed. The simulated normal data illustrate this uncertainty, while the simulated mixture presents a related problem in which a person’s response is known but class membership is not. Choosing one completion would treat an uncertain value or membership as settled. The expectation-maximization (EM) algorithm instead lets possible completions contribute according to how plausible they are given the observed record and the current parameter values. The chapter develops the algorithm on two simulated examples, normal measurements with missing values and a two-class normal mixture, and follows it from its justification and implementation to its speed, its variants and the uncertainty of its estimates.
4.1 Observed-data likelihoods, complete-data likelihoods, and the Q function
These simulated examples treat people as independent sampling units. For a person in the normal sample, $y$ denotes the observed measurements and $z$ the missing measurements that would complete the record. In the mixture, $y$ is a single response and $z$ identifies the class that generated it. With the book directory as the working directory, the calculation starts from the two files of observations. The complete normal data and generating class labels are stored separately.
1
2
3
4
5
6
source("code/lib/stability.R", local = TRUE)
source("code/lib/mixture_em.R", local = TRUE)
source("code/practice/class-probability-tables.R", local = TRUE)
mix_y <- readRDS("data/simulated/ch04/MIX1.rds")
normal_missing <- readRDS("data/simulated/ch04/NORMAL3-missing.rds")
print(c(mixture_people = length(mix_y), normal_people = nrow(normal_missing)))
1
2
mixture_people normal_people
300 240
The 300 responses in MIX1 were simulated with seed 403. Each person had probability 0.4 of belonging to class one. The class means were 55 and 80, and both standard deviations were 6. For NORMAL3, seed 404 determined which measurements to remove from the existing 240 records. The column totals give the numbers missing.
1
print(colSums(is.na(normal_missing)))
1
2
y1 y2 y3
0 60 52
The first measurement was always recorded. The second was missing for 60 people. Its missingness probability was $\operatorname{logit}^{-1}(-1+0.5y_1)$, so missingness can depend on the recorded first measurement. This is missing at random (MAR). For 52 people, the third measurement was missing. Its missingness probability was 0.2 whatever the three measurement values, so the missingness of this third measurement is missing completely at random (MCAR). Together, the two independently generated missingness indicators form a MAR mechanism, because their joint probabilities depend only on the always-observed first measurement. The parameters of this mechanism place no restrictions on the normal mean and covariance, and those normal parameters place no restrictions on the missingness parameters. Under these conditions, likelihood inference about the normal parameters can omit the missingness mechanism and use each person’s observed measurements.
Which density does a partly observed record contribute? Let $\theta$ denote the parameters of the response model and $p_\theta(y,z)$ the joint density for a complete record, with the probability mass function for a discrete class. The observed-data density accounts for all possible completions. For missing measurements, it is $p_\theta(y)=\int p_\theta(y,z)\,dz$. For an unknown class, it is $p_\theta(y)=\sum_k p_\theta(y,z=k)$. Independence across the $n$ people makes the observed-data log likelihood $\ell(\theta)=\sum_{i=1}^n\log p_\theta(y_i)$. If all completions were known, the complete-data log likelihood at a candidate $\theta$ would be $\ell_c(\theta)=\sum_{i=1}^n\log p_\theta(y_i,z_i)$. The expectation step, or E step, averages that last expression over the completions. Writing $Z_i$ for the unobserved random variable or vector gives
\[Q(\theta\mid\theta^{\mathrm{old}}) =\sum_{i=1}^n E_{\theta^{\mathrm{old}}} \!\left[\log p_\theta(y_i,Z_i)\mid y_i\right].\]The current parameter $\theta^{\mathrm{old}}$ fixes the conditional distribution for each person. As the candidate $\theta$ varies, the log joint density inside the expectation changes. The maximization step, or M step, chooses the candidate that maximizes $Q$ with those conditional distributions fixed. For two classes, the observed-data log density takes the logarithm after adding the two joint densities. The expectation in $Q$ averages their logarithms.
For the normal sample, model the complete measurement vectors $X_i$ as independent multivariate normal vectors with a common mean $\mu$ and covariance $\Sigma$. Each $\mu_j$ is the population mean of measurement $j$, in that measurement’s units. Each $\Sigma_{jj}$ is its variance across people, in squared measurement units. The covariance $\Sigma_{jk}$ describes how measurements $j$ and $k$ on the same person vary together; a positive value means that higher values of one tend to accompany higher values of the other. Its units are the product of the two measurement units. These parameters describe the complete response distribution, including measurements that happen to be missing.
With $n$ fixed, the likelihood for this mean and covariance depends on the complete vectors through two sufficient statistics, $\sum_i X_i$ and $\sum_i X_iX_i^\top$. A missing measurement enters the first sum through its conditional mean given the observed measurements. Its product with an observed measurement uses that same mean times the observed value. Its square also depends on the conditional variance. To evaluate the observed-data likelihood at a proposed mean vector and positive definite covariance matrix, normal_loglik() uses the indices of the recorded measurements to select both the mean subvector and its covariance submatrix.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
normal_loglik <- function(y, mean, covariance) {
stopifnot(is.matrix(y), ncol(y) == length(mean),
identical(dim(covariance), c(ncol(y), ncol(y))))
contributions <- numeric(nrow(y))
for (i in seq_len(nrow(y))) {
observed <- which(!is.na(y[i, ]))
if (!length(observed)) next
# Restrict the covariance to the measurements observed for this person.
R <- chol(covariance[observed, observed, drop = FALSE])
residual <- y[i, observed] - mean[observed]
chol_scaled_residual <- forwardsolve(t(R), residual)
contributions[i] <- -length(observed) * log(2 * pi) / 2 -
sum(log(diag(R))) - sum(chol_scaled_residual^2) / 2
}
contributions
}
Here, R is the upper Cholesky factor of the covariance submatrix of the observed measurements. The sum of its log diagonal entries gives half the log determinant. The vector called chol_scaled_residual solves $R^\top u=y_o-\mu_o$. Its squared length is $(y_o-\mu_o)^\top\Sigma_{oo}^{-1}(y_o-\mu_o)$, the quadratic term in the normal log density. Applying sum() to the returned vector gives the observed-data log likelihood.
For the E step, suppose a pair of jointly normal measurements has current covariance 0.4, with zero means and respective variances 1 and 2. The first value observed is 0.5. Multiplying it by the regression slope $0.4/1$ gives the conditional mean for the missing second value. The regression leaves conditional variance $2-0.4^2/1$.
1
2
3
4
conditional_mean <- 0.4 * 0.5
conditional_variance <- 2 - 0.4^2
print(c(mean = conditional_mean, variance = conditional_variance,
second_moment = conditional_mean^2 + conditional_variance))
1
2
mean variance second_moment
0.20 1.84 1.88
The conditional mean of 0.20 enters the sum of measurements. Its square, 0.04, accounts for only part of the expected square. Adding the conditional variance of 1.84 gives 1.88.
Posterior class probabilities in the mixture
For the mixture, the E step replaces an unknown class by probabilities rather than by conditional moments. In the mixture, let $Z_i=k$ mean that person $i$ belongs to class $k$. At the current parameters, class $k$ has mixing proportion $\pi_k$ and normal density $f_k$ with mean $\mu_k$ and standard deviation $\sigma_k$. The proportion $\pi_k$ is the probability of membership in class $k$ before the response is observed, and the two proportions sum to one. Within that class, $\mu_k$ is the expected response and $\sigma_k$ describes the spread of people’s responses around it, both in response units. Increasing $\mu_k$ shifts that class’s response distribution upward; increasing $\sigma_k$ spreads it more widely around the same mean.
Their product $\pi_k f_k(y_i)$ is the joint density for response $y_i$ and class $k$. The indicator of membership in class $k$ equals one when $Z_i=k$ and zero otherwise. Dividing the joint density by the observed-data density gives the conditional mean of this indicator, the posterior class probability
\[w_{ik}=\Pr(Z_i=k\mid y_i,\theta^{\mathrm{old}}) =\frac{\pi_k f_k(y_i)}{\pi_1 f_1(y_i)+\pi_2 f_2(y_i)}.\]Here posterior refers to class membership conditional on the response, with the model parameters fixed. Both standard deviations are estimated separately and must be strictly positive. In the vector u used for fitting, the log odds $\log(\pi_1/\pi_2)$ come first, followed by both means and then both log standard deviations. The functions mix_pack() and mix_unpack() convert between scales. Each column of mix_terms() then gives one class’s log joint density.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
mix_pack <- function(probability, mean, sd) {
stopifnot(length(probability) == 2L, all(probability > 0),
abs(sum(probability) - 1) < 1e-12, length(mean) == 2L, length(sd) == 2L,
all(is.finite(mean)), all(is.finite(sd)), all(sd > 0))
unname(c(log(probability[1] / probability[2]), mean, log(sd)))
}
mix_unpack <- function(u) {
stopifnot(length(u) == 5L, all(is.finite(u)))
sd <- exp(u[4:5])
if (any(!is.finite(sd)) || any(sd <= 0)) stop("Invalid component SD")
list(probability = c(plogis(u[1]), plogis(-u[1])), mean = u[2:3], sd = sd,
log_probability = c(-log1pexp(-u[1]), -log1pexp(u[1])))
}
mix_terms <- function(u, y) {
model <- mix_unpack(u)
cbind(model$log_probability[1] + dnorm(y, model$mean[1], model$sd[1], log = TRUE),
model$log_probability[2] + dnorm(y, model$mean[2], model$sd[2], log = TRUE))
}
In the list returned by mix_unpack(u), probability[k] is $\pi_k$, mean[k] is $\mu_k$, and sd[k] is $\sigma_k$. The extra field log_probability[k] computes its logarithm directly from the log odds. For extreme finite inputs, probability[k] can round to zero while log_probability[k] remains finite. These are population parameters at the supplied u; the posterior probabilities $w_{ik}$ also depend on the person’s response and are calculated separately. For two log joint densities $a$ and $b$, the person’s marginal log density is $\max(a,b)+\log(1+\exp(-\vert a-b\vert ))$. Summing its negative over people gives the value of the negative observed-data log likelihood function computed by mix_nll().
1
2
3
4
5
6
7
8
9
mix_nll <- function(u, y) {
tryCatch({
terms <- mix_terms(u, y)
largest <- pmax(terms[, 1], terms[, 2])
if (any(!is.finite(largest))) return(Inf)
# Subtract the larger log joint density before summing the two components.
-sum(largest + log1p(exp(-abs(terms[, 1] - terms[, 2]))))
}, error = function(e) Inf)
}
The same two terms give posterior log odds $a-b$. The variable posterior_log_odds stores this log odds difference, rather than the odds ratio itself. Applying the inverse logit to that difference and its negative gives the two probabilities in a row of mix_estep().
1
2
3
4
5
6
7
8
9
10
mix_estep <- function(u, y) {
terms <- mix_terms(u, y)
# The log joint densities give the posterior log odds by subtraction.
posterior_log_odds <- terms[, 1] - terms[, 2]
weights <- cbind(plogis(posterior_log_odds), plogis(-posterior_log_odds))
stopifnot(!anyNA(weights))
list(weights = weights, count = colSums(weights),
sum_y = drop(crossprod(weights, y)), sum_y2 = drop(crossprod(weights, y^2)),
conditioning = u, n = length(y))
}
To initialize the mixture, quantile_partition() splits the responses at their median. The comparison with 1:2 turns these labels into a matrix with people in rows and classes in columns, assigning weight one to the selected class and zero to the other. Given the responses and this matrix, univariate_gaussian_mstep() estimates the class proportions, weighted means and variances. Both functions are in code/lib/mixture_em.R.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
quantile_partition <- function(x, k) {
x <- as.vector(x)
# Breaks: the unique sample quantiles at n equally spaced probabilities, with n raised
# from k + 1 until there are at least k + 1 of them.
n <- k + 1
q <- unique(quantile(x, seq(0, 1, length.out = n)))
while (length(q) < k + 1) {
n <- n + 1; q <- unique(quantile(x, seq(0, 1, length.out = n)))
}
# With too many breaks, drop those that begin the smallest gaps.
extra <- length(q) - (k + 1)
if (extra > 0) q <- q[-order(diff(q))[seq_len(extra)]]
# Move the outer breaks just beyond the data, by a margin relative to the spread of x.
margin <- sqrt(.Machine$double.eps) * sd(x)
q[c(1, length(q))] <- c(min(x) - margin, max(x) + margin)
# Class i: the observations from break i up to, not including, break i + 1.
cl <- numeric(length(x))
for (i in seq_len(k)) cl[q[i] <= x & x < q[i + 1]] <- i
cl
}
For $k$ classes, quantile_partition() takes the distinct sample quantiles at $k+1$ equally spaced probabilities as breaks, adding probabilities until there are at least $k+1$ distinct values and then dropping the breaks that begin the smallest gaps. The outer breaks are moved just beyond the smallest and largest observations, and class $i$ receives the observations from break $i$ up to, but not including, break $i+1$. With $k=2$ the breaks are the minimum, the median and the maximum.
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
univariate_gaussian_mstep <- function(x, z) {
n <- length(x); G <- ncol(z)
mixing_proportion <- mu <- sigma_sq <- rep(NA_real_, G)
sq <- z
smallest <- 1
for (k in 1:G) {
s <- 0; sum_mu <- 0
for (i in 1:n) { temp <- z[i, k]; s <- s + temp; sum_mu <- sum_mu + temp * x[i] }
mixing_proportion[k] <- s / n
smallest <- min(s, smallest)
if (s > sqrt(.Machine$double.eps)) {
sum_mu <- sum_mu / s
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
sq[i, k] <- temp
}
sigma_sq[k] <- sigma_sq_k / s
}
}
list(mixing_proportion = mixing_proportion, mean = mu, variance = sigma_sq, squares = sq, expected_count_check = smallest)
}
For class $k$, s sums column $k$ of z, the expected count $N_k$; mixing_proportion[k] is $N_k/n$, mu[k] is the weighted mean $\mu_k$ and sigma_sq[k] is the weighted average squared deviation $\sigma_k^2$. These are the updates derived in Section 4.3. Column $k$ of squares contains each $(y_i-\mu_k)^2$, and a class whose expected count is not above $\sqrt{\epsilon}$, with $\epsilon$ the machine precision, is left with missing estimates. The entry expected_count_check reports the smallest expected count, capped at one. At these values, ambiguous selects the person whose first posterior class probability is closest to one half.
1
2
3
4
5
6
7
8
mix_z0 <- outer(quantile_partition(mix_y, 2), 1:2, "==") * 1
# Estimate both groups from the initial classification.
mix_first_m <- univariate_gaussian_mstep(mix_y, mix_z0)
mix_start <- mix_pack(mix_first_m$mixing_proportion, mix_first_m$mean, sqrt(mix_first_m$variance))
mix_e <- function(u) mix_estep(u, mix_y)
first_e <- mix_e(mix_start)
ambiguous <- which.min(abs(first_e$weights[, 1] - 0.5))
print(c(person = ambiguous, response = mix_y[ambiguous], first_e$weights[ambiguous, ]))
1
2
person response
155.0000000 73.0732823 0.4398844 0.5601156
Person 155 had a response of 73.0732823. The two rows from class_density_row() trace the near-even split to the two joint densities.
1
2
3
4
log_joint <- as.numeric(mix_terms(mix_start, mix_y[ambiguous]))
probability <- as.numeric(first_e$weights[ambiguous, ])
class_table <- class_density_row(mix_y, ambiguous, log_joint, probability)
print(class_table, row.names = FALSE)
1
2
3
4
5
6
person response class joint_density posterior_class_probability
155 73.07328 1 0.004481630 0.4398844
155 73.07328 2 0.005706571 0.5601156
weighted_log_joint observed_log_density
-2.378793 -4.586525
-2.893634 -4.586525
Dividing 0.004481630 by the sum of the two joint densities, $0.004481630+0.005706571$, gives the first posterior probability, 0.4398844. Class two accounts for the remaining 0.5601156.
Each weighted_log_joint entry is the posterior probability times the log joint density in that row. At the starting parameters, the two weighted_log_joint entries add to about $-5.272427$ for this person. The repeated observed_log_density of $-4.586525$ counts once in the observed-data log likelihood.
For person 155, knowing the class would select one log joint density. Averaging over the unknown class gives a term from each row. Across people, the mixture’s Q function is
\[Q(\theta\mid\theta^{\mathrm{old}}) =\sum_{i=1}^n\sum_{k=1}^2 w_{ik} \log\!\left[\pi_k(\theta) f_k(y_i\mid\theta)\right].\]In mix_q(), sufficient$weights contains the probabilities from the E step and u specifies the candidate. A class with zero posterior probability contributes zero.
1
2
3
4
5
6
7
mix_q <- function(u, sufficient, y) {
weights <- sufficient$weights
# Evaluate candidate densities with posterior probabilities from the previous E step.
terms <- mix_terms(u, y)
active <- weights > 0
sum(weights[active] * terms[active])
}
At a new candidate, mix_terms() reevaluates both log joint densities while the two posterior probabilities remain fixed. Assigning person 155 wholly to the more probable class would replace the expected counts of about 0.44 and 0.56 by zero and one.
Summing the posterior probabilities down each class column gives the expected number of people in that class at the starting parameters.
1
print(first_e$count)
1
[1] 144.9821 155.0179
Each of the 300 rows of first_e$weights sums to one across its two class columns, so the expected counts sum to 300. The same columns weight the responses in sum_y and their squares in sum_y2. Each person therefore contributes to both sets of class totals in proportion to the person’s posterior class probabilities at the starting parameters. The R packages norm and mclust provide EM methods for incomplete normal measurements and normal mixtures, respectively.
4.2 Jensen’s inequality, monotonicity, and the connection to MM algorithms
Person 155 contributes to both classes when fitting the mixture. Why should an update based on such fractional counts improve a likelihood calculated from the responses alone? For one response $y$, let $q(z)$ be a trial distribution over its possible completions. In this mixture, take both mixing proportions and both standard deviations to be strictly positive, and let $q$ assign positive probability to each of the two classes, with total probability one. The support is then the same at every candidate considered below. The ratio $p_\theta(y,z)/q(z)$ then has expectation $p_\theta(y)$ under $q$, since multiplication by $q(z)$ in each term of the expectation cancels the denominator. Assuming the expectations are finite, the concavity of the logarithm gives Jensen’s inequality in the form
\[\begin{aligned} \log p_\theta(y) &=\log E_q\!\left[\frac{p_\theta(y,Z)}{q(Z)}\right]\\ &\ge E_q[\log p_\theta(y,Z)]-E_q[\log q(Z)] \equiv F(q,\theta). \end{aligned}\]The second term, $-E_q[\log q(Z)]$, is the entropy of the trial distribution. It measures uncertainty about class membership under the probabilities chosen for this person. For two classes it is largest when the probabilities are equal and approaches zero as either probability approaches one. For a missing continuous measurement, a normalized density on the same support replaces the class probabilities, integration replaces summation, and the second term is the differential entropy of that density.
Jensen’s inequality gives a lower bound for every such choice of $q$. Which choice makes it exact at the current parameters? Factoring the joint density into $p_\theta(y)\,p_\theta(z\mid y)$ separates a term that is constant over completions. Subtracting the bound from the observed-data log density leaves
\[\log p_\theta(y)-F(q,\theta) = E_q\!\left[\log\frac{q(Z)}{p_\theta(Z\mid y)}\right] = D_{\mathrm{KL}}\!\left(q\,\Vert\,p_\theta(\cdot\mid y)\right).\]This is the Kullback-Leibler divergence of $q$ relative to the posterior distribution at the parameter being evaluated. It is nonnegative by the inequality just derived. Strict concavity gives equality when the ratio inside Jensen’s inequality is constant with probability one under $q$. Its constant value must be $p_\theta(y)$, so $q(z)=p_\theta(z\mid y)$ on their common support, up to sets of probability zero. An exact E step makes this choice at the current parameters. For person 155, the starting probabilities 0.4398844 and 0.5601156 give entropy 0.685902. Adding it to the expected log joint density of $-5.272427$ recovers the observed-data log density of $-4.586525$.
For the full sample, the log likelihood $\ell$ and its bound are sums over independent people. Write $q^{\mathrm{old}}$ for the collection of their exact posterior distributions at $\theta^{\mathrm{old}}$, and $F$ for the summed bound. Its expected log joint density term is now $Q(\theta\mid\theta^{\mathrm{old}})$. During the parameter update, each person’s distribution remains fixed, so its entropy is the same at every candidate. For an update that respects the stated ranges of the model probabilities and variances and satisfies $Q(\theta^{\mathrm{new}}\mid\theta^{\mathrm{old}})\ge Q(\theta^{\mathrm{old}}\mid\theta^{\mathrm{old}})$, the comparisons are
\[\ell(\theta^{\mathrm{new}}) \ \ge\ F(q^{\mathrm{old}},\theta^{\mathrm{new}}) \ \ge\ F(q^{\mathrm{old}},\theta^{\mathrm{old}}) \ =\ \ell(\theta^{\mathrm{old}}).\]The equality on the right makes the old log likelihood the reference value. Moving left, the middle inequality follows from the choice of update, and the first inequality follows from Jensen’s inequality at the new parameters. Maximizing $Q$ is sufficient. A partial update also qualifies if it meets the same inequality. Repeating this argument establishes monotonicity of the observed-data log likelihood. This comparison of successive likelihoods does not by itself establish parameter convergence or attainment of a local or global maximum.
This construction makes EM a minorize-maximize (MM) algorithm. To minorize a criterion for maximization, one chooses a function that lies below it at every parameter value allowed by the model and equals it at the current point. Increasing this function then improves or preserves the criterion. EM constructs its minorizing function from the posterior distribution. For a fitting routine that minimizes the negative observed-data log likelihood, reversing the signs gives the majorize-minimize form. The function $-F$ bounds $-\ell$ from above and equals it at the current point. Reducing the upper bound from that common value can only reduce or preserve the negative log likelihood.
In the MIX1 session, mix_y contains the 300 responses and first_e contains the posterior class probabilities at mix_start. Binding the responses to mix_nll() gives mix_fn(), the negative observed-data log likelihood as a function of the working parameters. The lower bound adds the entropy of the two class probabilities for each person to the sample’s $Q$. A zero probability contributes zero to entropy.
1
2
3
4
5
6
7
mix_fn <- function(u) mix_nll(u, mix_y)
mixture_bound <- function(u, sufficient, y) {
w <- sufficient$weights
entropy <- -sum(w[w > 0] * log(w[w > 0]))
mix_q(u, sufficient, y) + entropy
}
The class totals in first_e also determine the updated parameters. The expected count divided by 300 gives the updated mixing proportion. Dividing the weighted response sum by that count gives the class mean. Its weighted second moment less the squared mean gives its variance. For comparison, the code also evaluates the midpoint between the starting and updated working vectors. Thus each midpoint mean is an arithmetic average, while the proportions and standard deviations are averaged on the log-odds and log scales, respectively. All three evaluations use the same first_e.
1
2
3
4
5
6
7
8
9
10
next_mean <- first_e$sum_y / first_e$count
next_variance <- first_e$sum_y2 / first_e$count - next_mean^2
first_update <- mix_pack(first_e$count / first_e$n, next_mean, sqrt(next_variance))
trial_parameters <- list(old = mix_start, intermediate = (mix_start + first_update) / 2,
updated = first_update)
# Keep the starting posterior probabilities at all three trial points.
bound_table <- t(vapply(trial_parameters, function(u) {
c(loglik = -mix_fn(u), bound = mixture_bound(u, first_e, mix_y))
}, numeric(2)))
print(cbind(bound_table, gap = bound_table[, 1] - bound_table[, 2]))
1
2
3
4
loglik bound gap
old -1161.570 -1161.570 4.547474e-13
intermediate -1159.619 -1159.942 3.220912e-01
updated -1158.207 -1159.427 1.220364e+00
At the start, both columns give $-1161.570$, with a gap of $4.55\times10^{-13}$ from rounding. At the midpoint, the bound of $-1159.942$ lies 0.322 below the log likelihood of $-1159.619$. At the update, the bound has risen to $-1159.427$ and the log likelihood to $-1158.207$. The gap of 1.220 is positive because the starting probabilities no longer equal the posteriors at the updated parameters. Each gap uses the unrounded values of the two columns.
Could equal class probabilities give the same guarantee? For this comparison, the reference point is the finite vector returned after minimizing the negative log likelihood from mix_start. With NULL in place of a gradient, bfgs() (Section 3.3) uses central differences. The returned vector in fitted_mixture$par determines each person’s exact probabilities in correct. The copy wrong gives both classes probability one half for every response. Those are valid probabilities for a trial bound, but they are not the conditional class probabilities required by the E step at this reference point.
1
2
3
4
5
6
7
8
source("code/lib/result.R")
source("code/lib/quasi_newton.R")
fitted_mixture <- bfgs(mix_fn, NULL, mix_start)
stopifnot(fitted_mixture$converged)
correct <- mix_e(fitted_mixture$par)
wrong <- correct
wrong$weights[,] <- 0.5
Assigning each person probability one half for each class gives each class an expected count of 150. The common multiplier one half cancels in each weighted mean and variance. Both classes are therefore assigned the overall mean and the variance about it computed with divisor 300. These values maximize the weighted complete-data log likelihood for those probabilities. Of the fields in each E-step object, only its matrix of probabilities enters the bound. Both evaluations of the uniform bound use the matrix of halves.
1
2
3
4
5
6
7
8
9
10
wrong_candidate <- mix_pack(c(0.5, 0.5), rep(mean(mix_y), 2),
rep(sqrt(mean((mix_y - mean(mix_y))^2)), 2))
# Use uniform probabilities at both parameter vectors for the change in the bound.
print(c(posterior_bound_gap = -mix_fn(fitted_mixture$par) -
mixture_bound(fitted_mixture$par, correct, mix_y),
uniform_touching_gap = -mix_fn(fitted_mixture$par) -
mixture_bound(fitted_mixture$par, wrong, mix_y),
uniform_bound_gain = mixture_bound(wrong_candidate, wrong, mix_y) -
mixture_bound(fitted_mixture$par, wrong, mix_y),
observed_loglik_gain = -mix_fn(wrong_candidate) + mix_fn(fitted_mixture$par)))
1
2
posterior_bound_gap uniform_touching_gap uniform_bound_gain observed_loglik_gain
2.501110e-12 1.121972e+03 1.058958e+03 -6.301414e+01
At the BFGS solution, the exact probabilities give equality to rounding. The gap is $2.50\times10^{-12}$. With uniform probabilities, the bound starts 1121.972 below the observed-data log likelihood. The update raises this bound by 1058.958 while the observed-data log likelihood falls by 63.014. At the new point, the two fitted components are identical and equally probable, so one half is now the exact posterior probability for each class. The uniform bound reaches the log likelihood at the new point, after its gain has covered only part of the initial gap. The step that fails in the monotonicity proof is equality at the old parameters. Normal mixtures can be fitted by EM with the R package mclust.
4.3 Implementing E and M steps for missing normal data and a normal mixture
For the normal measurements, the E step requires conditional moments for each pattern of missing values. One person’s first two measurements are recorded and the third is missing. If the third measurement covaries with either of the first two, their observed values help predict it. How much uncertainty remains in that prediction? Let $X_i$ be the complete normal vector for person $i$. Use $o$ for the indices observed in this row and $m$ for those missing. Partition the current mean $\mu$ and positive definite covariance $\Sigma$ by these indices. The matrix $B=\Sigma_{mo}\Sigma_{oo}^{-1}$ gives the regression coefficients of the missing measurements on the observed ones. Each entry gives the change in one missing measurement’s conditional mean for a one-unit increase in one observed measurement, with the other observed values fixed.
To see why, consider the residual $X_{im}-\mu_m-B(X_{io}-\mu_o)$. Its covariance with $X_{io}$ is $\Sigma_{mo}-B\Sigma_{oo}=0$. The residual and the observed subvector are jointly normal, so they are independent. Its mean is zero and its covariance is $\Sigma_{mm}-B\Sigma_{om}$. Conditioning on the recorded value $X_{io}=y_{io}$ therefore gives
\[\begin{aligned} m_i &= E[X_{im}\mid y_{io}] = \mu_m+B(y_{io}-\mu_o),\\ V_i &= \operatorname{Cov}(X_{im}\mid y_{io}) = \Sigma_{mm}-B\Sigma_{om}. \end{aligned}\]The matrix $V_i$ describes the remaining variation in the missing measurements after conditioning on this person’s recorded values, with the model parameters fixed. Two people with the same pattern of observed measurements share $B$ and $V_i$ at these parameter values. Their recorded values can differ, so each needs a separate conditional mean.
Let $a_i$ be the full vector with the recorded values in positions $o$ and $m_i$ in positions $m$. The E step also needs a full covariance matrix $C_i$ conditional on this person’s observations. Its missing-by-missing block is $V_i$. Every row or column corresponding to a known value is zero because that value is fixed under conditioning. Since each second moment is the sum of a covariance and an outer product of means, the expected sufficient statistics for $n$ independent people are
\[s_1=\sum_{i=1}^n a_i,\qquad S_2=\sum_{i=1}^n E[X_iX_i^\top\mid y_{io}] =\sum_{i=1}^n (a_i a_i^\top+C_i).\]In the session containing normal_missing, the working vector u begins with the means, followed by the entries of the lower Cholesky factor with its diagonal on the log scale. The conversion in normal_estep() reconstructs the covariance. The row indices in patterns group together people with the same observed columns.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
source("code/lib/transforms.R")
normal_estep <- function(u, y) {
p <- ncol(y)
mean <- u[seq_len(p)]
covariance <- logchol_to_cov(u[-seq_len(p)])
patterns <- split(seq_len(nrow(y)), apply(!is.na(y), 1, paste0, collapse = ""))
sum_y <- numeric(p)
sum_yy <- matrix(0, p, p)
for (rows in patterns) {
observed <- which(!is.na(y[rows[1], ]))
missing <- which(is.na(y[rows[1], ]))
completed <- y[rows, , drop = FALSE]
conditional_cov <- matrix(0, p, p)
Within each group, completed has one row per person. The call to R’s sweep() subtracts the means of the observed measurements. This array operation is separate from the regression sweep operator used later inside mvn_missing_em() through the imported function mvn_sweep(). Multiplying those residuals by the regression coefficients and adding the means of the missing measurements fills each row with its conditional expectations. For complete rows the covariance correction is zero. A row with no observations would contribute the unconditional moments. In these data the first measurement is always observed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if (length(missing)) {
if (length(observed)) {
# Reuse this regression for every person with this pattern.
regression <- covariance[missing, observed, drop = FALSE] %*%
solve(covariance[observed, observed, drop = FALSE])
residual <- sweep(completed[, observed, drop = FALSE], 2, mean[observed])
completed[, missing] <- sweep(residual %*% t(regression), 2, mean[missing], "+")
conditional_cov[missing, missing] <- covariance[missing, missing, drop = FALSE] -
regression %*% covariance[observed, missing, drop = FALSE]
} else {
completed[,] <- matrix(rep(mean, each = length(rows)), length(rows))
conditional_cov <- covariance
}
}
sum_y <- sum_y + colSums(completed)
# Add the conditional covariance once for each row in the pattern.
sum_yy <- sum_yy + crossprod(completed) + length(rows) * conditional_cov
}
list(sum_y = sum_y, sum_yy = sum_yy, n = nrow(y), conditioning = u,
patterns = length(patterns))
}
The 240 records have four patterns. There are 143 complete rows, 45 missing only the second measurement, 37 missing only the third, and 15 missing both. Multiplying conditional_cov by the number of rows in its pattern adds one copy of the appropriate covariance per person. Grouping saves repeated regressions while preserving every person’s contribution. Summing the completed rows gives sum_y, and summing their outer products with the covariance corrections gives sum_yy.
How do these two sums determine the normal M step? With the conditional moments fixed, the expected sum of centered outer products about a candidate mean $\mu$ is $A(\mu)=S_2-s_1\mu^\top-\mu s_1^\top+n\mu\mu^\top$. Up to terms independent of the candidate, the expected complete-data log likelihood is
\[Q=-\frac n2\log|\Sigma|-\frac12\operatorname{tr}\{\Sigma^{-1} A(\mu)\}.\]The derivative of $Q$ with respect to $\mu$ is $\Sigma^{-1}(s_1-n\mu)$, which vanishes at $\mu^+=s_1/n$. At this mean, differentiating with respect to the precision $\Sigma^{-1}$ gives $(n\Sigma-A(\mu^+))/2$. Thus the maximizing positive definite covariance matrix is $\Sigma^+=S_2/n-\mu^+(\mu^+)^\top$ when the centered matrix is positive definite. At that mean the criterion is strictly concave in the precision, so a stationary point with positive definite covariance gives the maximum over positive definite covariance matrices. The divisor $n$ comes from the log determinant term contributed by each of the $n$ people. In normal_mstep(), these updates use exactly the two sums returned by the E step.
1
2
3
4
5
6
normal_mstep <- function(sufficient, old) {
mean <- sufficient$sum_y / sufficient$n
covariance <- sufficient$sum_yy / sufficient$n - tcrossprod(mean)
covariance <- (covariance + t(covariance)) / 2
c(mean, cov_to_logchol(covariance))
}
Averaging the covariance with its transpose removes asymmetry from rounding before cov_to_logchol() converts it to working coordinates. The fitted log likelihood still sums normal log densities for the subvectors actually observed. Using the filled rows as complete observations in that calculation would treat their conditional means as measured values.
In the mixture, it is class membership that is missing. For response $y_i$, let $w_{ik}$ be the posterior probability of class $k$ under the current parameters and let $N_k=\sum_i w_{ik}$. The terms in $Q$ involving the mixing proportions are $\sum_k N_k\log\pi_k$. Under the constraint $\sum_k\pi_k=1$, their derivatives $N_k/\pi_k$ must equal the same multiplier. Summing the expected counts gives $n$, so $\pi_k^+=N_k/n$. For a class with $N_k>0$ and variance $v_k=\sigma_k^2>0$, the terms involving its mean and variance are $-(N_k/2)\log v_k-\sum_i w_{ik}(y_i-\mu_k)^2/(2v_k)$. Setting the derivative with respect to $\mu_k$ to zero makes the weighted residuals sum to zero. Differentiating in $v_k$ then equates the variance to the weighted average squared residual. Expanding the square gives the updates
\[\mu_k^+=\frac{\sum_i w_{ik}y_i}{N_k},\qquad (\sigma_k^2)^+=\frac{\sum_i w_{ik}y_i^2}{N_k}-(\mu_k^+)^2.\]In the original session, first_e$weights contains the probabilities at mix_start. The sums already in first_e give the next working vector first_update. The general update raises an error for an empty class or a nonfinite or nonpositive updated variance.
1
2
3
4
5
6
7
8
9
10
11
mix_mstep <- function(sufficient, old) {
if (any(sufficient$count <= 0)) stop("Empty component")
mean <- sufficient$sum_y / sufficient$count
variance <- sufficient$sum_y2 / sufficient$count - mean^2
if (any(!is.finite(variance)) || any(variance <= 0)) stop("Degenerate component")
mix_pack(sufficient$count / sufficient$n, mean, sqrt(variance))
}
next_mean <- first_e$sum_y / first_e$count
next_variance <- first_e$sum_y2 / first_e$count - next_mean^2
first_update <- mix_pack(first_e$count / first_e$n, next_mean, sqrt(next_variance))
The square root passed to mix_pack() converts these variances to standard deviations.
The same fits with the library routines
The functions above express the E and M steps directly through conditional moments. The following standalone example, also in code/practice/4.3.R, fits both models with the library routines: the mixture updates use a matrix of class probabilities, and the normal routine computes the same moments by standardizing the data and sweeping by missingness pattern. Begin this example in a separate R session in the book directory. Here first_e will contain the mixture library’s result, with posterior probabilities in z; the original session’s first_e contains weights and class totals.
The median split supplies an initial classification. Its M step gives the parameters for the first E step, whose probabilities then supply the next M step.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.libPaths(c(".R-library", .libPaths()))
source("code/lib/stability.R")
source("code/lib/mixture_em.R")
source("code/lib/mvn_missing_em.R")
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
responses <- readRDS("data/simulated/ch04/MIX1.rds")
observed <- readRDS("data/simulated/ch04/NORMAL3-missing.rds")
initial_class <- quantile_partition(responses, 2)
initial_membership <- outer(initial_class, 1:2, "==") * 1
# Estimate from the median groups, then refresh the class probabilities.
first_m <- univariate_gaussian_mstep(responses, initial_membership)
first_e <- univariate_gaussian_estep(responses, first_m$mixing_proportion, first_m$mean,
first_m$variance, first_m$squares)
updated <- univariate_gaussian_mstep(responses, first_e$z)
mixture_update <- data.frame(class = 1:2, mass = updated$mixing_proportion, mean = updated$mean,
variance = updated$variance)
print(mixture_update)
1
2
3
class mass mean variance
1 1 0.4832738 57.49379 67.70668
2 2 0.5167262 81.87949 24.77762
In the column named mass, which contains mixing proportions, dividing the expected count of 144.9821 by 300 gives the first class proportion, 0.48327. With those same probabilities weighting the observations, its updated mean is 57.49379 and its variance is 67.70668. For the other class, the corresponding values are 0.51673, 81.87949 and 24.77762.
The matrix first_m$squares contains each person’s squared deviation from each class mean returned in first_m, with people in rows and classes in columns. The function univariate_gaussian_estep() reuses these deviations in the normal densities and returns refreshed posterior probabilities in z and the observed-data log likelihood in loglik.
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
univariate_gaussian_estep <- function(x, mixing_proportion, mu, sigma_sq, squares = outer(x, mu, function(a, b) (a - b) * (a - b))) {
n <- length(x); G <- length(mixing_proportion)
huge_value <- 1.7976931348623157e308; log_floor <- -708; log_2pi <- 1.837877066409345
z <- squares
for (k in 1:G) {
const <- log_2pi + log(sigma_sq[k])
z[, k] <- -(const + (z[, k] / sigma_sq[k])) / 2
}
z_max <- rep(-huge_value, n)
for (k in 1:G) if (mixing_proportion[k] == 0) z[, k] <- 0 else {
z[, k] <- log(mixing_proportion[k]) + z[, k]
z_max <- pmax(z_max, z[, k])
}
rowsum <- numeric(n)
for (k in 1:G) if (mixing_proportion[k] != 0) {
temp <- z[, k] - z_max
keep <- temp >= log_floor
z[, k] <- ifelse(keep, exp(temp), 0)
rowsum <- ifelse(keep, rowsum + z[, k], rowsum)
}
terms <- log(rowsum) + z_max
ll_sum <- 0
for (i in 1:n) ll_sum <- ll_sum + terms[i]
list(z = z * (1 / rowsum), loglik = ll_sum)
}
The first loop replaces each squared deviation by $\log f_k(y_i)=-\lbrace \log(2\pi)+\log\sigma_k^2+(y_i-\mu_k)^2/\sigma_k^2\rbrace /2$, and the second adds $\log\pi_k$. Subtracting each row’s largest term z_max before exponentiating gives terms between zero and one; a term below $e^{-708}$ is set to zero, and a class with $\pi_k=0$ receives probability zero. Then rowsum multiplied by the exponential of z_max is $\sum_k\pi_kf_k(y_i)$, so terms contains each person’s log likelihood contribution and loglik their sum. Dividing each row by rowsum gives the posterior probabilities $w_{ik}$. Passing first_e$z to the M step updates all class parameters using these probabilities.
Each new E step recomputes the conditional moments at the current parameters. For the normal sample, mvn_prepare() centers each column at the mean of its observed entries and, when this scale is positive, divides by the square root of their centered sum of squares divided by their count. It sorts rows by pattern.
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
mvn_prepare <- function(x) {
if (is.vector(x)) x <- matrix(x, ncol = 1)
storage.mode(x) <- "double"; n <- nrow(x); p <- ncol(x)
is_missing <- is.na(x)
# Each row's pattern of missing values as one integer, 1 + sum of 2^(j - 1) over missing j.
pattern_code <- as.integer(drop(is_missing %*% 2^(seq_len(p) - 1)) + 1)
sorted <- order(pattern_code)
pattern_code <- pattern_code[sorted]
x <- matrix(x[sorted, , drop = FALSE], n, p)
pattern_start <- which(!duplicated(pattern_code))
n_patterns <- length(pattern_start); row_order <- order(sorted)
# The observed variables of each pattern, from the pattern's first row, as 0/1 integers.
r <- matrix(as.integer(!is_missing[sorted, , drop = FALSE][pattern_start, ]), n_patterns, p)
# Rows are now grouped by pattern; row_order restores the original order.
col_mean <- numeric(p); col_sd <- numeric(p)
for (j in seq_len(p)) {
sum1 <- 0; sum2 <- 0; count <- 0L
for (i in seq_len(n)) if (!is.na(x[i, j])) {
count <- count + 1L
sum1 <- sum1 + x[i, j]
sum2 <- sum2 + x[i, j] * x[i, j]
}
if (count > 0L) {
col_mean[j] <- sum1 / count
col_sd[j] <- sqrt((sum2 - (sum1 * sum1) / count) / count)
x[, j] <- x[, j] - col_mean[j]
if (col_sd[j] > 0) x[, j] <- x[, j] / col_sd[j] else col_sd[j] <- 1
} else col_sd[j] <- 1
}
slot <- matrix(0L, p + 1L, p + 1L)
slot_n <- 0L
for (j in 0:p) {
slot_n <- slot_n + 1L
slot[j + 1L, j + 1L] <- slot_n
if (j < p) for (k in (j + 1L):p) {
slot_n <- slot_n + 1L
slot[j + 1L, k + 1L] <- slot_n
slot[k + 1L, j + 1L] <- slot_n
}
}
pattern_size <- diff(c(pattern_start, n + 1L))
list(x = x, n = n, p = p, r = r, row_order = row_order, pattern_start = pattern_start, pattern_size = pattern_size, n_patterns = n_patterns,
col_mean = col_mean, col_sd = col_sd, d = as.integer((p + 1) * (p + 2) / 2), slot = slot)
}
Each row’s missing variables are coded as one integer, one plus $\sum_j2^{j-1}$ over the missing columns $j$, and the rows are sorted by that code, so rows with the same pattern are adjacent; pattern_start and pattern_size give each pattern’s first row and number of rows, and row_order restores the original order. Row $g$ of r marks with ones the variables observed in pattern $g$. The column means and standard deviations use the observed entries only, with divisor equal to their count, and are stored in col_mean and col_sd for the return to measurement units. The matrix slot numbers the $(p+1)(p+2)/2$ distinct entries of the symmetric $(p+1)\times(p+1)$ matrix described next, row by row, each row starting at the diagonal.
In mvn_missing_em(), theta stores each distinct entry of the symmetric matrix $\begin{pmatrix}-1&\mu^\top\cr \mu&\Sigma\end{pmatrix}$ once. Row and column zero represent the constant. The integer array slot gives the vector index for each matrix entry, and P(i, j) retrieves that index; slot does not contain parameter estimates. The initial standardized means are zero and the initial covariance is the identity. Observed sums and products can be calculated once because they do not change with the parameters.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
mvn_missing_em <- function(s, max_iter = 1000, criterion = 1e-4) {
p <- s$p; d <- s$d; slot <- s$slot; x <- s$x
P <- function(i, j) slot[i + 1L, j + 1L]
theta <- numeric(d); theta[1] <- -1
for (j in seq_len(p)) theta[P(j, j)] <- 1
rows <- function(pat) s$pattern_start[pat] + seq_len(s$pattern_size[pat]) - 1L
t_obs <- numeric(d); t_obs[1] <- 1
for (pat in seq_len(s$n_patterns)) {
obs_cols <- which(s$r[pat, ] == 1L)
for (i in rows(pat)) for (j in seq_along(obs_cols)) {
t_obs[P(0, obs_cols[j])] <- t_obs[P(0, obs_cols[j])] + x[i, obs_cols[j]]
for (k in j:length(obs_cols)) t_obs[P(obs_cols[j], obs_cols[k])] <- t_obs[P(obs_cols[j], obs_cols[k])] +
x[i, obs_cols[j]] * x[i, obs_cols[k]]
}
}
it <- 0L; converged <- FALSE
history <- list(theta)
At each iteration, t starts with those observed totals. The sweep operator converts the mean and covariance entries into coefficients and residual covariances for regression on the observed variables. Sweeping on an observed variable performs this conversion for that variable. Reversing that sweep restores the variable when the next pattern requires it. After all the observed variables of a pattern have been swept, work[P(0, j)] gives the conditional intercept for missing variable j and work[P(k, j)] gives its coefficient for observed variable k. With both indices missing, the same array contains the conditional covariance. That is the extra term in the update of each missing pair.
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
while (!converged && it < max_iter) {
old <- theta
work <- old
t <- t_obs
cond_mean <- numeric(p)
for (pat in seq_len(s$n_patterns)) {
for (j in seq_len(p)) {
if (s$r[pat, j] == 1L && work[P(j, j)] > 0) work <- mvn_sweep(work, j, slot, p, 1)
else if (s$r[pat, j] == 0L && work[P(j, j)] < 0) work <-
mvn_sweep(work, j, slot, p, -1)
}
mis_cols <- which(s$r[pat, ] == 0L)
obs_cols <- which(s$r[pat, ] == 1L)
# Conditional means depend on the observed values of this row.
for (i in rows(pat)) {
for (j in mis_cols) {
cond_mean[j] <- work[P(0, j)]
for (k in obs_cols) cond_mean[j] <- cond_mean[j] + work[P(k, j)] * x[i, k]
}
for (jj in seq_along(mis_cols)) {
j <- mis_cols[jj]
t[P(0, j)] <- t[P(0, j)] + cond_mean[j]
for (k in obs_cols) t[P(k, j)] <- t[P(k, j)] + x[i, k] * cond_mean[j]
for (kk in jj:length(mis_cols)) {
k <- mis_cols[kk]
# The unswept block gives the covariance of two missing measurements.
t[P(k, j)] <- t[P(k, j)] + cond_mean[k] * cond_mean[j] + work[P(k, j)]
}
}
}
}
Division by the sample size gives the expected uncentered moments. Sweeping on the constant subtracts the product of the new means from each second moment and stores the result in the parameter representation. The loop saves every updated vector in history. It stops when the largest absolute change in any packed entry is at most $10^{-4}$ or after 1,000 iterations. The flag converged records whether the change met the tolerance.
1
2
3
4
5
6
7
8
9
t[2:d] <- t[2:d] / s$n
# Center the expected second moments at the new mean.
theta <- mvn_sweep(t, 0L, slot, p, 1)
it <- it + 1L
history[[it + 1L]] <- theta
converged <- !(max(abs(old - theta)) > criterion)
}
list(theta = theta, iterations = it, converged = converged, history = history)
}
The mixture loop begins each pass with an M step. It returns component_weight_too_small if the smallest sum of posterior class probabilities is at most $\sqrt{\epsilon}$, where $\epsilon$ is the machine epsilon, .Machine$double.eps, by default. The field expected_count_check stores the minimum of these expected counts and one; it is not a mixing proportion. With the default threshold below one, this truncation does not change the comparison. Once the counts pass that check, a variance at or below $\epsilon$ gives variance_too_small.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
univariate_gaussian_em <- function(x, z, tol = 1e-05, eps = .Machine$double.eps,
maxi = .Machine$integer.max) {
huge_value <- 1.7976931348623157e308
ll_prev <- huge_value / 2
iter <- 0L
path <- list()
repeat {
iter <- iter + 1L
m <- univariate_gaussian_mstep(x, z)
if (m$expected_count_check <= sqrt(eps))
return(list(mixing_proportion = m$mixing_proportion, mean = m$mean, variance = m$variance, z = z,
loglik = NA_real_,
iterations = iter, reason = "component_weight_too_small",
path = do.call(rbind, path)))
if (min(huge_value, m$variance) <= eps)
return(list(mixing_proportion = m$mixing_proportion, mean = m$mean, variance = m$variance, z = z,
loglik = NA_real_,
iterations = iter, reason = "variance_too_small", path = do.call(rbind, path)))
The E step now evaluates the observed-data log likelihood $\ell$ and supplies new probabilities for the next pass. Each path row pairs the current estimates with that likelihood. The test $\vert \ell-\ell_{\mathrm{old}}\vert /(1+\vert \ell\vert )\le10^{-5}$ uses the current log likelihood in the denominator. The initial value of ll_prev makes the first change large for these responses. Reaching the iteration limit while the change still exceeds tolerance returns iteration_limit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Evaluate the marginal log likelihood and refresh posterior class probabilities.
e <- univariate_gaussian_estep(x, m$mixing_proportion, m$mean, m$variance, m$squares)
z <- e$z
ll_sum <- e$loglik
err <- abs(ll_prev - ll_sum) / (1 + abs(ll_sum))
ll_prev <- ll_sum
path[[iter]] <- c(mixing_proportion = m$mixing_proportion, mean = m$mean, variance = m$variance, loglik = ll_sum)
if (!(err > tol && iter < maxi)) break
}
list(mixing_proportion = m$mixing_proportion, mean = m$mean, variance = m$variance, z = z, loglik = ll_sum,
iterations = iter, relative_change = err,
reason = if (err <= tol) "converged" else "iteration_limit",
path = do.call(rbind, path))
}
For the 300 responses, the mixture receives the initial membership matrix. For the normal sample of 240 people, the normal fit receives the standardized data and the indices for each pattern.
1
2
3
4
mixture <- univariate_gaussian_em(responses, initial_membership)
prepared <- mvn_prepare(observed)
normal <- mvn_missing_em(prepared)
The first row of mixture$path uses the original classification. Its second row contains the one-step updated estimates displayed above.
What changed for person 1 after the first normal update? In the separate session, normal$history[[1L]] contains the initial vector. Applying mvn_parameters() to the second vector restores means and covariances to measurement units.
1
2
3
4
5
6
7
mvn_parameters <- function(s, theta) {
p <- s$p
inner <- seq_len(p) + 1L; mu <- theta[s$slot[1, inner]] * s$col_sd + s$col_mean
sigma <- matrix(theta[s$slot[inner, inner]], p, p)
# Rescale by the standard deviations used to standardize the columns.
list(mu = mu, sigma = sigma * matrix(s$col_sd, p, p) * matrix(s$col_sd, p, p, byrow = TRUE))
}
Row and column zero of the stored matrix belong to the constant, so slot[1, inner] selects the standardized means and slot[inner, inner] the standardized covariances. Multiplying each mean by its column’s standard deviation and adding the column mean, and multiplying entry $(j,k)$ of the covariance by the standard deviations of columns $j$ and $k$, reverses the standardization of mvn_prepare(). Person 1 is the first row with exactly one missing measurement. The recorded values in observed[row, known], approximately $-0.32604$ and 1.69298, enter the regression for the third measurement.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
first_parameters <- mvn_parameters(prepared, normal$history[[2L]])
row <- which(rowSums(is.na(observed)) == 1L)[1]
known <- which(!is.na(observed[row, ]))
missing <- which(is.na(observed[row, ]))
mu <- first_parameters$mu
covariance <- first_parameters$sigma
regression <- covariance[missing, known, drop = FALSE] %*% solve(covariance[known, known])
conditional_mean <- mu[missing] + drop(regression %*% (observed[row, known] - mu[known]))
conditional_variance <- covariance[missing, missing] -
drop(regression %*% covariance[known, missing])
row_moments <- data.frame(person = row, missing_coordinate = missing, after_updates = 1,
conditional_mean = conditional_mean, conditional_variance = conditional_variance,
conditional_second_moment = conditional_mean^2 + conditional_variance)
print(row_moments)
1
2
3
4
person missing_coordinate after_updates conditional_mean
y3 1 3 1 -1.101683
conditional_variance conditional_second_moment
y3 1.06942 2.283127
Its expected value is $-1.10168$. The expected square is 2.28313 because the conditional variance of 1.06942 adds to the square of that mean.
Both fits at their stopping rules
Return to the original session with mix_y and normal_missing. The fits below put the returned estimates on the working scales of their negative observed-data log likelihood functions. The vector normal_start pairs the observed column means with an identity covariance on the original scale. The call to mvn_missing_em() takes normal_prepared and constructs its own starting vector after standardization.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
source("code/lib/mvn_missing_em.R")
source("code/lib/differentiation.R")
normal_start <- c(colMeans(normal_missing, na.rm = TRUE), cov_to_logchol(diag(3)))
normal_fn <- function(u) {
tryCatch(-sum(normal_loglik(normal_missing, u[1:3], logchol_to_cov(u[-(1:3)]))),
error = function(e) Inf)
}
normal_e <- function(u) normal_estep(u, normal_missing)
# The normal fit starts on the standardized scale defined by mvn_prepare().
normal_prepared <- mvn_prepare(normal_missing)
normal_run <- mvn_missing_em(normal_prepared)
normal_estimate <- mvn_parameters(normal_prepared, normal_run$theta)
normal_fit <- list(par = c(normal_estimate$mu, cov_to_logchol(normal_estimate$sigma)),
iterations = normal_run$iterations, converged = normal_run$converged)
normal_fit$value <- normal_fn(normal_fit$par)
The mixture starts from mix_z0. Since mix_fn() and normal_fn() return values of negative log likelihood functions, negating them gives the displayed log likelihood values. Negating a gradient leaves its largest absolute component unchanged.
1
2
3
4
5
6
7
8
mix_run <- univariate_gaussian_em(mix_y, mix_z0)
mix_fit <- list(par = mix_pack(mix_run$mixing_proportion, mix_run$mean, sqrt(mix_run$variance)),
iterations = mix_run$iterations, converged = mix_run$reason == "converged")
mix_fit$value <- mix_fn(mix_fit$par)
print(rbind(mixture = c(iterations = mix_fit$iterations, loglik = -mix_fit$value,
max_abs_score_component = max(abs(num_grad(mix_fn, mix_fit$par)$gradient))),
normal = c(iterations = normal_fit$iterations, loglik = -normal_fit$value,
max_abs_score_component = max(abs(num_grad(normal_fn, normal_fit$par)$gradient)))))
1
2
3
iterations loglik max_abs_score_component
mixture 14 -1152.8739 0.644655033
normal 7 -890.5341 0.005999577
The mixture stopped after 14 iterations at $-1152.8739$. Its final relative change, mix_run$relative_change, was $6.784011\times10^{-6}$. The largest absolute score component was still 0.644655 on the log-odds, mean and log standard deviation scales. The normal fit stopped after seven updates at $-890.5341$, with largest absolute score component 0.005999577 on its mean and log-Cholesky coordinates. These derivatives measure the slopes remaining when each fit met its own stopping rule. Unpacking the mixture vector returns the proportions and standard deviations on their original scales.
1
print(mix_unpack(mix_fit$par)[1:3])
1
2
3
4
5
6
7
8
$probability
[1] 0.4218257 0.5781743
$mean
[1] 55.40016 80.81526
$sd
[1] 6.397439 5.766341
The first fitted class accounts for about 42.2% of the population under this model. Its mean response is 55.40016, with within-class standard deviation 6.397439 response units. The other class has a higher mean, 80.81526, and a smaller within-class standard deviation, 5.766341. These proportions describe the population mixture; person-specific membership probabilities also use each response. For the normal sample, normal_estimate expresses the mean and covariance in the units of the three measurements.
1
print(normal_estimate)
1
2
3
4
5
6
7
8
$mu
[1] 0.008552729 0.711169699 -1.059571234
$sigma
[,1] [,2] [,3]
[1,] 0.8889652 0.21913132 0.20302834
[2,] 0.2191313 1.56667397 0.08015758
[3,] 0.2030283 0.08015758 1.09804820
The normal means are 0.00855, 0.71117 and $-1.05957$. For the covariance 0.21913 between the first two measurements, rows with both values recorded contribute their observed product. When the second is missing, its conditional mean multiplies the recorded first value. The M step averages those products and subtracts the product of the two updated means. After seven updates, entries 7 and 8 of normal_run$history contain the preceding and returned standardized vectors. Their largest absolute difference was $8.512145\times10^{-5}$, within the stopping tolerance. One further E and M step from normal_fit$par measures the displacement on the working scale used for the score vector.
1
print(max(abs(normal_mstep(normal_e(normal_fit$par), normal_fit$par) - normal_fit$par)))
1
[1] 3.555171e-05
This extra update changes the original-scale means and log-Cholesky coordinates by at most $3.555171\times10^{-5}$. The pattern sweeps and the direct conditional-moment calculation both average expected first and second moments. Standardization and covariance coordinates determine how large a parameter change appears. For both models, maximizing $Q$ with exact conditional moments produces an observed-data log likelihood at least as high as before. The supplied mvn_missing_em() is translated from norm, and univariate_gaussian_em() is adapted from the one-dimensional EM of mclust (code/NOTICE.md); these packages provide EM fits for incomplete normal data and for normal mixtures, respectively.
4.4 Missing information and the rate of convergence
The observed-data log likelihood can increase at every EM update while the parameter estimates move slowly toward their limit. With the observations fixed, let $M(\theta)$ be the result of taking an E step at $\theta$ and then maximizing $Q$. How much error remains after that update, measured from the limiting estimate for these data? At a fixed point $\hat\theta$, one more update returns $\hat\theta$. If the map is differentiable there, its first-order expansion gives
\[M(\theta)-\hat\theta =DM(\hat\theta)(\theta-\hat\theta)+o(\|\theta-\hat\theta\|).\]The Jacobian $DM$ has one row for each updated parameter and one column for each current parameter. It acts on the error written as a column vector.
Suppose the error points along an eigenvector $v$ of this Jacobian with eigenvalue $\lambda$. To first order, one update multiplies that error by $\lambda$. An eigenvalue close to one leaves almost the entire error for the next iteration. When the error spans several eigendirections, the components associated with smaller absolute eigenvalues decay faster. An error with a component in the slowest direction then contracts asymptotically at the rate set by the largest absolute eigenvalue, provided it is less than one. This describes behavior near the fixed point.
What determines these eigenvalues? Assume that $\hat\theta$ is a fixed point and a local maximum with a neighborhood in which all parameter values are allowed by the model. In this mixture, both mixing proportions and standard deviations are strictly positive. Assume that $Q$ and $\ell$ are twice continuously differentiable there, that the maximizing update $M$ is differentiable, and that derivatives can pass under the conditional integrals. An integrable bound on the differentiated integrands throughout this neighborhood is one sufficient condition for that interchange. Also assume that the complete-data and observed-data information matrices defined next are positive definite. Let $I_{\rm com}$ be the conditional expectation of the negative complete-data Hessian given the observations at $\hat\theta$. Let $I_{\rm obs}$ be the negative Hessian of the observed-data log likelihood there, and set $I_{\rm mis}=I_{\rm com}-I_{\rm obs}$. This difference measures information about the model parameters lost because the completions are unknown.
To relate these information matrices to the update, write $g(a,b)=\nabla_a Q(a\mid b)$, the gradient in the candidate with the conditioning parameter fixed. At $a=b$, the bound touches the log likelihood, so $g(b,b)$ equals the observed-data score vector. Writing $D_1$ and $D_2$ for derivatives with respect to the first and second arguments, differentiation along this diagonal gives $D_1g+D_2g=-I_{\rm obs}$ at the fixed point. The candidate derivative $D_1g$ is $-I_{\rm com}$, hence $D_2g=I_{\rm mis}$. Differentiating the exact M-step condition $g(M(b),b)=0$ now gives
\[-I_{\rm com}\,DM(\hat\theta)+I_{\rm mis}=0,\qquad DM(\hat\theta)=I_{\rm com}^{-1}I_{\rm mis}.\]The gap between the log likelihood and its touching bound has a minimum of zero at contact, so its Hessian $I_{\rm mis}$ is positive semidefinite. For an eigenvector $v$, the matrix identity gives $I_{\rm mis}v=\lambda I_{\rm com}v$. Thus $\lambda=v^\top I_{\rm mis}v/(v^\top I_{\rm com}v)$ is the fraction of information missing in that direction. With the positive definite information matrices assumed above, these fractions are nonnegative and strictly less than one. The largest fraction governs the slowest local contraction.
The local rate of the mixture update
To measure the mixture update’s local rate, first define num_jacobian(). It estimates each Jacobian column by perturbing one input in both directions and differencing every output. Four step sizes, each half the preceding one, supply the central differences for Richardson extrapolation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
num_jacobian <- function(fn, par) {
f <- fn(par)
n <- length(par); n_est <- 4; tiny <- sqrt(.Machine$double.eps / 7e-7)
h <- abs(1e-4 * par) + 1e-4 * (abs(par) < tiny)
# est[, k, i] holds step k for coordinate i; each step is half the last.
est <- array(NA, c(length(f), n_est, n))
unit <- function(i) seq_len(n) == i
for (k in seq_len(n_est)) {
# Perturb input i and record the change in every output.
for (i in seq_len(n)) est[, k, i] <- (fn(par + h * unit(i)) -
fn(par - h * unit(i))) / (2 * h[i])
h <- h / 2
}
# Combine adjacent step sizes to remove successive even powers of h.
for (m in seq_len(n_est - 1)) est <- (4^m * est[, -1, , drop = FALSE] -
est[, -dim(est)[2], , drop = FALSE]) / (4^m - 1)
list(jacobian = array(est, dim(est)[c(1, 3)]), map_evaluations = 1L + 2L * n_est * n)
}
Each extrapolation cancels the next even power of the step size. In the original R session containing mix_y and mix_fit, define mix_map() to convert the five working coordinates to mixture parameters, refresh the class probabilities, update the parameters and return to working coordinates. The numerical Jacobian therefore has five rows and five columns. Evaluate it at mix_fit$par, the vector returned when the mixture met its likelihood-change tolerance.
1
2
3
4
5
6
7
8
mix_map <- function(u) {
model <- mix_unpack(u)
e <- univariate_gaussian_estep(mix_y, model$probability, model$mean, model$sd^2)
m <- univariate_gaussian_mstep(mix_y, e$z)
mix_pack(m$mixing_proportion, m$mean, sqrt(m$variance))
}
map_derivative <- num_jacobian(mix_map, mix_fit$par)
print(eigen(map_derivative$jacobian)$values)
1
[1] 7.448373e-01 1.567867e-01 3.058602e-03 5.052780e-10 -8.059984e-11
The Jacobian was evaluated at the stopped EM estimate, rather than an exact fixed point. Its leading eigenvalue, 0.7448, gives an approximate local rate: an update near the limiting solution would retain about three quarters of an error in the slowest direction. The next two eigenvalues are 0.1568 and 0.0031. The last two are zero to numerical precision. The posterior log odds for response $y$ are a constant plus $(y-\mu_2)^2/(2\sigma_2^2)-(y-\mu_1)^2/(2\sigma_1^2)$. The three quadratic coefficients determine all probabilities entering the M step, so the exact update Jacobian has rank at most three.
Examples with known contraction rates
A scalar normal mean allows a direct check of the information fraction. For the first measurement of the 240 complete NORMAL3 records, assume independent normal responses with a common unknown mean $\mu$ and variance fixed at one. Here $\mu$ is the population mean of this measurement in response units, and the unit variance describes variation between people. Both masked samples below estimate this same mean.
For each mask, let $n_o$ and $n_m$ be the observed and missing counts, $n=n_o+n_m$, and $\bar y_o$ the mean of its observed values. A missing response contributes the current mean $\mu$ to the expected total. Thus
\[M(\mu)=\frac{n_o\bar y_o+n_m\mu}{n},\qquad M(\mu)-\bar y_o=\frac{n_m}{n}(\mu-\bar y_o).\]Two new masks compare the same uniforms from seed 100404 with thresholds 0.10 and 0.70.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
normal_complete <- as.matrix(readRDS("data/simulated/ch01/NORMAL3.rds"))
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(100404)
mask_uniforms <- runif(nrow(normal_complete))
mean_rate_runs <- lapply(c(0.1, 0.7), function(fraction) {
observed <- mask_uniforms >= fraction
target <- mean(normal_complete[observed, 1])
# Each missing response contributes the current mean.
map <- function(mean) (sum(normal_complete[observed, 1]) + sum(!observed) * mean) / 240
path <- target + 1
for (iteration in 1:20) path <- c(path, map(tail(path, 1)))
list(observed = observed, target = target, path = path,
rate = num_jacobian(map, target)$jacobian[1, 1],
information = sum(observed), n = 240L)
})
print(t(vapply(mean_rate_runs, function(x) c(observed = sum(x$observed), rate = x$rate,
observed_information_fraction = x$information / x$n,
error_after_five = x$path[6] - x$target), numeric(4))))
1
2
3
observed rate observed_information_fraction error_after_five
[1,] 216 0.1000 0.9000 0.0000100
[2,] 69 0.7125 0.2875 0.1836218
The thresholds leave 216 and 69 measurements observed. The numerical rates, 0.10 and 0.7125, equal the realized missing fractions, $24/240$ and $171/240$.
Each path starts one unit above its own fixed point $\bar y_o$. After five updates, its remaining error is exactly $(n_m/n)^5$, giving 0.00001 and 0.18362 in the two rows. With known unit variance, each observed response contributes one unit of information about the mean. The observed fraction is $n_o/n$, or 0.9000 and 0.2875. Its complement accounts for the two contraction factors.
Class overlap can hide information even when every response is recorded. Consider two normal components with known means equally spaced about zero and known standard deviations of one. Only $p$, the population proportion in class 1 before observing a response, is estimated. Since both component standard deviations are one, the difference between their means also gives their separation in standard deviation units. To represent a generating proportion of 0.5, each component contributes 300 fixed points. They are its mean plus the standard normal quantiles at $(i-0.5)/300$, for $i=1,\ldots,300$. For each response, normalize_logweights() turns the two log joint densities into posterior probabilities. The update averages the first column over all 600 responses. The function objective() uses logsumexp() to obtain the log marginal density for each response and sums their negatives.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
quantile_errors <- qnorm((seq_len(300) - 0.5) / 300)
mass_rate_runs <- lapply(c(4, 0.7), function(separation) {
means <- c(-separation / 2, separation / 2)
y <- c(means[1] + quantile_errors, means[2] + quantile_errors)
map <- function(p) {
terms <- cbind(log(p) + dnorm(y, means[1], log = TRUE),
log1p(-p) + dnorm(y, means[2], log = TRUE))
# Average the first posterior class probability across the 600 responses.
mean(t(apply(terms, 1, normalize_logweights))[, 1])
}
objective <- function(p) -sum(vapply(y, function(z) logsumexp(c(
log(p) + dnorm(z, means[1], log = TRUE),
log1p(-p) + dnorm(z, means[2], log = TRUE))), numeric(1)))
path <- 0.7
for (iteration in 1:40) path <- c(path, map(tail(path, 1)))
list(y = y, means = means, path = path, objective = objective,
rate = num_jacobian(map, 0.5)$jacobian[1, 1])
})
print(vapply(mass_rate_runs, function(x) x$rate, numeric(1)))
1
[1] 0.06861818 0.89025756
With means four units apart, an update near $p=0.5$ leaves about 6.9% of the error, as the derivative is 0.0686. Reducing the separation to 0.7 raises the derivative to 0.8903. The sample symmetry makes 0.5 a stationary point. Each log density is the logarithm of an affine function of $p$, strictly concave whenever the component densities differ. Hence 0.5 is the unique maximum for both deterministic sets of quantile points. The path for the closer components starts at 0.7.
1
2
3
4
5
slow_path <- mass_rate_runs[[2]]$path
slow_objectives <- vapply(slow_path, mass_rate_runs[[2]]$objective, numeric(1))
print(data.frame(iteration = c(0, 10, 20, 40),
mass_error = slow_path[c(1, 11, 21, 41)] - 0.5,
loglik_gap = slow_objectives[c(1, 11, 21, 41)] - mass_rate_runs[[2]]$objective(0.5)))
1
2
3
4
5
iteration mass_error loglik_gap
1 0 0.200000000 5.3809387441
2 10 0.066992267 0.5924014655
3 20 0.021101145 0.0586499851
4 40 0.002065177 0.0005616573
After 0, 10, 20 and 40 updates the proportion errors in the mass_error column are 0.200, 0.0670, 0.0211 and 0.0021. Subtracting the value of the negative log likelihood function at 0.5 from its value at each iterate gives the remaining log likelihood gains of 5.381, 0.592, 0.0586 and 0.00056. For a population comparison, write $f_1,f_2$ for the known component densities. The posterior probability $p f_1/[p f_1+(1-p)f_2]$ has derivative $4f_1f_2/(f_1+f_2)^2$ at 0.5. Averaging under the population density $(f_1+f_2)/2$ gives the population contraction factor, the expected fraction of information missing about $p$,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
population_rates <- vapply(c(4, 0.7), function(separation) {
integrand <- function(y) {
first <- dnorm(y, -separation / 2)
second <- dnorm(y, separation / 2)
total <- first + second
value <- numeric(length(y))
# Leave the contribution at zero wherever both densities underflow.
active <- total > 0
value[active] <- 2 * first[active] * second[active] / total[active]
value
}
stats::integrate(integrand, -Inf, Inf)$value
}, numeric(1))
print(cbind(separation = c(4, 0.7), population_rate = population_rates,
finite_data_rate = vapply(mass_rate_runs, function(x) x$rate, numeric(1))))
1
2
3
separation population_rate finite_data_rate
[1,] 4.0 0.06859741 0.06861818
[2,] 0.7 0.89013983 0.89025756
The population rates of 0.0686 and 0.8901 closely match the derivatives for the two sets of fixed normal quantiles. When both classes give a response nearly the same density, its posterior probability remains close to the current mixing proportion. Averaging many such probabilities changes the proportion slowly. In the quantile set with closer component means, only 0.0586 of log likelihood improvement remains after 20 updates, although the proportion is still more than two percentage points above its maximum likelihood estimate. The supplied num_jacobian() is adapted from jacobian() of numDeriv (code/NOTICE.md), which provides Richardson estimates of the Jacobian of a supplied map.
4.5 Conditional maximization with ECM and EC-MM
In the two-class normal mixture, a change in a class mean changes which responses are likely to belong to that class. Which probabilities should weight the squared deviations about the new mean? Ordinary EM uses one set of posterior class probabilities for the entire M step. Expectation-conditional maximization (ECM) divides the M step into a sequence of maximizations of $Q$, varying some parameters at each step and fixing the rest. Ordinary ECM uses the same $Q$ throughout these conditional maximizations. The version used here inserts an E step between the two maximizations and is called multicycle ECM: each cycle comprises an E step and one conditional maximization.
Let $w_{ik}$ be the posterior probability of class $k$ given response $y_i$ before the first conditional maximization. With positive expected counts $N_k=\sum_i w_{ik}$ and the standard deviations fixed, maximizing $Q$ gives the proportions $\pi_k^\ast =N_k/n$ and the means $\mu_k^\ast =\sum_i w_{ik}y_i/N_k$, where $n$ is the number of people. Recomputing the probabilities at these intermediate estimates gives new weights $\widetilde w_{ik}$ with column sums $\widetilde N_k$. With the means fixed at $\mu_k^\ast $, the second maximization gives
\[\pi_k^+=\frac{\widetilde N_k}{n},\qquad (\sigma_k^+)^2= \frac{\sum_i\widetilde w_{ik}(y_i-\mu_k^*)^2}{\widetilde N_k}.\]An observation whose probability of class $k$ increased enters that class’s residual sum of squares with the larger weight. The proportions are updated twice because each set of probabilities has its own expected counts. Adding the entropy of the starting probabilities to the first $Q$ bounds the observed-data log likelihood from below, with equality at the start. The first maximization therefore cannot lower the likelihood. Refreshing the probabilities makes the new bound equal the likelihood at the intermediate point. Maximizing this second $Q$ over the proportions and positive variances gives the same guarantee after both conditional maximizations when the weighted residual sums of squares are positive.
Continue in the R session containing the ordinary mixture fit mix_run and its summary mix_fit. From the book directory, load the mixture routines and the original MIX1 responses.
1
2
source("code/lib/mixture_em.R", local = TRUE)
mix_y <- readRDS("data/simulated/ch04/MIX1.rds")
The function gaussian_em_or_ecm() implements the two conditional maximizations, starting from supplied parameters or a random start. Its lambda, mu and sigma contain the same mixing proportions $\pi_k$, component means $\mu_k$ and standard deviations $\sigma_k$ that mix_unpack() names probability, mean and sd.
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
gaussian_em_or_ecm <- function(x, lambda = NULL, mu = NULL, sigma = NULL, k = 2,
epsilon = 1e-08,
maxit = 1000, max_restarts = 20, ECM = FALSE) {
x <- as.vector(x)
tmp <- gaussian_mixture_random_start(x, lambda, mu, sigma, k)
lambda <- tmp$lambda; mu <- tmp$mu; sigma <- tmp$s; k <- tmp$k
# With two or more free standard deviations, refresh the probabilities between steps.
ECM <- ECM || any(seq_len(k) != 1)
n <- length(x)
not_done <- TRUE
restarts <- 0
starts <- list()
while (not_done) {
not_done <- FALSE
tmp <- gaussian_mixture_random_start(x, lambda, mu, sigma, k)
lambda <- tmp$lambda; mu <- tmp$mu; k <- tmp$k; sigma <- tmp$s
starts[[length(starts) + 1L]] <- list(lambda = lambda, mu = mu, sigma = sigma)
diff <- epsilon + 1
iter <- 0
mu <- rep(mu, k)[1:k]
sigma <- rep(sigma, k)[1:k]
# Start with the class probabilities at the initial parameters.
z <- normal_posterior(x, mu, sigma, lambda)
post_probs <- z$post; res <- z$resid_sq
ll <- obs_ll <- z$loglik
path <- list(c(lambda = lambda, mu = mu, sigma = sigma))
The initializer returns the standard deviations in tmp$s, which is assigned to sigma. The expression assigning ECM is true whenever k exceeds one, even if the caller passes ECM = FALSE. For the two-component model here, the function therefore always selects the intervening E step. The initial call to normal_posterior() supplies one row per person in each of two matrices, post for the posterior class probabilities and resid_sq for the squared deviations from the class means. The next block performs the two conditional updates.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
while (iter < maxit && diff > epsilon) {
# First conditional step: update the proportions and means.
lambda <- colMeans(post_probs)
mu[] <- vapply(seq_len(k), function(i) {
s_i <- sum(post_probs[, i] * x); s_i / (n * lambda[i]) }, 0)
if (ECM) {
# Refresh the probabilities and squared deviations at the new means.
z <- normal_posterior(x, mu, sigma, lambda)
post_probs <- z$post; res <- z$resid_sq
# Second conditional step: update the proportions and standard deviations.
lambda <- colMeans(post_probs)
}
sigma[] <- vapply(seq_len(k), function(i) {
ss_i <- sum(post_probs[, i] * res[, i]); sqrt(ss_i / (n * lambda[i])) }, 0)
if (any(sigma < 1e-08)) {
not_done <- TRUE
restarts <- restarts + 1
lambda <- mu <- sigma <- NULL
if (restarts > max_restarts) stop("Too many tries!")
break
}
In this loop, i indexes components and post_probs[, i] gives that component’s posterior probabilities. The column average is the updated proportion, so n * lambda[i] is the expected count in the mean update. The call inside if (ECM) then computes both matrices again. The variance update uses each refreshed probability with the squared deviation about the corresponding new mean.
After an update, recompute the posterior probabilities and the observed-data log likelihood to prepare the next cycle and test whether to continue.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Compute probabilities for the next cycle and the signed likelihood increase.
z <- normal_posterior(x, mu, sigma, lambda)
post_probs <- z$post; res <- z$resid_sq
diff <- z$loglik - obs_ll
obs_ll <- z$loglik
ll <- c(ll, obs_ll)
iter <- iter + 1
path[[iter + 1L]] <- c(lambda = lambda, mu = mu, sigma = sigma)
}
}
list(lambda = lambda, mu = mu, sigma = sigma, loglik = obs_ll, posterior = post_probs,
loglik_path = ll, restarts = restarts, iterations = iter, converged = iter < maxit,
start = starts[[length(starts)]], path = do.call(rbind, path))
}
If a standard deviation falls below $10^{-8}$, the routine discards that attempt. The outer loop draws new starting values and permits up to 20 restarts. On a successful update, the posterior calculation also gives the observed-data log likelihood for the stopping test. The loop continues while its signed increase exceeds $10^{-8}$ and the count is below 1,000. A decrease would also end the loop. The returned converged flag tests only the count.
The random-start scheme is defined in code/lib/mixture_em.R. For the 300 responses in mix_y, the initializer gaussian_mixture_random_start() sorts the sample and uses positions 1 through 150 for the first group and 150 through 300 for the second. The 150th ordered response enters both groups’ summaries. Each starting standard deviation is the reciprocal of an exponential draw whose rate is the group’s sample standard deviation. A zero exponential rate is replaced by a uniform draw between zero and the full sample standard deviation before drawing the reciprocal exponential. It then draws each starting mean from a normal distribution centered at the corresponding group mean with the newly drawn standard deviation. Finally, it normalizes two independent uniform draws to sum to one, redrawing the pair until both proportions are at least 0.05.
Seed 100405 fixes the random start reported by the returned fit.
1
2
3
4
RNGkind("Mersenne-Twister", "Inversion", "Rejection")
set.seed(100405)
ecm_fit <- gaussian_em_or_ecm(mix_y)
print(ecm_fit$start)
1
2
3
4
5
6
7
8
$lambda
[1] 0.5702508 0.4297492
$mu
[1] 48.44577 94.15766
$sigma
[1] 58.93857 40.25603
Relative to the gap between the starting means, both standard deviations are large. Responses near the midpoint initially have appreciable probability in both classes. Differencing loglik_path includes the first update from this start.
1
2
3
print(c(updates = ecm_fit$iterations, restarts = ecm_fit$restarts,
loglik = ecm_fit$loglik,
smallest_rise = min(diff(ecm_fit$loglik_path))))
1
2
updates restarts loglik smallest_rise
4.800000e+01 0.000000e+00 -1.152864e+03 8.027200e-09
From this start, ECM made 48 updates without a restart and reached an observed-data log likelihood of $-1152.864$. Even its smallest increase, about $8.0\times10^{-9}$, was positive. That final increase met the stopping tolerance.
A precision ordering fitted by EC-MM
Suppose the model specifies that class 2 has at least as much precision as class 1. The restriction refers to the original component labels before sorting for display. If the labels have no other restrictions or substantive meanings, either ordering can be obtained by relabeling; imposing this order then selects labels without restricting the set of mixture densities. Write the precisions, or inverse variances, as $\tau=Ag$, where $g_1>0$, $g_2\geq0$, and
\[A=\begin{pmatrix}1&0\\1&1\end{pmatrix},\qquad \tau_1=g_1,\qquad \tau_2=g_1+g_2.\]Thus $g_1$ is the inverse variance of class 1 and $g_2$ is the excess inverse variance of class 2 over class 1. Both have inverse squared response units. Increasing $g_1$ with $g_2$ fixed narrows both component distributions; increasing $g_2$ alone narrows only class 2. For positive precisions, the second standard deviation can be no larger than the first.
The combination used here is expectation-conditional maximization with a conditional minorize-maximize update (EC-MM) for a constrained normal mixture. It first updates the proportions and means as in ECM. Using the refreshed probabilities, it updates the proportions again and constructs a lower bound for the precision update. For this step, let $w_{ik}$ denote the refreshed probability, $N_k=\sum_i w_{ik}$ the refreshed count and $S_k=\sum_i w_{ik}(y_i-\mu_k^\ast )^2$ the residual sum at the updated mean. The normal log density contributes half the log precision and subtracts half the precision times the squared deviation. Thus the terms of $Q$ that depend on $g$ are
\[Q_\tau(g)=\tfrac12\sum_k \{N_k\log\tau_k-S_k\tau_k\},\qquad \tau_k=(Ag)_k.\]Increasing $g_1$ changes both log precisions. To obtain an update for each coordinate, take positive current values $g_j^{\rm old}$ and define $b_{kj}=A_{kj}g_j^{\rm old}/\tau_k^{\rm old}$. The entries in each row sum to one. The ratio of candidate to current precision is a weighted average of the coordinate ratios, so concavity of the logarithm gives
\[\log\frac{\tau_k}{\tau_k^{\rm old}} =\log\!\left(\sum_{j:b_{kj}>0} b_{kj}\frac{g_j}{g_j^{\rm old}}\right) \ \geq\ \sum_{j:b_{kj}>0} b_{kj}\log\frac{g_j}{g_j^{\rm old}}.\]At the current coordinates every ratio is one and the two sides agree. Use this bound for the logarithm and retain the exact linear term in the residual sums of squares. In twice the resulting lower bound, the coefficient of $\log g_j$ is $\sum_k N_k b_{kj}$ and the coefficient of $-g_j$ is $\sum_k S_k A_{kj}$. Each coordinate now has its own concave function to maximize. Setting its derivative to zero and substituting the old variance $s_k^2=1/\tau_k^{\rm old}$ gives
\[g_j^{\rm new} =\frac{\sum_k N_k b_{kj}}{\sum_k A_{kj}S_k} =g_j^{\rm old} \frac{\sum_{i,k} w_{ik}A_{kj}s_k^2} {\sum_{i,k} w_{ik}A_{kj}(y_i-\mu_k^*)^2}.\]For the second column of $A$, only class 2 contributes. Its multiplier compares the old variance with $S_2/N_2$, the mean squared deviation under the refreshed probabilities. Both classes contribute to the first column. With positive counts and denominators, these multipliers are positive. Raising the touching lower bound raises or preserves $Q$, which in turn guarantees that the observed-data log likelihood cannot fall. Starting with strictly positive coefficients preserves their positivity under finite positive multipliers; equality of the two precisions, $g_2=0$, can then be approached as a limit rather than reached by a positive finite update.
The function gaussian_precision_ecmm() implements this EC-MM cycle. Its argument precision_constraint supplies $A$, whose rows correspond to class precisions and columns to the coefficients in $g$.
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
gaussian_precision_ecmm <- function(x, lambda = NULL, mu = NULL, sigma = NULL, k = 2,
precision_constraint, precision_coefficients = NULL, epsilon = 1e-08, maxit = 1000,
max_restarts = 20) {
A <- precision_constraint
restarts <- 0L
x <- as.vector(x); n <- length(x)
tmp <- gaussian_mixture_random_start(x, lambda, mu, sigma, k)
lambda <- tmp$lambda; mu <- tmp$mu; sigma <- tmp$s; k <- tmp$k
not_done <- TRUE
while (not_done) {
not_done <- FALSE
tmp <- gaussian_mixture_random_start(x, lambda, mu, sigma, k)
lambda <- tmp$lambda; mu <- tmp$mu; k <- tmp$k; sigma <- tmp$s
q <- dim(A)[2]
g <- if (is.null(precision_coefficients)) rexp(q) else precision_coefficients
# Convert the starting precisions to variances and standard deviations.
v <- 1 / (A %*% g)
sigma <- as.vector(sqrt(v))
diff <- epsilon + 1
iter <- 0
mu <- rep(mu, length.out = k)
sigma <- rep(sigma, length.out = k)
start <- list(lambda = lambda, mu = mu, sigma = sigma, g = g)
# Evaluate the starting class probabilities and observed-data log likelihood.
z <- normal_posterior(x, mu, sigma, lambda)
post_probs <- z$post; res <- z$resid_sq
obs_ll <- z$loglik; ll <- obs_ll
Unless initial precision coordinates are supplied, the function draws each entry of g from a unit-rate exponential distribution. The vector v then contains the component variances $1/(Ag)_k$, and sigma is replaced by their square roots. The means and proportions retain the values supplied by the initializer. The next block refreshes the probabilities and applies the multiplicative precision update.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
while (iter < maxit && diff > epsilon) {
# Update proportions and means, then refresh the class probabilities.
lambda <- colMeans(post_probs)
mu[] <- vapply(seq_len(k), function(i) {
s_i <- sum(post_probs[, i] * x); s_i / (n * lambda[i]) }, 0)
z <- normal_posterior(x, mu, sigma, lambda)
post_probs <- z$post; res <- z$resid_sq
lambda <- colMeans(post_probs)
# Sum the weighted squared deviations for each column of A.
weighted_res <- (post_probs * res) %*% A
den <- colSums(weighted_res)
# Use the old variances for the numerator of the precision update.
v_by_class <- A * matrix(v, nrow = k, ncol = q)
num <- colSums(post_probs %*% v_by_class)
g <- g * (num / den)
v <- 1 / (A %*% g)
sigma <- as.vector(sqrt(v))
In the precision update, column $j$ of v_by_class multiplies the entries of column $j$ of $A$ by the old variances. Multiplying by the refreshed probabilities and summing over people gives num. For den, post_probs * res first weights the squared deviations about the updated means, then weighted_res combines classes according to the same column of $A$. Their ratio num / den, which multiplies g, is the multiplier just derived.
The final part checks for a collapsed standard deviation and records the new log likelihood.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
if (any(sigma < 1e-08)) {
not_done <- TRUE
restarts <- restarts + 1
lambda <- mu <- sigma <- NULL
if (restarts > max_restarts) stop("Too many tries!")
break
}
# Compare the new observed-data log likelihood with the previous one.
z <- normal_posterior(x, mu, sigma, lambda)
post_probs <- z$post; res <- z$resid_sq
diff <- z$loglik - obs_ll
obs_ll <- z$loglik
ll <- c(ll, obs_ll)
iter <- iter + 1
}
}
list(lambda = lambda, mu = mu, sigma = sigma, g = g, loglik = obs_ll,
posterior = post_probs, loglik_path = ll, restarts = restarts, iterations = iter,
converged = iter < maxit, start = start)
}
The function applies the same signed-increase test at the new standard deviations. Its convergence flag tests only the iteration count. The restart counter is cumulative, so max_restarts limits the number of restarts across the entire fit.
R fills the matrix by columns. The first row of ecmm_A selects $g_1$ and the second adds $g_2$. Use seed 100406 for this fit.
1
2
3
4
ecmm_A <- matrix(c(1, 1, 0, 1), 2, 2)
set.seed(100406)
ecmm_fit <- gaussian_precision_ecmm(mix_y, precision_constraint = ecmm_A)
print(ecmm_fit$start)
1
2
3
4
5
6
7
8
9
10
11
$lambda
[1] 0.7080545 0.2919455
$mu
[1] 60.11464 82.24404
$sigma
[1] 0.6999434 0.6541323
$g
[1] 2.0411465 0.2959079
The starting standard deviations are $1/\sqrt{g_1}$ and $1/\sqrt{g_1+g_2}$. The fitted value of $g_2$ shows whether they reached equality.
1
2
print(c(updates = ecmm_fit$iterations, loglik = ecmm_fit$loglik, g = ecmm_fit$g,
smallest_rise = min(diff(ecmm_fit$loglik_path))))
1
2
updates loglik g1 g2 smallest_rise
1.680000e+02 -1.152864e+03 2.491339e-02 4.724404e-03 9.898713e-09
After 168 updates, the smallest log likelihood increase was $9.9\times10^{-9}$ and the observed-data log likelihood was $-1152.864$. At the fitted $g_1=0.02491339$ and $g_2=0.004724404$, the second precision strictly exceeds the first. The likelihood agrees to the printed precision with that of unrestricted ECM.
These estimates have finite means, positive proportions and positive variances; those facts alone do not establish a local maximum. In the unrestricted normal mixture, one component can put its mean at an observed response and shrink its standard deviation toward zero with a fixed positive mixing proportion. Its density there grows without bound. Fixing the other component at positive variance gives every remaining response a positive density throughout. Hence the unrestricted likelihood has no finite global maximum. The precision ordering also permits this construction by shrinking the variance of class 2, so that ordering alone does not make the likelihood bounded.
For comparison, ordered() sorts the two means and preserves the association of each class’s proportion and standard deviation with its mean. All three rows evaluate the same observed-data log likelihood for the 300 responses. EC-MM restricts the precisions in the original class order before this display sorts the means.
1
2
3
4
5
6
7
8
9
10
11
12
ordered <- function(p, m, s) {
o <- order(m)
values <- c(p[o], m[o], s[o])
setNames(values, paste0(rep(c("mixing_proportion_", "mean_", "sd_"), each = 2), 1:2))
}
print(rbind(
EM = c(updates = mix_fit$iterations, loglik = -mix_fit$value,
ordered(mix_run$mixing_proportion, mix_run$mean, sqrt(mix_run$variance))),
ECM = c(updates = ecm_fit$iterations, loglik = ecm_fit$loglik,
ordered(ecm_fit$lambda, ecm_fit$mu, ecm_fit$sigma)),
EC_MM = c(updates = ecmm_fit$iterations, loglik = ecmm_fit$loglik,
ordered(ecmm_fit$lambda, ecmm_fit$mu, ecmm_fit$sigma))), digits = 8)
1
2
3
4
updates loglik mixing_proportion_1 mixing_proportion_2 mean_1 mean_2 sd_1 sd_2
EM 14 -1152.8739 0.42182570 0.57817430 55.400160 80.815261 6.3974387 5.7663413
ECM 48 -1152.8641 0.41957364 0.58042636 55.329151 80.767993 6.3358656 5.8084494
EC_MM 168 -1152.8641 0.41956541 0.58043459 55.328882 80.767812 6.3355387 5.8086744
At four decimal places, ECM and EC-MM both reached $-1152.8641$. For the lower-mean class, the two mixing proportions differ by less than 0.000009. Across the two classes, the corresponding means differ by less than 0.00027 and the standard deviations by less than 0.00033. Subtracting the displayed ordinary EM log likelihood of $-1152.8739$ gives a difference of 0.0098.
Ordinary EM started from the median classification, updated all parameters from the same probabilities, and stopped after 14 updates when the relative change in the log likelihood fell below $10^{-5}$. Its largest absolute score component on the working scales was still 0.64. ECM and EC-MM used different random starts and tested the signed increase on the log likelihood scale. ECM maximized over free variances, whereas EC-MM maximized a lower bound for the constrained precisions. These differences prevent the counts of 14, 48 and 168 from isolating the effect of the update rule.
The supplied ECM and EC-MM fits are adapted from normalmixEM() and normalmixMMlc() of mixtools (code/NOTICE.md), which provides both methods for normal mixtures.
4.6 SQUAREM, quasi-Newton acceleration, and parabolic EM
How many ordinary EM updates does the two-class mixture need before its parameters scarcely move? The mixture session uses the 300 responses in data/simulated/ch04/MIX1.rds. The median classification supplies mix_start. Its first coordinate is the log odds of class 1 versus class 2, followed by the class means and their log standard deviations. Write $M$ for mix_map(), which computes each person’s posterior class probabilities and updates all five coordinates. A separate call to mix_fn() gives the negative observed-data log likelihood at vectors for which the transformed mixture parameters and its log likelihood can be evaluated. From the book directory, load new_result() for storing the accelerated fit.
1
source("code/lib/result.R")
The function fixed_point_iterate() supplies a plain EM comparison using the Euclidean norm of the change in working coordinates as its stopping distance.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
fixed_point_iterate <- function(par, map, obj_fn = NULL, tol = 1e-07, max_iter = 5000) {
iter <- 1
conv <- FALSE
path <- list(par)
while (iter < max_iter) {
mapped <- map(par)
# Save the trial point before testing its distance from the current point.
path[[length(path) + 1L]] <- mapped
res <- sqrt(crossprod(mapped - par))
if (res < tol) {
conv <- TRUE
break
}
par <- mapped
iter <- iter + 1
}
# Evaluate the negative observed-data log likelihood at the returned point.
list(par = par, objective = if (!is.null(obj_fn)) obj_fn(par) else NA, map_count = iter,
obj_count = 0, convergence = conv, path = path)
}
fp_fit <- fixed_point_iterate(mix_start, mix_map, mix_fn)
print(c(map_evaluations = fp_fit$map_count, loglik = -fp_fit$objective,
converged = fp_fit$convergence))
1
2
map_evaluations loglik converged
56.000 -1152.864 1.000
The 56th map evaluation moved the parameters by less than $10^{-7}$. The function saved that trial point in path before testing the distance. Because break precedes par <- mapped, it returned the preceding point, with observed-data log likelihood $-1152.864$. The iterations used only the map; mix_fn() was evaluated once, at the returned point. The path contains 57 points including the start.
Here the reported count equals the number of calls. If the iteration exhausts its limit, starting iter at one and testing iter < max_iter permits only 4,999 calls for a reported 5,000.
To put 56 in perspective, a scalar error that starts at one and contracts by 0.745 each time takes about $\log(10^{-7})/\log(0.745)\approx55$ updates to reach $10^{-7}$. That calculation uses distance to the limit. The implemented test requires only two successive parameter vectors.
Can two ordinary updates suggest a point farther along the slow direction? From working vector $\theta$, let $r=M(\theta)-\theta$ be the first displacement. The change from the first displacement to the second is $v=M(M(\theta))-2M(\theta)+\theta$. SQUAREM denotes squared extrapolation methods for accelerating EM-like iterations. For $v^\top v>0$, the variant used here chooses a step length from their relative magnitudes, subject to the current upper limit $\alpha_{\max}$. Its squared extrapolation is
\[\alpha=\max\!\left(1,\min\!\left(\alpha_{\max}, \sqrt{\frac{r^\top r}{v^\top v}}\right)\right),\qquad \theta^*=\theta+2\alpha r+\alpha^2v.\]Substituting one for $\alpha$ gives $M(M(\theta))$. To see what a larger step can do, suppose the map multiplies a scalar error by $\rho$ with $0<\rho<1$. For starting error $e$, the two differences are $r=(\rho-1)e$ and $v=(\rho-1)^2e$. The extrapolated error is $[1-\alpha(1-\rho)]^2e$, which vanishes at the unrestricted length $1/(1-\rho)$. A mixture need not follow that scalar relation. The function squarem_proposal() constructs the extrapolated candidate and, for a sufficiently long step, applies one more EM update to stabilize it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
squarem_proposal <- function(map, fn, par, first, second, base_value, step_max = 1,
alpha = NULL, obj_increase = 1, initial_step_max = 1) {
q1 <- first - par
q2 <- second - first
# Compare the lengths of the first displacement and the second difference.
if (is.null(alpha)) {
alpha <- max(1, min(step_max, sqrt(crossprod(q1) / crossprod(q2 - q1))))
}
extrapolated <- par + 2 * alpha * q1 + alpha^2 * (q2 - q1)
# Apply one further EM update when abs(alpha - 1) > 0.01.
stabilized <- abs(alpha - 1) > 0.01
candidate <- if (stabilized) {
tryCatch(map(extrapolated), error = identity)
} else extrapolated
failed <- inherits(candidate, "error") || any(is.nan(candidate))
message <- if (inherits(candidate, "error")) conditionMessage(candidate) else
if (failed) "NaN from the map" else "evaluated"
In squarem_proposal(), q1 is $r$ and q2 - q1 is $v$. The function calls one additional EM update a stabilization step and applies it when abs(alpha - 1) > 0.01. A cycle that reaches a proposal at 1.005 thus uses two map calls, while one at 1.02 uses three.
For this fit, base_value is the negative observed-data log likelihood at the start of the cycle. The candidate after any stabilization is accepted if it can be evaluated and its negative log likelihood is at most base_value + 1. An increase of one in the negative log likelihood is a decrease of one in the observed-data log likelihood, so this acceptance rule permits nonmonotone likelihood paths. An accepted step at the upper limit multiplies that limit by four.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# With a finite allowance, evaluate the negative observed-data log likelihood.
value <- if (failed) NA_real_ else if (is.infinite(obj_increase)) base_value else
tryCatch(fn(candidate), error = function(e) NaN)
accepted <- !failed && !is.nan(value) && !(value > base_value + obj_increase)
attempt <- data.frame(alpha = alpha, step_max = step_max,
value = if (is.infinite(obj_increase)) NA_real_ else value,
accepted = accepted, message = message)
binding <- alpha == step_max
if (accepted) {
# A step at its limit lengthens the limit fourfold.
return(list(par = candidate, value = value, attempt = attempt,
reason = "extrapolation", alpha = alpha,
step_max = if (binding) 4 * step_max else step_max))
}
# On rejection, reduce a binding upper limit to at least its initial setting.
# The fallback has length one. If that equals the limit, the next limit is four.
if (binding) step_max <- max(initial_step_max, step_max / 4)
if (step_max == 1) step_max <- 4
list(par = second, value = tryCatch(fn(second), error = function(e) NaN),
attempt = attempt, reason = "two_ordinary_em_updates", alpha = 1, step_max = step_max)
}
On rejection, second already contains the point two ordinary updates ahead. The function evaluates its negative log likelihood and treats the step length as one. If the rejected length was at the limit, the limit is divided by four, down to its initial setting. With an initial limit of one, a reduced limit of one makes the fallback step itself reach the limit, so the next limit is four.
The SQUAREM cycle and its fallback
The function squarem() repeats these proposals, starting with a step limit of one. The arguments map and fn will receive mix_map() and mix_fn() for the mixture 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
squarem <- function(map, fn, init, gr = NULL, control = list()) {
# Count EM calls and negative observed-data log likelihood evaluations separately.
stopifnot(all(names(control) %in% c("maxit", "tol", "obj_increase", "step_max")))
settings <- modifyList(list(maxit = 1500L, tol = 1e-7, obj_increase = 1, step_max = 1),
control)
objective_calls <- 0L
objective <- function(u) {
objective_calls <<- objective_calls + 1L
fn(u)
}
maps <- 0L
evaluate_map <- function(u) {
maps <<- maps + 1L
map(u)
}
par <- init
step_max <- settings$step_max
value <- objective(par)
history <- list(list(par = par, value = value, map_calls = maps, action = "initial"))
proposals <- list()
converged <- FALSE
reason <- "iteration_limit"
valid_map <- function(x) !inherits(x, "error") && is.numeric(x) && is.null(dim(x)) &&
length(x) == length(par) && !any(is.nan(x))
At initialization, objective(par) counts one evaluation of the negative observed-data log likelihood. The map counter is still zero. The initial history entry records the starting vector, its negative log likelihood and that map count.
At each cycle, test the first and then the second ordinary update for a small change before proposing an extrapolation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# Record the point meeting the tolerance and its negative observed-data log likelihood.
stop_at <- function(x) {
par <<- unname(x)
value <<- objective(par)
history[[length(history) + 1L]] <<- list(par = par, value = value, map_calls = maps,
action = "small_map_change")
converged <<- TRUE
reason <<- "small_map_change"
}
# Test the call limit at entry, then test each of the two ordinary EM updates.
while (maps < settings$maxit) {
first <- tryCatch(evaluate_map(par), error = identity)
if (!valid_map(first)) { reason <- "invalid_ordinary_map"; break }
if (sqrt(drop(crossprod(first - par))) < settings$tol) { stop_at(first); break }
second <- tryCatch(evaluate_map(first), error = identity)
if (!valid_map(second)) { reason <- "invalid_ordinary_map"; break }
if (sqrt(drop(crossprod(second - first))) < settings$tol) { stop_at(second); break }
The cycle first compares the distance from par to first with $10^{-7}$. If that change is small, stop_at() records the new point and evaluates its negative log likelihood there. Otherwise, the same test compares second with first. If both changes exceed or equal the tolerance, the proposal determines the next point and step limit.
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
proposal <- squarem_proposal(evaluate_map, objective, par, first, second, value,
step_max, obj_increase = settings$obj_increase, initial_step_max = settings$step_max)
# Continue from the selected point with the revised limit.
step_max <- proposal$step_max
proposals[[length(proposals) + 1L]] <- proposal
par <- unname(proposal$par)
if (!is.nan(proposal$value)) value <- proposal$value
history[[length(history) + 1L]] <- list(par = par,
value = if (is.infinite(settings$obj_increase) &&
proposal$reason == "extrapolation") NA_real_ else value,
map_calls = maps, action = proposal$reason, alpha = proposal$alpha,
step_max = step_max)
}
# At the call limit, report exhaustion even if a small change supplied the point.
if (converged && maps >= settings$maxit) {
converged <- FALSE
reason <- "iteration_limit"
}
if (is.infinite(settings$obj_increase) &&
tail(history, 1L)[[1L]]$action != "small_map_change") {
value <- objective(par)
history[[length(history)]]$value <- value
}
gradient <- if (is.null(gr)) rep(NA_real_, length(par)) else gr(par)
new_result(par, value, gradient, converged, reason, length(history) - 1L,
c(objective = objective_calls, gradient = as.integer(!is.null(gr)), hessian = 0L),
history, map_evaluations = maps, attempts = proposals)
}
The map budget is checked at cycle entry, so a cycle already under way can pass 1,500 calls. Even a small change on exactly the last allowed call satisfies converged && maps >= settings$maxit. The returned coordinates and their likelihood still belong to the point that met the distance tolerance, but the final flag becomes false and the reason becomes iteration_limit.
First check the fallback for an excessively long step. After defining the parabolic and quasi-Newton alternatives, the comparison will fit all three accelerations from the same mixture start. For one trial from mix_start, the length and its limit are both set to 100. The calculation reconstructs the extrapolation before stabilization so that the last two coordinates can be read as log standard deviations.
1
2
3
4
5
6
7
8
9
10
11
12
13
first <- mix_map(mix_start)
second <- mix_map(first)
long_extrapolation <- squarem_proposal(mix_map, mix_fn, mix_start,
first, second, mix_fn(mix_start), step_max = 100, alpha = 100)
print(long_extrapolation$attempt, digits = 6)
print(c(ordinary_updates_loglik = -long_extrapolation$value,
original_loglik = -mix_fn(mix_start),
next_step_max = long_extrapolation$step_max))
r <- first - mix_start
v <- second - 2 * first + mix_start
candidate <- mix_start + 200 * r + 1e4 * v
print(c(alpha = 100, min_log_sd = min(candidate[4:5]), max_sd = max(exp(candidate[4:5])),
min_sd = min(exp(candidate[4:5]))))
1
2
3
4
5
6
alpha step_max value accepted message
1 100 100 NA FALSE missing value where TRUE/FALSE needed
ordinary_updates_loglik original_loglik next_step_max
-1156.518 -1161.570 25.000
alpha min_log_sd max_sd min_sd
1.000000e+02 -4.742734e+02 3.932649e-149 1.060924e-206
The smaller log standard deviation was $-474.27$. Its exponential, about $1.06\times10^{-206}$, is representable, but its square rounds to zero when mix_map() forms the variances for the E step. The stabilizing update raised the error missing value where TRUE/FALSE needed. The NA in value records the absence of a value of the negative observed-data log likelihood function for that candidate. The reported $-1156.518$ instead comes from fn(second) with its sign reversed. Those two ordinary updates improved the observed-data log likelihood from $-1161.570$. Since the failed length equaled its limit, the next limit was $100/4=25$. The SQUAREM fit below starts separately with its usual limit of one.
Parabolic and quasi-Newton updates
Parabolic EM and quasi-Newton acceleration use the same mixture map, but each has a different way to decide whether a proposed point improves on ordinary EM. In pem_qn_accelerate(), the parabolic method first takes ten ordinary updates. It stores points eight, nine and ten as $p_0,p_1,p_2$. The coefficients in the quadratic below sum to one. The curve equals $p_0$ at zero and $p_2$ at one, with $p_1$ determining its direction between them. It generally does not pass through $p_1$. Extrapolating beyond one gives candidates whose likelihood can be evaluated without another EM update.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
pem_qn_accelerate <- function(par, map, obj_fn, method = c("pem", "qn"), tol = 1e-07,
max_iter = 1500) {
method <- match.arg(method)
supplied_map <- map
actual_map_calls <- 0L
map <- function(x) {
actual_map_calls <<- actual_map_calls + 1L
supplied_map(x)
}
n_map <- 0
n_obj <- 0
if (method == "pem") {
l <- 10; h <- 0.1; a <- 1.5
# Use the final three of ten EM iterates to initialize the quadratic curve.
for (i in 1:l) {
par <- map(par)
n_map <- n_map + 1
if (i == l - 2) p0 <- par else if (i == l - 1) p1 <- par
}
input <- list(p0 = p0, p1 = p1, par = par, obj_val = obj_fn(par))
n_obj <- n_obj + 1
At $t=1$ the curve gives $p_2$. The first trial beyond it uses $t=1.1$. Its log likelihood must exceed that at $p_2$ to justify a second trial. Each subsequent trial must improve on the preceding one. The last improving point, p_old, receives two EM updates. If the first trial fails to improve, the two updates start at $p_2$. The function evaluates the likelihood after those updates to establish the starting comparison for the next curve.
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
body <- function(input) {
L2 <- -input$obj_val
p0 <- input$p0; p1 <- input$p1; p2 <- input$par
i <- 0
t <- 1 + a^i * h
w <- c((1 - t)^2, 2 * t * (1 - t), t^2); p_extrap <- w[1] * p0 + w[2] * p1 + w[3] * p2
# Negate the negative observed-data log likelihood to compare log likelihoods.
ll_new <- try(-obj_fn(p_extrap), silent = TRUE)
n_obj <<- n_obj + 1
if (inherits(ll_new, "try-error") || is.nan(ll_new) || ll_new <= L2) {
p0 <- p2
p1 <- map(p0)
p2 <- map(p1)
n_map <<- n_map + 2
} else {
# Increase t while each trial improves on the preceding log likelihood.
while (ll_new > L2) {
p_old <- p_extrap
L2 <- ll_new
i <- i + 1
t <- 1 + a^i * h
w <- c((1 - t)^2, 2 * t * (1 - t), t^2); p_extrap <- w[1] * p0 + w[2] * p1 + w[3] * p2
ll_new <- try(-obj_fn(p_extrap), silent = TRUE)
n_obj <<- n_obj + 1
if (inherits(ll_new, "try-error") || is.nan(ll_new) || any(is.nan(unlist(p_extrap)))) {
p_extrap <- p_old
ll_new <- L2
}
}
p0 <- p1
p1 <- p2
p2 <- map(map(p_old))
n_map <<- n_map + 2
}
L2 <- -obj_fn(p2)
n_obj <<- n_obj + 1
list(p0 = p0, p1 = p1, par = p2, obj_val = -L2)
}
Quasi-Newton acceleration uses two columns of differences between EM updates to approximate a solution of $M(p)-p=0$. The matrix approximation concerns this fixed-point equation. It is different from the BFGS approximation to the inverse Hessian of the negative log likelihood used in the next section. At a current vector $p$, write $p_{\rm new}=M(p)$. Each column of $U$ records a displacement like $p_{\rm new}-p$, and its partner in $V$ records the displacement one update farther on. Four map calls initialize the two pairs.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
} else {
qn <- 2
U <- NULL
for (i in 1:qn) {
# Columns of U are displacements from ordinary EM updates.
p_extrap <- map(par)
n_map <- n_map + 1
U <- cbind(U, p_extrap - par)
par <- p_extrap
}
# Two more map steps give the last difference columns of U and V.
p_extrap <- map(par); p_extrap2 <- map(p_extrap)
n_map <- n_map + 2
U <- cbind(U[, -1, drop = FALSE], p_extrap - par)
V <- cbind(U[, -1, drop = FALSE], p_extrap2 - p_extrap)
input <- list(par = par, p_extrap = p_extrap, p_extrap2 = p_extrap2, V = V, U = U)
Why subtract these matrices? The residual of the fixed-point equation is $d(p)=M(p)-p$. For a column $u$ of $U$ and its partner in $V$, their difference in the order $V-U$ is the change in this residual over the step $u$. Thus, for a step $Uc$ with two coefficients $c$, the linear approximation to the new residual is $d(p)+(V-U)c$. Requiring it to be orthogonal to both columns of $U$ gives $U^\top(U-V)c=U^\top d(p)$. Over the same step the predicted change in $M$ is $Vc$, so the candidate is
\[p_{\rm new}-V\{U^\top(U-V)\}^{-1}U^\top(p-p_{\rm new}).\]The alternative p_extrap2 is $M(p_{\rm new})$. If solving this linear system raises an error, the algorithm uses this two-step point. When the candidate differs from p_extrap2, the code evaluates the negative log likelihood function at both points and takes p_extrap2 if its value is smaller. Two calls from the selected point supply the new columns for $U$ and $V$.
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
body <- function(input) {
par <- input$par; p_extrap <- input$p_extrap; p_extrap2 <- input$p_extrap2
U <- input$U; V <- input$V
# Calculate the correction in the two directions represented in U and V.
tmp <- try(solve(crossprod(U, U - V)), silent = TRUE)
if (inherits(tmp, "try-error")) p_try <- p_extrap2 else {
correction <- (V %*% tmp) %*% crossprod(U, par - p_extrap)
p_try <- as.vector(p_extrap - correction)
}
ll_try <- obj_fn(p_try)
n_obj <<- n_obj + 1
# Compare the candidate with the point two ordinary updates ahead.
if (any(p_try != p_extrap2)) {
l2 <- obj_fn(p_extrap2)
n_obj <<- n_obj + 1
if (l2 < ll_try) {
p_try <- p_extrap2
ll_try <- l2
}
}
par <- p_try
p_extrap <- map(par)
n_map <<- n_map + 1
U <- cbind(U[, -1, drop = FALSE], p_extrap - par)
# This second map call enters actual_map_calls but is absent from fpeval.
p_extrap2 <- map(p_extrap)
V <- cbind(V[, -1], p_extrap2 - p_extrap)
list(par = par, p_extrap = p_extrap, p_extrap2 = p_extrap2, V = V, U = U, obj_val = ll_try)
}
}
Both methods stop when the Euclidean distance between successive outer iterates falls below $10^{-7}$ or the count reaches 1,500 updates. The ten parabolic initialization calls and the four quasi-Newton initialization calls precede this count.
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
par <- input$par
iter <- 0
convergence <- FALSE
trace <- numeric(0)
repeat {
iter <- iter + 1
output <- body(input)
mapped <- output$par
obj_val_new <- output$obj_val
trace <- c(trace, obj_val_new)
# Test the movement of the selected point in working coordinates.
if (sqrt(crossprod(mapped - par)) < tol) {
convergence <- TRUE
break
}
par <- mapped
input <- output
if (iter == max_iter) break
}
if (is.null(obj_val_new)) {
obj_val_new <- obj_fn(mapped)
n_obj <- n_obj + 1
}
list(par = mapped, objective = obj_val_new, n_iter = iter, n_map = n_map,
map_evaluations = actual_map_calls,
n_obj = n_obj, convergence = convergence, trace = trace)
}
All four fits use the same mix_start. In the comparison, map_evaluations counts actual applications of $M$ and likelihood_evaluations counts separate evaluations of the negative observed-data log likelihood, including the final evaluation in the plain fit.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
squarem_fit <- squarem(mix_map, mix_fn, mix_start)
pem_fit <- pem_qn_accelerate(mix_start, mix_map, mix_fn, "pem")
qn_fit <- pem_qn_accelerate(mix_start, mix_map, mix_fn, "qn")
comparison_fits <- rbind(
EM = c(updates = fp_fit$map_count, map_evaluations = fp_fit$map_count,
likelihood_evaluations = 1,
loglik = -fp_fit$objective),
SQUAREM = c(updates = squarem_fit$iterations,
map_evaluations = squarem_fit$map_evaluations,
likelihood_evaluations = unname(squarem_fit$evaluations[1]),
loglik = -squarem_fit$value),
parabolic = c(updates = pem_fit$n_iter, map_evaluations = pem_fit$map_evaluations,
likelihood_evaluations = pem_fit$n_obj, loglik = -pem_fit$objective),
quasi_Newton = c(updates = qn_fit$n_iter, map_evaluations = qn_fit$map_evaluations,
likelihood_evaluations = qn_fit$n_obj, loglik = -qn_fit$objective))
print(comparison_fits, digits = 10)
1
2
3
4
5
updates map_evaluations likelihood_evaluations loglik
EM 56 56 1 -1152.864145
SQUAREM 8 21 9 -1152.864145
parabolic 11 32 51 -1152.864145
quasi_Newton 10 24 20 -1152.864145
The common log likelihood was $-1152.864145$ to six decimal places. Plain EM used 56 map calls and one likelihood evaluation.
SQUAREM took eight cycles. The first used two ordinary updates at $\alpha=1$, the next six each used a third call for stabilization, and the last stopped at its first update. That accounts for all 21 map calls. The nine likelihood evaluations covered the start, seven accepted proposals and the final small change.
Parabolic EM used $10+2(11)=32$ map calls and 51 likelihood evaluations, including the trials along the curve.
Quasi-Newton acceleration took ten updates and 20 likelihood evaluations. Its n_map counts four calls during initialization and only the first call from each selected point, giving 14. The call p_extrap2 <- map(p_extrap) also runs on every update, which gives map_evaluations its total of $4+2(10)=24$. Equal printed likelihoods still allow differences in the estimates.
1
2
print(rbind(EM = fp_fit$par, SQUAREM = squarem_fit$par, parabolic = pem_fit$par,
quasi_Newton = qn_fit$par), digits = 8)
1
2
3
4
5
[,1] [,2] [,3] [,4] [,5]
EM -0.32453091 55.329088 80.767951 1.8462191 1.7593193
SQUAREM -0.32453095 55.329088 80.767951 1.8462191 1.7593193
parabolic -0.32453095 55.329088 80.767951 1.8462191 1.7593193
quasi_Newton -0.32453095 55.329088 80.767951 1.8462191 1.7593193
The columns give the log odds, both means and both log standard deviations in their original working order. The range of the four unrounded estimates in each column measures their agreement. The widest range occurs for the mean of class 1 and is less than $3.2\times10^{-7}$. Here all three accelerations reached the same local fit to that precision with fewer EM calls. The parabolic method used the most separate likelihood evaluations. The supplied pem_qn_accelerate() is adapted from the parabolic EM and quasi-Newton routines of turboEM, and squarem() follows the documented settings of SQUAREM (code/NOTICE.md); both packages provide these acceleration methods.
4.7 Observed information of mixture estimates from a quasi-Newton refit
The accelerated fits agreed on a mean near 55.33 for the lower component. How precisely do the 300 observed responses determine that mean when the other mean, both standard deviations and the mixing proportion must also be estimated? The calculation first refits the ordinary EM estimate more precisely, then estimates the observed information at that returned point.
Let $\ell(\theta)$ be the observed-data log likelihood summed over the independent people in the sample. The observed information is $J(\theta)=-\nabla^2\ell(\theta)$. At a local maximum $\hat\theta$ with strictly positive mixing proportions and standard deviations, suppose the score is zero and $\ell$ is twice continuously differentiable with positive definite $J(\hat\theta)$. Then a small displacement $d$ reduces the log likelihood by approximately $d^\top J(\hat\theta)d/2$. A small eigenvalue therefore describes a direction in which the estimates can move appreciably with little change in fit.
The covariance approximation requires an additional large-sample argument. Suppose independent responses come from the specified two-component model, with distinct component distributions, positive proportions and variances, and labels fixed consistently. For a sequence of local maxima converging to the true parameter, with finite nonsingular per-person information and integrable bounds permitting the likelihood derivatives and their averages to converge, $J(\hat\theta)^{-1}$ approximates the sampling covariance of the jointly estimated parameters. This argument concerns a consistent local solution; the unrestricted mixture likelihood has no finite global maximizer.
Ordinary EM stopped after 14 updates when the relative change in its log likelihood fell below $10^{-5}$. At that stopping point, its log likelihood was about 0.0097 below that of the refit. Starting from that EM estimate, the refit locates the local maximum more precisely before estimating the observed information.
The vector from mix_pack() starts with $\log(\pi_1/\pi_2)$. Positions two and three contain the component means, and positions four and five contain their log standard deviations. The refit pairs each mean $\mu_k$ with its own log standard deviation $\eta_k=\log\sigma_k$ and puts the reversed log odds $a=\log(\pi_2/\pi_1)$ last. Thus $\theta=(\mu_1,\eta_1,\mu_2,\eta_2,a)^\top$ represents the same mixture, with $\pi_2=e^a/(1+e^a)$.
To obtain the score vector on this scale, write $f_{ik}$ for the normal density of response $y_i$ in component $k$, and $m_i=\pi_1 f_{i1}+\pi_2 f_{i2}$ for its observed-data density. For any coordinate, the chain rule gives $\partial\log m_i=(1/m_i)\sum_k\partial(\pi_k f_{ik})$. Writing each derivative as the joint density times its log derivative gives the weight $w_{ik}=\pi_k f_{ik}/m_i$, the posterior class probability at the parameter vector being evaluated.
For a mean, differentiating the normal log density gives the residual divided by the variance. For a log standard deviation, differentiating $-\eta_k-(y_i-\mu_k)^2e^{-2\eta_k}/2$ gives the squared standardized residual minus one. Finally, the derivatives of $\log\pi_1$ and $\log\pi_2$ with respect to $a$ are $-\pi_2$ and $1-\pi_2$. Their weighted sum is $w_{i2}-\pi_2$. A response equally likely under both component densities has $w_{i2}=\pi_2$ and contributes zero to this last component of the score vector. Summing over people gives
\[\begin{aligned} \frac{\partial\ell}{\partial\mu_k} &=\sum_i w_{ik}\frac{y_i-\mu_k}{\sigma_k^2},& \frac{\partial\ell}{\partial\eta_k} &=\sum_i w_{ik}\left\{\frac{(y_i-\mu_k)^2}{\sigma_k^2}-1\right\} \quad(k=1,2),\\ \frac{\partial\ell}{\partial a}&=\sum_i(w_{i2}-\pi_2). \end{aligned}\]Continue in the mixture session where mix_y contains the responses from data/simulated/ch04/MIX1.rds and mix_run contains the ordinary EM fit. From the book directory, load the result constructor, the BFGS optimizer and the numerical derivative routines.
1
2
3
source("code/lib/result.R")
source("code/lib/quasi_newton.R")
source("code/lib/differentiation.R")
The functions below form the two log joint densities for each response and combine them to evaluate the observed-data log likelihood.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
row_log_sum_exp <- function(m) {
pick <- max.col(m, "first"); M <- m[cbind(seq_along(pick), pick)]
M + log(rowSums(exp(m - M)))
}
refit_terms <- function(par, y) {
prior <- exp(c(0, par[5]))
prior <- prior / sum(prior)
priors <- matrix(prior, length(y), 2, byrow = TRUE)
priors <- priors / rowSums(priors)
# Add the log proportion to each component log density.
list(priors = priors, terms = cbind(dnorm(y, par[1], exp(par[2]), log = TRUE),
dnorm(y, par[3], exp(par[4]), log = TRUE)) + log(priors))
}
refit_loglik <- function(par, y = mix_y) sum(row_log_sum_exp(refit_terms(par, y)$terms))
In refit_terms(), prior and every row of priors contain the two population mixing proportions. Each row of terms contains the two log joint densities for one response and its possible class. Subtracting the row maximum before exponentiating lets row_log_sum_exp() compute $\log m_i$ on a common scale for the two terms.
Subtracting the log marginal density from each log joint density gives the log posterior probabilities. The score function uses these probabilities to weight the derivatives derived above. BFGS minimizes the negative log likelihood, so the supplied gradient is the negative of the observed-data score vector.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
refit_score <- function(par, y = mix_y) {
parts <- refit_terms(par, y)
# Exponentiate the log joint density minus the log marginal density.
weights <- exp(parts$terms - row_log_sum_exp(parts$terms))
scores <- lapply(1:2, function(k) {
res <- as.vector(y - par[2 * k - 1])
sigma <- exp(par[2 * k])
cbind(weights[, k] * res * 1 / sigma^2, weights[, k] * (-1 + res^2 / sigma^2))
})
# Sum the four component derivatives and the log odds derivative over people.
colSums(cbind(scores[[1]], scores[[2]], -parts$priors[, 2] + weights[, 2]))
}
refit_start <- c(mix_run$mean[1], log(sqrt(mix_run$variance[1])), mix_run$mean[2],
log(sqrt(mix_run$variance[2])), log(mix_run$mixing_proportion[2]) - log(mix_run$mixing_proportion[1]))
refit_fn <- function(p) -refit_loglik(p)
refit_gr <- function(p) -refit_score(p)
refit <- bfgs(refit_fn, refit_gr, refit_start)
In refit_score(), column k of weights supplies the multiplier for both derivatives of component k. The last column passed to colSums() subtracts the second mixing proportion from the posterior probability of class 2. The functions refit_fn() and refit_gr() negate the log likelihood and score for minimization.
At the returned vector, num_hess() (Section 3.1) perturbs coordinate $j$ by $h=10^{-3}$ in each direction. If $g=-\nabla\ell$ and $e_j$ is the coordinate unit vector, column $j$ is estimated by $[g(\hat\theta+h e_j)-g(\hat\theta-h e_j)]/(2h)$. Each perturbation recomputes the posterior probabilities as well as the residuals. The routine averages this matrix with its transpose to obtain refit_hessian. The five pairs of perturbations require ten gradient evaluations after fitting. During the fit, BFGS used its own inverse-Hessian approximation to choose search directions. For inference, solve(refit_hessian) inverts the estimated observed-information matrix at the returned parameters.
1
2
3
4
5
6
7
# Estimate the observed information from changes in the negative score vector at the refit.
refit_hessian <- num_hess(refit_fn, refit$par, gr = refit_gr)$hessian
refit_covariance <- solve(refit_hessian)
print(c(updates = refit$iterations, nll_evaluations = unname(refit$evaluations[1]),
gradient_evaluations = unname(refit$evaluations[2]),
loglik_gain = refit_loglik(refit$par) - mix_run$loglik,
largest_move = max(abs(refit$par - refit_start))))
1
2
updates nll_evaluations gradient_evaluations loglik_gain largest_move
7.000000000 30.000000000 7.000000000 0.009729353 0.071078696
The printed updates value is an iteration counter that starts at one. In refit$history, the initial record is followed by six BFGS updates and two entries labeled final_step. The optimizer reported 30 evaluations of the negative log likelihood and seven gradient evaluations. One further call to the supplied gradient produced refit$gradient on return. The gain of 0.009729353 is the difference between the two unrounded values of the observed-data log likelihood.
Which estimate moved most, and how large was that change relative to its sampling uncertainty? The square roots of the diagonal entries of refit_covariance give standard errors on the five working scales. For a component mean, this estimates its variability across repeated samples of 300 people, while the component standard deviation describes differences among responses within that class.
1
print(cbind(start = refit_start, refit = refit$par, se = sqrt(diag(refit_covariance))))
1
2
3
4
5
6
start refit se
[1,] 55.4001596 55.3290809 0.71415526
[2,] 1.8558977 1.8462186 0.08816152
[3,] 80.8152608 80.7679559 0.53140980
[4,] 1.7520378 1.7593196 0.07205470
[5,] 0.3152832 0.3245307 0.13013051
The first mean fell from 55.40016 to 55.32908. Its absolute change of 0.07108 was the largest among the five working coordinates and about one tenth of its standard error, 0.714155. The first row takes the square root of the corresponding diagonal entry of refit_covariance, about 0.5100. Inverting the full matrix accounts for estimating the other four coordinates jointly with this mean. The estimated upper component mean, 80.76796, has standard error 0.531410 on the response scale. The fifth estimate, 0.32453, has standard error 0.130131 on the log odds scale.
The eigenvalues and score vector at the same point describe the second derivatives of the negative log likelihood and the remaining first derivatives of the log likelihood in the five working coordinates.
1
print(eigen(refit_hessian, symmetric = TRUE)$values)
1
[1] 274.968966 166.114936 63.871342 4.401819 1.754939
All five eigenvalues were positive, from 1.754939 to 274.968966. Reversing the sign of a gradient leaves its absolute components unchanged, so max(abs(refit$gradient)) gives the largest absolute score component at the refit. Its value was $7.228807\times10^{-5}$. The small score vector and positive eigenvalues of its negative log likelihood Hessian support a strict local maximum of the log likelihood to numerical accuracy.
To assess the numerical approximation at the fitted point with distinct components, vary the difference formula and step size at the five estimates in refit$par.
1
2
3
4
5
hessian_step_check <- t(vapply(c(1e-3, 1e-4, 1e-5), function(step) {
H <- num_hess(refit_fn, refit$par, step = step)$hessian
c(step = step, Hessian_difference = max(abs(H - refit_hessian)))
}, numeric(2)))
print(hessian_step_check)
1
2
3
4
step Hessian_difference
[1,] 1e-03 5.195985e-05
[2,] 1e-04 1.176387e-04
[3,] 1e-05 1.796647e-02
Without a supplied gradient, num_hess() (Section 3.1) differences the negative log likelihood itself. Each row gives the largest absolute entry of the difference from refit_hessian, computed by differencing the gradient. At steps $10^{-3}$, $10^{-4}$ and $10^{-5}$, those differences were $5.2\times10^{-5}$, $1.2\times10^{-4}$ and $1.8\times10^{-2}$. Subtracting nearly equal values of the negative log likelihood function and dividing by a squared step amplifies rounding error as the step shrinks. Changing the step affects the accuracy of the numerical Hessian at the fit with distinct components.
When the component densities overlap
How much information about a proportion remains as the two component densities grow more alike? Each comparison in mass_rate_runs uses 600 deterministic responses, 300 normal quantile points per component. Both standard deviations are fixed at one, the means are fixed at half the separation on either side of zero, and only the first mixing proportion $p$ is free. The symmetry of each constructed dataset gives an estimated proportion of 0.5.
With $m_i=p f_{i1}+(1-p)f_{i2}$, the second derivative of $-\log m_i$ with respect to $p$ is $(f_{i1}-f_{i2})^2/m_i^2$. A response to which the two components assign nearly equal density contributes little information about the mixing proportion.
Here the argument of fn() is the log odds for class 1. At zero, num_hess() estimates the second derivative of the negative log likelihood with respect to those log odds. If $I$ is that scalar observed information, the standard error on the logit scale is $1/\sqrt I$. The derivative of the inverse logit at zero is $p(1-p)=0.25$, so the corresponding delta-method standard error for $p$ is $0.25/\sqrt I$. These are model-based standard-error calculations for the constructed datasets; the fixed quantiles themselves were not randomly sampled.
1
2
3
4
5
6
7
8
mass_information <- t(vapply(mass_rate_runs, function(run) {
fn <- function(a) run$objective(plogis(a))
# Zero log odds of class 1 versus class 2 gives a mixing proportion of one half.
observed <- num_hess(fn, 0)$hessian[1, 1]
c(separation = diff(run$means), logit_information = observed,
mass_se = 0.25 / sqrt(observed))
}, numeric(3)))
print(mass_information, digits = 6)
1
2
3
separation logit_information mass_se
[1,] 4.0 139.6826 0.0211529
[2,] 0.7 16.4735 0.0615952
Reducing the separation from 4 to 0.7 lowered the logit information from 139.6826 to 16.4735 and raised the proportion’s standard error in the mass_se column from 0.0211529 to 0.0615952.
Now take a separate deterministic set of 300 standard-normal quantile points, weak_y. In the full five-coordinate model, merged_par gives each component mixing proportion one half, mean zero and variance equal to the sample mean square. If $f_i$ is their common density at a response, then $\pi_1 f_i+\pi_2 f_i=f_i$ for every mixing proportion.
1
2
3
4
5
6
7
8
9
weak_y <- qnorm((seq_len(300) - 0.5) / 300)
# Give both components the pooled normal mean and variance.
merged_par <- c(0, log(sqrt(mean(weak_y^2))), 0, log(sqrt(mean(weak_y^2))), 0)
merged_hessian <- num_hess(function(p) -refit_loglik(p, weak_y), merged_par,
gr = function(p) -refit_score(p, weak_y))$hessian
merged_eigen <- eigen(merged_hessian, symmetric = TRUE)$values
print(c(merged_max_abs_score_component = max(abs(refit_score(merged_par, weak_y))),
smallest_absolute_eigenvalue = min(abs(merged_eigen)),
largest_eigenvalue = max(merged_eigen)))
1
2
merged_max_abs_score_component smallest_absolute_eigenvalue largest_eigenvalue
3.907985e-14 1.850569e-11 2.999995e+02
At the pooled normal estimates, the partial derivatives of the log likelihood with respect to the means and log standard deviations are zero within rounding. They do so for every choice of the mixing proportion because the posterior probabilities at equality are just the mixing proportions. The log likelihood is constant along the log odds direction, and the cross derivatives with that coordinate also vanish here. The largest absolute score component was only $3.9\times10^{-14}$, yet the smallest absolute eigenvalue of the numerical Hessian was $1.9\times10^{-11}$ against a largest eigenvalue near 300. The proportion is not identified: changing it while maintaining equality of the two component distributions leaves the response distribution unchanged. The singular information matrix has no inverse, so it supplies no standard errors for the joint fit.
The step-size checks at the separated fit concerned numerical approximation. At coincident components, no choice of step can recover information about the mixing proportion.
The R package flexmix provides likelihood refits through refit(..., method = "optim"). Its alternative method = "mstep" fixes the posterior probabilities and does not account fully for joint parameter estimation, so its componentwise uncertainty estimates serve a different purpose.
4.8 Checking likelihood sequences and accelerated solutions
How much evidence is there that different fitting methods have found the same solution for the 300 MIX1 responses? In the mixture session, use the common starting vector mix_start obtained from the median classification. Four methods apply the EM map. The fifth minimizes the negative observed-data log likelihood directly. The assignment direct_mix <- fitted_mixture retrieves the BFGS fit used to examine the lower bound with uniform class probabilities. This fit used numerical gradients from mix_start. The BFGS refit for standard errors started at the ordinary EM estimate and used the analytic gradient.
To check all five endpoints on the same terms, num_grad() differentiates mix_fn() at each returned vector. Changing the sign of the gradient gives the score vector and leaves the largest absolute component unchanged.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
direct_mix <- fitted_mixture
comparison_routes <- list(
EM = list(par = fp_fit$par, maps = fp_fit$map_count,
likelihood_evaluations = 1, converged = fp_fit$convergence),
SQUAREM = list(par = squarem_fit$par, maps = squarem_fit$map_evaluations,
likelihood_evaluations = unname(squarem_fit$evaluations[1]),
converged = squarem_fit$converged),
parabolic = list(par = pem_fit$par, maps = pem_fit$map_evaluations,
likelihood_evaluations = pem_fit$n_obj,
converged = pem_fit$convergence),
quasi_Newton = list(par = qn_fit$par, maps = qn_fit$map_evaluations,
likelihood_evaluations = qn_fit$n_obj,
converged = qn_fit$convergence),
BFGS = list(par = direct_mix$par, maps = 0,
likelihood_evaluations = unname(direct_mix$evaluations[1]),
converged = direct_mix$converged))
comparison_table <- do.call(rbind, lapply(names(comparison_routes), function(method) {
# Evaluate the same objective function and score vector at every returned vector.
fit <- comparison_routes[[method]]
data.frame(method = method, initial_nll = mix_fn(mix_start),
final_nll = mix_fn(fit$par),
max_abs_score_component = max(abs(num_grad(mix_fn, fit$par)$gradient)),
em_update_evaluations = fit$maps,
likelihood_evaluations = fit$likelihood_evaluations, converged = fit$converged,
row.names = NULL)
}))
print(comparison_table, row.names = FALSE, digits = 7)
1
2
3
4
5
6
7
8
9
10
11
12
method initial_nll final_nll max_abs_score_component em_update_evaluations likelihood_evaluations
EM 1161.57 1152.864 2.296168e-06 56 1
SQUAREM 1161.57 1152.864 2.225866e-07 21 9
parabolic 1161.57 1152.864 5.269558e-07 32 51
quasi_Newton 1161.57 1152.864 1.551131e-07 24 20
BFGS 1161.57 1152.864 8.653583e-05 0 30
converged
TRUE
TRUE
TRUE
TRUE
TRUE
All five methods reported convergence, reducing the negative log likelihood from 1161.57 to 1152.864 at the precision shown. The EM methods stopped on a small change in the parameters. At their returned estimates the largest absolute score components were $2.3\times10^{-6}$ for plain EM, $2.2\times10^{-7}$ for SQUAREM, $5.3\times10^{-7}$ for parabolic EM and $1.6\times10^{-7}$ for quasi-Newton acceleration. BFGS stopped on a small relative reduction in the negative log likelihood, with a largest absolute score component of $8.7\times10^{-5}$.
The table separates EM map calls from evaluations of the negative log likelihood. Quasi-Newton acceleration’s 24 map calls include four at initialization and two per outer update. BFGS reported 30 evaluations of the negative log likelihood, excluding two further evaluations per coordinate for each numerical gradient. There were ten counted gradients and one final gradient, each in five dimensions. The fit therefore evaluated the negative log likelihood $30+2(5)(10+1)=140$ times. Computing the comparison and its score diagnostics takes place after fitting.
An endpoint comparison leaves open what happened between the start and the solution. The first column below recomputes the negative log likelihood at each returned EM estimate and takes the absolute difference from the stored value. The second reports the largest signed difference between consecutive values of the negative log likelihood function in each recorded sequence. A positive difference means the observed-data log likelihood fell.
1
2
3
4
5
6
7
8
9
10
11
reevaluation <- rbind(
EM = c(stored_error = abs(fp_fit$objective - mix_fn(fp_fit$par)),
maximum_signed_nll_change = max(diff(vapply(fp_fit$path, mix_fn, numeric(1))))),
SQUAREM = c(stored_error = abs(squarem_fit$value - mix_fn(squarem_fit$par)),
maximum_signed_nll_change = max(diff(
vapply(squarem_fit$history, `[[`, numeric(1), "value")))),
parabolic = c(stored_error = abs(pem_fit$objective - mix_fn(pem_fit$par)),
maximum_signed_nll_change = max(diff(pem_fit$trace))),
quasi_Newton = c(stored_error = abs(qn_fit$objective - mix_fn(qn_fit$par)),
maximum_signed_nll_change = max(diff(qn_fit$trace))))
print(reevaluation)
1
2
3
4
5
stored_error maximum_signed_nll_change
EM 0 9.094947e-13
SQUAREM 0 0.000000e+00
parabolic 0 6.821210e-13
quasi_Newton 0 0.000000e+00
All four endpoint discrepancies were zero. The largest increases in negative log likelihood were $9.1\times10^{-13}$ for ordinary EM and $6.8\times10^{-13}$ for parabolic EM, both at rounding precision. The largest signed changes for SQUAREM and quasi-Newton acceleration were zero.
The ordinary sequence includes the final trial after the returned point. SQUAREM’s history begins at the start, whereas the parabolic and quasi-Newton traces begin after their first outer updates. Their signed differences therefore omit the move from the starting vector. The following calculation reverses the signs to obtain the observed-data log likelihood and prepends the common starting value to those last two traces.
1
2
3
4
5
6
# Reverse the signs to obtain observed-data log likelihood values.
likelihood_paths <- list(
EM = -vapply(fp_fit$path, mix_fn, numeric(1)),
SQUAREM = -vapply(squarem_fit$history, `[[`, numeric(1), "value"),
parabolic = -c(mix_fn(mix_start), pem_fit$trace),
"quasi-Newton" = -c(mix_fn(mix_start), qn_fit$trace))
Figure 4.1. Observed-data log likelihood against recorded iteration for the two-class mixture. The left panel shows each full path. The right panel enlarges the likelihood scale near the solution.
Position zero in Figure 4.1 is the common start. The accelerated curves appear level by about the third recorded position, ordinary EM by about the fifteenth. The first interval includes ten initialization calls for parabolic EM and four for quasi-Newton acceleration. Map evaluations count ordinary EM updates, including initialization. Total computational work also includes the separate likelihood evaluations in the comparison table.
Fits from different starting values
Agreement from a common start leaves another question for the mixture. Which solution is reached if the initial means are close, reversed or identical? Each starting vector below first gives posterior class probabilities. After the inner EM run stops, one final M step uses its last probabilities. Sorting the means then puts the corresponding mixing proportions and standard deviations in the same order across fits. The column mass is the mixing proportion of the lower-mean component when the means are distinct.
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
mix_starts <- list(quantiles = mix_start,
narrow = mix_pack(c(0.3, 0.7), c(58, 77), c(5, 8)),
reversed = mix_pack(c(0.5, 0.5), c(85, 50), c(10, 10)),
coincident = mix_pack(c(0.5, 0.5), rep(mean(mix_y), 2), rep(sd(mix_y), 2)))
start_fits <- lapply(mix_starts, function(start) {
model <- mix_unpack(start)
z <- univariate_gaussian_estep(mix_y, model$probability, model$mean, model$sd^2)$z
run <- univariate_gaussian_em(mix_y, z)
last <- univariate_gaussian_mstep(mix_y, run$z)
list(par = mix_pack(last$mixing_proportion, last$mean, sqrt(last$variance)),
converged = run$reason == "converged",
reason = run$reason, iterations = run$iterations)
})
# Reorder every component quantity by its fitted mean.
align_mixture <- function(u) {
natural <- mix_unpack(u)
order <- order(natural$mean)
mix_pack(natural$probability[order], natural$mean[order], natural$sd[order])
}
start_table <- do.call(rbind, lapply(names(start_fits), function(name) {
fit <- start_fits[[name]]
u <- align_mixture(fit$par)
natural <- mix_unpack(u)
data.frame(start = name, loglik = -mix_fn(u), mass = natural$probability[1],
lower_mean = natural$mean[1], upper_mean = natural$mean[2],
label_error = abs(mix_fn(u) - mix_fn(fit$par)), converged = fit$converged,
reason = fit$reason, updates = fit$iterations, row.names = NULL)
}))
print(start_table, row.names = FALSE)
1
2
3
4
5
start loglik mass lower_mean upper_mean label_error converged reason updates
quantiles -1152.870 0.4212464 55.38180 80.80318 0 TRUE converged 13
narrow -1152.872 0.4176153 55.26819 80.72616 0 TRUE converged 11
reversed -1152.865 0.4190792 55.31405 80.75723 0 TRUE converged 4
coincident -1215.878 0.5000000 70.09452 70.09452 0 TRUE converged 2
When the means are distinct, the mass column gives the fitted mixing proportion of the lower-mean component. The quantiles, narrow and reversed rows reached log likelihoods of $-1152.870$, $-1152.872$ and $-1152.865$ after 13, 11 and 4 inner updates. Their spread of about 0.007 reflects stopping at a relative change in the log likelihood of $10^{-5}$. The final M step is outside these counts. The row labeled quantiles uses the median-based mix_start. It begins with probabilities calculated from those initial parameters, while the 14-update ordinary fit counted an M step from the initial zero-or-one class assignments. All four values of label_error were zero. Reordering the components left each fitted likelihood unchanged.
From coincident components, two inner updates gave equal means of 70.09452. At the pooled mean and maximum likelihood variance, the mixture density equals a single normal density and its log likelihood is $-1215.878$. Uniform class probabilities reproduce those same moments in an M step. This stationary fixed point has a lower likelihood than the three separated fits. Reporting all four starts reveals this dependence on initialization. Determining whether this stationary point is a maximum, minimum or saddle would require its Hessian and, if that matrix is singular, higher-order terms or nearby likelihood comparisons.
Checks against a package and closed-form moments
An implementation check can fix the starting vector, map and likelihood while changing only the routine that performs the extrapolation. The SQUAREM package supplies squarem(). Pass it the same mix_map(), mix_fn() and mix_start and compare its returned coordinates directly with squarem_fit$par.
1
2
3
4
5
6
7
8
.libPaths(c(file.path(getwd(), ".R-library"), .libPaths()))
reference_squarem <- SQUAREM::squarem(par = mix_start, fixptfn = mix_map,
objfn = mix_fn, control = list(intermed = TRUE))
print(rbind(book = c(loglik = -mix_fn(squarem_fit$par),
em_update_evaluations = squarem_fit$map_evaluations, converged = squarem_fit$converged),
reference = c(loglik = -mix_fn(reference_squarem$par),
em_update_evaluations = reference_squarem$fpevals,
converged = isTRUE(reference_squarem$convergence))))
1
2
3
loglik em_update_evaluations converged
book -1152.864 21 1
reference -1152.864 21 1
1
print(max(abs(squarem_fit$par - reference_squarem$par)))
1
[1] 0
The recorded comparison reported a true convergence flag for both implementations and a log likelihood of $-1152.864$ after 21 map calls. The largest absolute coordinate difference was zero for this fit. This comparison uses the same EM map and likelihood in both implementations; it checks their acceleration results on this input.
Return now to the normal-data example with missing measurements. For the 240 people with three normal measurements, the complete records in normal_complete allow the EM update to be compared with the complete-data sample-moment formulas. When all three measurements are present, the E step uses each observed vector and its outer product. One M step should give the sample mean vector and the centered cross-product matrix divided by $n$. With some measurements missing, normal_fn() evaluates the likelihood of each person’s observed subvector. The direct BFGS fit and the EM fit can therefore be compared on the same observations.
1
2
3
4
5
6
7
8
9
10
11
12
13
complete_update <- normal_mstep(normal_estep(normal_start, normal_complete), normal_start)
complete_mean <- colMeans(normal_complete)
complete_covariance <- crossprod(sweep(normal_complete, 2, complete_mean)) /
nrow(normal_complete)
direct_normal <- bfgs(normal_fn, NULL, normal_start)
print(c(complete_mean_error = max(abs(complete_update[1:3] - complete_mean)),
complete_covariance_error = max(abs(logchol_to_cov(complete_update[-(1:3)]) -
complete_covariance)),
missing_parameter_difference = max(abs(normal_fit$par - direct_normal$par)),
missing_loglik_difference = abs(normal_fn(normal_fit$par) -
normal_fn(direct_normal$par)),
direct_max_abs_score_component = max(abs(direct_normal$gradient)),
direct_converged = direct_normal$converged))
1
2
3
4
complete_mean_error complete_covariance_error missing_parameter_difference
0.000000e+00 1.332268e-15 5.160700e-05
missing_loglik_difference direct_max_abs_score_component direct_converged
3.780200e-07 2.186201e-04 1.000000e+00
The complete-data mean agreed exactly, and the largest covariance difference was $1.3\times10^{-15}$. With missing data the two stopped vectors differed by at most $5.2\times10^{-5}$ on the mean and log-Cholesky scales. Their values of the observed-data log likelihood differed by $3.8\times10^{-7}$. Direct BFGS reported convergence with a largest absolute score component of $2.2\times10^{-4}$. The normal EM fit stopped when every standardized working parameter changed by at most $10^{-4}$. The two stopping rules allow slightly different estimates at nearly the same likelihood.
Sampling variability of the lower mean
The mixture fits have so far used the same people. How variable would the refitted lower mean be if the responses were sampled again? Each of 200 samples contains 300 independent people, with class 1 probability 0.4, class means 55 and 80, and standard deviation 6 in both classes. Starting from seed 100408, assign each sample its own stream from L’Ecuyer’s combined multiple recursive random number generator (L'Ecuyer-CMRG).
1
2
3
4
5
6
7
8
RNGkind("L'Ecuyer-CMRG", "Inversion", "Rejection")
set.seed(100408)
replication_streams <- vector("list", 200)
replication_streams[[1]] <- .Random.seed
for (replication in 2:200) {
replication_streams[[replication]] <-
parallel::nextRNGStream(replication_streams[[replication - 1L]])
}
The function mixture_replication() generates one sample, fits it by EM and BFGS, and estimates the lower component mean and its standard error. It also records whether the fit is usable and whether its 95% Wald interval contains the generating lower mean, 55.
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
mixture_replication <- function(replication, streams) {
assign(".Random.seed", streams[[replication]], envir = .GlobalEnv)
class <- ifelse(runif(300) < 0.4, 1L, 2L)
y <- c(55, 80)[class] + 6 * rnorm(300)
run <- univariate_gaussian_em(y, outer(quantile_partition(y, 2), 1:2, "==") * 1)
converged <- run$reason == "converged"
lower <- which.min(run$mean)
upper <- 3L - lower
start <- c(run$mean[lower], log(sqrt(run$variance[lower])), run$mean[upper],
log(sqrt(run$variance[upper])), log(run$mixing_proportion[upper]) - log(run$mixing_proportion[lower]))
fn <- function(p) -refit_loglik(p, y)
gr <- function(p) -refit_score(p, y)
refitted <- if (converged) bfgs(fn, gr, start) else NULL
# Check curvature only after a converged refit.
H <- if (!is.null(refitted) && refitted$converged)
num_hess(fn, refitted$par, gr = gr)$hessian else NULL
refit_converged <- !is.null(refitted) && isTRUE(refitted$converged)
valid <- !is.null(H) && all(is.finite(H)) && min(eigen(H, symmetric = TRUE)$values) > 0
# Select the lower mean after the refit; use the matching row of its covariance.
final_lower <- if (!is.null(refitted)) c(1L, 3L)[which.min(refitted$par[c(1L, 3L)])] else NA_integer_
estimate <- if (!is.null(refitted)) refitted$par[final_lower] else NA_real_
standard_error <- if (valid) sqrt(solve(H)[final_lower, final_lower]) else NA_real_
usable <- converged && refit_converged && valid && is.finite(estimate) &&
is.finite(standard_error) && standard_error > 0
covered <- if (usable) abs(estimate - 55) <= qnorm(0.975) * standard_error else NA
data.frame(replication = replication, estimate = estimate, se = standard_error,
covered = covered, converged = converged, information_valid = valid,
refit_converged = refit_converged, final_mean_coordinate = final_lower,
refit_reason = if (is.null(refitted)) "not_run" else refitted$reason,
refit_loglik = if (is.null(refitted)) NA_real_ else -refitted$value,
usable = usable, reason = run$reason, loglik = run$loglik, updates = run$iterations)
}
Within mixture_replication(), EM starts from the median classification. Its ordered means determine the first and third coordinates for the BFGS refit. After the refit, final_lower selects whichever of these two mean coordinates is smaller. The estimate and the diagonal entry used for its standard error come from that same coordinate. The reported quantity therefore corresponds to the lower component mean even if the fitted means exchange order.
Here usable requires EM and the refit to meet their stopping rules, finite positive definite observed information, a finite estimate and a finite positive standard error. These checks do not include a separate score tolerance. The 95% Wald interval extends the estimated lower mean by the 97.5th standard normal percentile times its standard error in each direction. Its coverage indicator records whether the interval contains the generating lower mean, 55.
1
mixture_replication(1L, replication_streams)
For replication 1, updates was 14. This count, converged and loglik describe the EM run. The lower mean of 54.179544 and its standard error of 0.658109 come from the refit. Their 95% Wald interval is $54.179544\ \pm\ 1.959964(0.658109)$, or $[52.88967,55.46941]$. It contains 55, so this row contributes one to the coverage count.
The same definition gives one row per replication in data/derived/ch04/replications.csv. From the book directory in a fresh R session, the calculation checks that each ID from 1 to 200 occurs once. For the usable fits, bias is estimated by the average fitted lower mean minus 55. The root mean squared error (RMSE) is the square root of the average squared difference from 55, in response units. The empirical standard deviation describes how the estimates vary across samples; mean_se is the arithmetic mean of the standard errors reported by the individual fits.
Averaging the coverage indicators estimates the proportion of intervals containing 55. The denominator is the number of usable samples. If any fits are excluded, this estimates coverage conditional on satisfying those checks, and the excluded counts must be reported separately. The Monte Carlo standard errors for bias and coverage measure uncertainty from using a finite number of simulated samples. They describe the precision of these simulation summaries, whereas the standard error within a fit describes uncertainty in its estimated component mean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
study_results <- read.csv("data/derived/ch04/replications.csv")
stopifnot(identical(as.integer(table(factor(study_results$replication, levels = 1:200))),
rep(1L, 200L)))
# Use the same rows for the sampling and interval summaries.
usable <- study_results$usable
estimates <- study_results$estimate[usable]
coverage <- mean(study_results$covered[usable])
study_summary <- data.frame(target = "lower component mean", truth = 55,
attempted = nrow(study_results), usable = sum(usable),
nonconverged = sum(!study_results$converged),
invalid_information = sum(!study_results$information_valid),
bias = mean(estimates - 55), bias_mcse = sd(estimates) / sqrt(length(estimates)),
rmse = sqrt(mean((estimates - 55)^2)), empirical_sd = sd(estimates),
mean_se = mean(study_results$se[usable]), coverage = coverage,
coverage_mcse = sqrt(coverage * (1 - coverage) / sum(usable)),
fewest_updates = min(study_results$updates), most_updates = max(study_results$updates))
print(study_summary, row.names = FALSE)
1
2
3
4
5
6
target truth attempted usable nonconverged invalid_information
lower component mean 55 200 200 0 0
bias bias_mcse rmse empirical_sd mean_se coverage coverage_mcse
-0.03682603 0.04770195 0.6739257 0.6746074 0.6745055 0.955 0.01465862
fewest_updates most_updates
7 34
All 200 rows were usable, with no EM stopping-rule failures or nonpositive eigenvalues in the refitted information matrices. EM took 7 to 34 updates. The root mean squared error for the lower mean was 0.6739. The empirical standard deviation across the 200 estimates was 0.67461, close to the mean reported standard error, 0.67451. The estimated bias was $-0.0368$ with Monte Carlo standard error $0.67461/\sqrt{200}=0.0477$. Of the 200 intervals, 191 contained 55. The resulting coverage of 0.955 has Monte Carlo standard error $\sqrt{0.955(1-0.955)/200}=0.01466$.
The final check compares these calculations with the supplied summary to a tolerance of $10^{-8}$.
1
2
3
stored <- read.csv("data/derived/ch04/study-summary.csv")
stopifnot(isTRUE(all.equal(study_summary, stored, tolerance = 1e-8,
check.attributes = FALSE)))
Under this generating model, the reported standard errors closely tracked the observed sampling variability. The bias estimate lies less than one Monte Carlo standard error from zero, and the estimated coverage lies within one Monte Carlo standard error of 0.95.
