Lecture 21 EM in R
In example 19.1 we derived the E and M steps of the EM algorithm for a two-component normal mixture. In this lecture we write the two steps as R functions, check them against the hand computation of exercise 20.2 and run them on a simulated sample of size . We end with label switching and the effect of a poor starting value.
21.1 The E and M Steps as R Functions
Throughout, the parameter is the vector and the common standard deviation is known. The E step of example 19.1 computes the responsibilities and the M step computes the updates (19.1). Both steps need only vector arithmetic and the normal density, which the command dnorm can be used to compute. To check the iteration, we also compute the observed-data log-likelihood , which by proposition 20.2 cannot decrease from one iteration to the next.
resp <- function(x, theta, sigma) { a <- theta[1] * dnorm(x, mean = theta[2], sd = sigma) b <- (1 - theta[1]) * dnorm(x, mean = theta[3], sd = sigma) a / (a + b)}mstep <- function(x, gamma) { c(mean(gamma), sum(gamma * x) / sum(gamma), sum((1 - gamma) * x) / sum(1 - gamma))}loglik <- function(x, theta, sigma) { sum(log(theta[1] * dnorm(x, mean = theta[2], sd = sigma) + (1 - theta[1]) * dnorm(x, mean = theta[3], sd = sigma)))}We first test the functions on the data of exercise 20.2, the five observations with and the initial value . We run one iteration and compare the responsibilities, the iterate and the two values of the log-likelihood with the hand computation.
Everything agrees with the hand computation ( differs in the last digit because the hand computation rounded the intermediate sums).
21.2 A Larger Sample
The two groups in the five observations of exercise 20.2 are far apart, and the iteration converges to , as stated in section 20.2. We now simulate a larger sample in which the groups overlap. For each observation we first choose a group, using the command rbinom to set with probability . For the other group R gives the value instead of , and thus z == 0 marks group 2. We then simulate the observation from the normal distribution of its group, with mean or and . The command ifelse can be used to choose the mean for each observation.
The box below contains the complete script for the simulation and the EM iteration, with the lines shuffled except for the body of the loop. Before you can run the script, you have to put these lines into a working order. The loop uses the stopping rule of section 20.2: the command break ends it as soon as the log-likelihood increases by less than . The vector ll stores the log-likelihood after each iteration, with the initial value at position .
theta <- c(0.5, q[1], q[2])for (k in 1:1000) { theta <- mstep(x, resp(x, theta, 1)) ll[k + 1] <- loglik(x, theta, 1) if (ll[k + 1] - ll[k] < 1e-8) break}z <- rbinom(n, size = 1, prob = 0.3)n <- 200q <- quantile(x, c(0.25, 0.75), names = FALSE)set.seed(2026)ll <- loglik(x, theta, 1)x <- rnorm(n, mean = ifelse(z == 1, 0, 3), sd = 1)The order follows the rule of lecture 9: each line must come after all lines on which it depends. As in that lecture, several orders satisfy the rule. One of them is the seed, n, z, x, the quartiles q, the start value and the first entry of ll, followed by the loop. The seed and n can also be swapped. The start value puts the weight at and the two means at the lower and upper quartiles, which is a simple way to split the sample into two groups. After the loop, the variable k holds the number of the last iteration.
Before you look at the output, answer two questions. Will the loop need fewer than iterations, between and , or more than ? Will the log-likelihood increase by the same amount in each iteration?
The loop stops at the fixed point . Its weight is close to the proportion of group-1 observations which were actually drawn, rather than to , and its two means are within about two tenths of the true values. By proposition 20.3 the fixed point is a root of the likelihood equation.
The command diff can be used to compute the differences of consecutive entries of a vector, and thus d holds the increases of the log-likelihood in the iterations. The last two lines of the output show the first seven increases and seven increases near the end. They are all positive, as proposition 20.2 guarantees, but they are not equal. Towards the end, each increase is about times the previous one, for example , then and . This is the geometric convergence mentioned in section 20.2. Since is approximately , at this rate about further iterations are needed to reduce the increase from in the seventh iteration to below the tolerance , which explains the total of iterations. The factor depends on the data, and the take-home task below shows what happens when the groups overlap more.
At the fixed point the responsibility of group 1 is a decreasing function of which equals where . Before you look at figure 21.1, predict where the crossing lies: at the midpoint of the two fitted means, or above or below this point?

