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 200200. 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 θ=(π,μ1,μ2)\theta=(\pi,\mu_{1},\mu_{2}) and the common standard deviation σ\sigma is known. The E step of example 19.1 computes the responsibilities γi,k\gamma_{i,k} 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 ℓ\ell, 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 x=(0,1,5,6,7)x=(0,1,5,6,7) with σ=1\sigma=1 and the initial value θ0=(1/2,2,4)\theta_{0}=(1/2,2,4). We run one iteration and compare the responsibilities, the iterate θ1\theta_{1} and the two values of the log-likelihood with the hand computation.

x <- c(0, 1, 5, 6, 7)
theta <- c(0.5, 2, 4)
gamma <- resp(x, theta, 1)
round(gamma, 4)
theta1 <- mstep(x, gamma)
theta1
c(loglik(x, theta, 1), loglik(x, theta1, 1))
## [1] 0.9975 0.9820 0.0180 0.0025 0.0003
## [1] 0.4000671 0.5444727 5.9709581
## [1] -17.518842 -9.212934

Everything agrees with the hand computation (μ2,1\mu_{2,1} 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 (0.4,0.5,6.0)(0.4,0.5,6.0), 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 Zi=1Z_{i}=1 with probability π=0.3\pi=0.3. For the other group R gives the value 0 instead of 22, and thus z == 0 marks group 2. We then simulate the observation from the normal distribution of its group, with mean 0 or 33 and σ=1\sigma=1. 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 10−810^{-8}. The vector ll stores the log-likelihood after each iteration, with the initial value at position 11.

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 <- 200
q <- 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 1/21/2 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 1010 iterations, between 1010 and 5050, or more than 5050? Will the log-likelihood increase by the same amount in each iteration?

table(z)
k
round(theta, 4)
round(ll[k + 1], 3)
d <- diff(ll)
signif(d[1:7], 2)
signif(d[21:27], 2)
## z
## 0 1
## 152 48
## [1] 28
## [1] 0.2397 0.2202 3.0761
## [1] -354.505
## [1] 5.00 4.40 3.80 3.00 2.10 1.20 0.66
## [1] 3.3e-06 1.3e-06 5.4e-07 2.2e-07 8.8e-08 3.6e-08 1.4e-08

The loop stops at the fixed point θ^=(0.240,0.220,3.076)\hat{\theta}=(0.240,0.220,3.076). Its weight is close to the proportion 48/200=0.2448/200=0.24 of group-1 observations which were actually drawn, rather than to π=0.3\pi=0.3, 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 2828 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 0.40.4 times the previous one, for example 3.3⋅10−63.3\cdot 10^{-6}, then 1.3⋅10−61.3\cdot 10^{-6} and 5.4⋅10−75.4\cdot 10^{-7}. This is the geometric convergence mentioned in section 20.2. Since 0.66⋅0.4200.66\cdot 0.4^{20} is approximately 7⋅10−97\cdot 10^{-9}, at this rate about 2020 further iterations are needed to reduce the increase from 0.660.66 in the seventh iteration to below the tolerance 10−810^{-8}, which explains the total of 2828 iterations. The factor 0.40.4 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 xx which equals 1/21/2 where π⁢φσ⁢(x−μ1)=(1−π)⁢φσ⁢(x−μ2)\pi\varphi_{\sigma}(x-\mu_{1})=(1-\pi)\varphi_{\sigma}(x-\mu_{2}). Before you look at figure 21.1, predict where the crossing lies: at the midpoint 1.6481.648 of the two fitted means, or above or below this point?

Two panels. Top: histogram of 200 observations with
a peak near 3 and a shoulder near 0, together with the fitted mixture
density (solid line) and its two weighted components (dashed lines),
centred at 0.22 and 3.08. Bottom:
responsibilities as a function of x, showing an S-shaped curve which
decreases from 1 to 0. The curve crosses the level 1/2 at x = 1.244
(dotted lines). Filled points on the left, open points on the
right, both mixed between 0.7 and 1.6.
Figure 21.1: The fitted mixture density with its two weighted components (top panel) and the responsibilities of group 1 at the fixed point as a function of the observations (bottom panel). The filled circles mark the observations which were simulated from group 1. The dotted lines give the responsibility 1/21/2 and the crossing point 1.2441.244.

The crossing lies at 1.2441.244, well below the midpoint 1.6481.648, 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 0.70.7 and 1.61.6 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 (1/2,3,3)(1/2,3,3) 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 μ1=μ2\mu_{1}=\mu_{2}?

start π\pi μ1\mu_{1} μ2\mu_{2} ℓ\ell iterations
quartiles 0.2397 0.2202 3.0761 −354.5046-354.5046 28
swapped 0.7603 3.0761 0.2202 −354.5046-354.5046 28
equal 0.5000 2.3915 2.3915 −421.8067-421.8067 2
Table 21.1: The fixed points, their log-likelihoods and the numbers of iterations of the EM algorithm for three starts, computed by the script R/S21-starts.R.

The start with swapped means ends in the mirror image (0.760,3.076,0.220)(0.760,3.076,0.220) after the same 2828 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 μ1=μ2\mu_{1}=\mu_{2}, the two normal densities in the responsibility cancel, all γi\gamma_{i} are equal to π\pi, 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 (1/2,2.3915,2.3915)(1/2,2.3915,2.3915). This is effectively a single normal distribution, with a log-likelihood 6767 below the maximum. By proposition 20.3 the point is a root of the likelihood equation. Since the density does not depend on π\pi when μ1=μ2\mu_{1}=\mu_{2}, every point (π,x¯,x¯)(\pi,\bar{x},\bar{x}) is such a root, and the weight 1/21/2 is the weight of the start.

The point (1/2,x¯,x¯)(1/2,\bar{x},\bar{x}) is not a local maximum. The log-likelihood at the nearby start (1/2,2.39,2.41)(1/2,2.39,2.41) is already −421.800-421.800. This is slightly above the value −421.807-421.807 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 μ1=μ2\mu_{1}=\mu_{2} 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 0.070.07. With a coarse tolerance such as 0.10.1, the loop would have stopped there, far away from the maximum.

Log-likelihood as a function of iteration number.
The thick, solid curve starts at -375 and gradually flattens to
-354.5 and ends after iteration 28. The dotted curve starts at
-422, is nearly constant for the first two iterations, then
increases to the same plateau as the solid curve and ends after
iteration 33. The dash-dotted line with crosses starts at -459,
jumps to -422 in the first iteration and ends after iteration 2.
Figure 21.2: Log-likelihood of the simulated data as a function of the iteration number of the EM algorithm, for the quartile start (solid line), for the start (1/2,2.39,2.41)(1/2,2.39,2.41) with nearly equal means (dotted line) and for the start with equal means (dash-dotted line with crosses). The trace of the start with swapped means coincides with the solid line.

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 π\pi between 0.20.2 and 0.50.5 and two means which are two to three units apart. Using your student ID as the seed, simulate a sample of size n=300n=300 from the mixture with σ=1\sigma=1 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 10001000 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.

Summary.
  • •
    ​

    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 200200 with overlapping groups, EM converges in 2828 iterations. The log-likelihood increases in every step, as required by proposition 20.2. Near the fixed point each increase is about 0.40.4 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 xx. The function crosses 1/21/2 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.