The crossing lies at , well below the midpoint , since the weights are unequal: an observation half-way between the means is about three times as likely to come from the larger group as from the smaller one. The filled and open circles give the true group of each observation, which is not known to EM. Far from the crossing point the responsibilities agree with the true groups, but between and observations from both groups occur, and the value of an observation there does not decide its group. The figure is drawn by the script R/S21-mixture.R.
21.3 Label Switching and a Poor Start
Section 20.2 discusses label switching and the danger of a poor start. In the script R/S21-starts.R the loop is packaged as a function em, which is then run on our sample from three starts: the quartile start, the same start with the two means swapped, and the start with both means equal. Before you look at table 21.1, answer two questions. Where does the start with the swapped means end up? What happens to the responsibilities, and thus to the next update, when ?
| start | iterations | ||||
| quartiles | 0.2397 | 0.2202 | 3.0761 | 28 | |
| swapped | 0.7603 | 3.0761 | 0.2202 | 28 | |
| equal | 0.5000 | 2.3915 | 2.3915 | 2 |
The start with swapped means ends in the mirror image after the same iterations and with the same log-likelihood. Both parameter values give the same density, and thus the model is not identifiable in the sense of definition 4.10. The labelling in the start determines which of the two maxima we reach.
When , the two normal densities in the responsibility cancel, all are equal to , and the M step sets both means equal to the sample mean while leaving the weight unchanged. The next step changes nothing, and the loop stops after two iterations at . This is effectively a single normal distribution, with a log-likelihood below the maximum. By proposition 20.3 the point is a root of the likelihood equation. Since the density does not depend on when , every point is such a root, and the weight is the weight of the start.
The point is not a local maximum. The log-likelihood at the nearby start is already . This is slightly above the value at the point itself, and figure 21.2 shows that EM started there climbs all the way to the maximum. Neither is it a local minimum, since among the points with the log-likelihood is largest at the sample mean. The point is thus a saddle point, and EM stops there just as it would at a maximum. The figure also shows that near the saddle point the log-likelihood increases only slowly at first: the first iteration from the nearby start gains only . With a coarse tolerance such as , the loop would have stopped there, far away from the maximum.

21.4 A Task to Take Home
The published scripts of this lecture can be used as a starting point for the following task. Choose a weight between and and two means which are two to three units apart. Using your student ID as the seed, simulate a sample of size from the mixture with and run the EM algorithm from the quartile start. The EM algorithm does not provide standard errors. To obtain them, use optim with hessian = TRUE to minimise the negative of loglik, starting from the fixed point, as in lecture 18. The script R/S21-mixture.R contains the necessary command. Report each estimate with its standard error. Then repeat the task with the two means only one unit apart. How many iterations does the loop need now? What happens to the standard errors? If the loop runs through all iterations, the stopping rule was never met and the result is not a fixed point. Say so in your answer if this happens.
Typing the commands yourself is an important step towards understanding how the R scripts work. Before the next session, please type in the commands from this session and check that you get the results shown in the text.
-
•
The written reference for the R code in this session is appendix B.
-
•
The E step and M step from example 19.1 involve only a few lines of vector arithmetic. For five observations, these lines reproduce the hand computation.
-
•
For a sample of size with overlapping groups, EM converges in iterations. The log-likelihood increases in every step, as required by proposition 20.2. Near the fixed point each increase is about times the previous one, and this geometric convergence sets the number of iterations.
-
•
The responsibility of group 1 is a decreasing S-shaped function of . The function crosses below the midpoint of the means when group 1 is the smaller group. Close to the crossing point it is no longer possible to decide which group an observation belongs to.
-
•
If the labels are swapped before starting the EM algorithm, the algorithm converges to the mirror-image maximum with the same log-likelihood. If the two means are equal at the start, the EM algorithm stops after two iterations at a saddle point, i.e. at a root of the likelihood equation which is not a maximum. As a precaution, EM is run from several starting values, and the run with the largest observed-data log-likelihood is kept.