← back to EEE 485
Week 10127 min full read
7 concepts20 worked examples32 exercises5 exam-level7 figures
What are you here for?

10 Clustering: K-means, mixtures of Gaussians and the EM algorithm

Start with this

One question before you read anything. Getting it wrong is the point: it shows you what this section is for.

§10.6 — a bag exactly halfway between two machines

Machine 1 fills $60$ of every $100$ bags, with weights $\mathcal N(500,\,2^2)$ in grams; machine 2 fills the other $40$, with weights $\mathcal N(510,\,2^2)$. A bag weighing exactly $505$ g comes off the belt.

Find(a) What is the probability that machine 1 filled this bag?
Given
  • machine 1: share $0.6$, weights $\mathcal N(500,4)$

  • machine 2: share $0.4$, weights $\mathcal N(510,4)$

  • the bag weighs $505$ g

Hint 1/4

Ask what the weight adds to what you already know about how common each machine is; no density values are needed yet.

Hint 2/4

Bayes' rule: $\Pr(1\mid x)=\dfrac{\pi_1\,p_1(x)}{\pi_1\,p_1(x)+\pi_2\,p_2(x)}$.

Hint 3/4

Here $\pi_1=0.6$, $\pi_2=0.4$, and $505$ is $5$ g from both means $500$ and $510$, with the same spread $\sigma=2$ for both machines.

Hint 4/4

The two densities are equal and cancel, so the probability is $0.6/(0.6+0.4)=0.6$.

Show solution

Bayes' rule is the direct route, and the symmetry of the two densities does most of the work.

Compare the densities

$$\mathcal N(505\mid500,4)=\mathcal N(505\mid510,4)$$

Both means are $5$ g away and both variances are $4$.

Apply Bayes' rule

$$\Pr(1\mid505)=\frac{0.6\,c}{0.6\,c+0.4\,c}=0.6$$

The common density value $c$ cancels.

Answer $$\boxed{0.6}$$
Check

Edge check: with equal shares $0.5$ and $0.5$ the same computation gives $0.5$, the symmetric answer most people expect here.

Near the middle between two components the prior shares decide; this section calls the result a .

Two machines fill coffee bags onto one belt, and nobody records which machine filled which bag. The weights crowd around $500$ g and around $510$ g, so the average weight, $504$ g, turns up seven times less often than $500$ g. A $506$ g bag comes past: which machine filled it, and how sure can you be?

By the end you can run and EM by hand, and you will have the number for the $506$ g bag: out of $100$ such bags, about $89$ come from machine 2.

In 60 seconds

K-means splits unlabeled points into $K$ groups by alternating nearest-prototype assignments with cluster means; a mixture of Gaussians does the same softly, and EM fits it by alternating responsibilities with weighted means, covariances and shares.

K-means
$$\begin{aligned}J&=\textstyle\sum_i\sum_k r_{ik}{\lVert x_i-\mu_k\rVert}^2\\ \text{E: }r_{ik}&=1\ \text{for the nearest }\mu_k\\ \text{M: }\mu_k&=\frac{\sum_i r_{ik}x_i}{\sum_i r_{ik}}\end{aligned}$$

grouping points by hand: repeat the two steps until no point changes cluster

Responsibility
$$\gamma(z_{ij})=\frac{\pi_j\,\mathcal N(x_i\mid\mu_j,\Sigma_j)}{\sum_k\pi_k\,\mathcal N(x_i\mid\mu_k,\Sigma_k)}$$

the probability that component $j$ produced $x_i$; the E step of EM

EM, M step
$$\begin{aligned}N_j&=\textstyle\sum_i\gamma(z_{ij}),\quad \pi_j=N_j/n\\ \mu_j&=\tfrac{1}{N_j}\textstyle\sum_i\gamma(z_{ij})\,x_i\\ \Sigma_j&=\tfrac{1}{N_j}\textstyle\sum_i\gamma(z_{ij})\\ &\quad\times(x_i-\mu_j){(x_i-\mu_j)}^T\end{aligned}$$

refitting every component with the responsibilities held fixed; $\Sigma_j$ uses the new $\mu_j$

Compressed image
$$24K+n\lceil\log_2K\rceil\ \text{ bits, against }24n$$

an $n$-pixel RGB image stored as $K$ colors plus one label per pixel

Three most common mistakes
  1. Dropping $\pi_j$ from the responsibility. It is $\pi_j\mathcal N(x_i\mid\mu_j,\Sigma_j)$ over the sum, not $\mathcal N$ alone: halfway between two equal-variance components the answer is the prior share, not $0.5$.

  2. Dividing by $n$ instead of $N_j$ in the M step. $\mu_j=\sum_i\gamma(z_{ij})x_i/N_j$ with $N_j=\sum_i\gamma(z_{ij})$, and only the share uses $n$: $\pi_j=N_j/n$.

  3. Trusting one run. K-means and EM both stop at a local optimum that depends on the start; run from several starts and keep the smallest $J$ or the largest $l$.

Two course documents give different weights:

  • Chapter 1 slides, undergraduate line: midterm 25, final 25, four quizzes 20, two-phase project 30.
  • STARS syllabus page printed on 21 September 2026: midterm 30, final 30, problem sets and quizzes 20, project 20. It is the later document; confirm which split applies.
  • The STARS weekly list has this topic as its eighth item; the lecture slides number it chapter 10.
How much time do you have?
10 minutes

The two algorithms in the form exams ask for: the K-means steps, the responsibility and the EM updates.

The 60-second card · K-means · Responsibilities · EM for a Gaussian mixture · Formula card
45 minutes

Every block once with its first worked example, then one EM iteration from fully worked to bare.

The 60-second card · K-means · K-medoids · Compressing an image with K-means · EM on two coins · A mixture of Gaussians · Responsibilities · EM for a Gaussian mixture · Scaffolding comes off · Formula card
full read

Adds the derivations, the look-alike pairs and mixed practice where you pick the method yourself.

The opening pages · Recall first · K-means · K-medoids · Compressing an image with K-means · EM on two coins · A mixture of Gaussians · Responsibilities · EM for a Gaussian mixture · Look-alike pairs · Method boxes · Scaffolding comes off · Full exam-style question · Practice set · Check yourself
By the end of this section
  1. Run K-means by hand: assign each point to its nearest prototype, move each prototype to its cluster mean, track $J$, and recognize a start that ends in a .

  2. Apply K-medoids with the Manhattan or the , choosing each prototype among the cluster's own points.

  3. Compute the size of an image compressed by K-means and compare it with the original.

  4. Estimate two coin biases with EM when the coin behind each run is hidden, and compare with the estimate from known coins.

  5. Write a Gaussian mixture as a model, evaluate its density and its moments, and count its parameters.

  6. Compute responsibilities, and explain why they can disagree with the nearest mean.

  7. Perform one EM iteration for a Gaussian mixture, derive its M step, and check that the log-likelihood went up.

Syllabus coverage

Clustering — covered

K-means

  • indicator variables, the $J$, the E and M steps and why each is exact, convergence to a local minimum
  • K-medoids with a general dissimilarity
  • and compression

The lecturer's chapter title. Spread over three blocks, in the lecture's order.

Probabilistic clustering — covered

: the responsibility of each component for each point, as the posterior of a hidden label, and how it differs from the of K-means.

The contrast with K-means comes back in the first look-alike pair.

mixture of Gaussians — covered

  • The multivariate Gaussian
  • the mixture density and its
  • the latent one-hot variable with $p(z)$ and $p(x\mid z)$
  • the log-likelihood of a sample
  • the number of parameters

expectation maximization — covered

EM on two coins with hidden labels, complete against ; EM for a Gaussian mixture: the E and M steps, where the M step comes from, the log-likelihood as a stopping rule, starting from K-means, restarts.

The lecture introduces EM on the two-coin experiment before the mixture, and so does this section.

Why the log-likelihood never decreases under EM — off syllabus

The monotonicity of EM, used here to check every worked iteration.

Further reading: stated without proof. The proof uses Jensen's inequality and is not on the slides.

Singular solutions of the mixture likelihood — off syllabus

A component that shrinks onto one data point sends $l$ to infinity.

Further reading, not on the slides. It explains why software keeps each variance above a small floor.

Choosing K with a held-out log-likelihood — off syllabus

Validation log-likelihood against training log-likelihood as $K$ grows.

Further reading: it joins this section with the cross-validation section and is used in one interleaved practice question only.

Recall first
Bayes' rule and total probability

For events $A_1,\dots,A_K$ that split the sample space: $P(A_j\mid B)=\dfrac{P(B\mid A_j)P(A_j)}{\sum_{k=1}^KP(B\mid A_k)P(A_k)}$; the denominator is $P(B)$ by the law of total probability.

Coin posteriors and responsibilities are exactly this formula.

Maximum likelihood estimates

For i.i.d. data $\hat\theta=\arg\max_\theta\sum_i\log p(x_i\mid\theta)$. For binomial runs this is heads over flips; for a Gaussian, $\hat\mu=\frac1n\sum_ix_i$ and $\hat\sigma^2=\frac1n\sum_i(x_i-\hat\mu)^2$.

Every M step is one of these, with weights.

Binomial probabilities

$\Pr(x=k)=\binom{F}{k}\theta^k(1-\theta)^{F-k}$ for $k$ heads in $F$ flips with heads probability $\theta$.

Each coin run is one binomial draw.

The multivariate Gaussian

$$\mathcal N(x\mid\mu,\Sigma)=\dfrac{1}{(2\pi)^{p/2}\lvert\Sigma\rvert^{1/2}}\exp\!\big(-\tfrac12(x-\mu)^T\Sigma^{-1}(x-\mu)\big)$$ with $\mu=E[X]$ and $\Sigma=E[(X-\mu)(X-\mu)^T]$. For $\Sigma=\sigma^2I$ it is a product of $p$ one-dimensional densities.

Each mixture component is one.

The mean minimizes squared distance

$\sum_i\lVert x_i-c\rVert^2=\sum_i\lVert x_i-\bar x\rVert^2+n\lVert\bar x-c\rVert^2$, so $c=\bar x$ is the unique minimizer.

This is the M step of K-means.

Law of total expectation

$E[X]=\sum_jP(j)\,E[X\mid j]$, and the same for $E[X^2]$.

It gives the mean and variance of a mixture.

To maximize $f(\pi)$ subject to $g(\pi)=0$, set $\nabla\big(f+\lambda g\big)=0$ and solve together with the constraint.

The shares $\pi_j$ must add up to $1$.

Two-way posteriors as a logistic function

$\dfrac{a}{a+b}=\dfrac{1}{1+e^{-d}}$ with $d=\log(a/b)$.

With two components, a responsibility comes from one log-odds.

Try it yourself first (2 questions)
1§10.1 — one number to stand for four readings

Four readings on a line are $0$, $1$, $2$ and $9$. We want one number $c$ that stands for all four, in the sense that $\sum_i(x_i-c)^2$ is as small as possible.

Find(a) Which $c$ is best?
Given
  • readings $0,\ 1,\ 2,\ 9$

  • criterion: $\sum_i(x_i-c)^2$ as small as possible

Hint 1/4

Treat the sum as a function of $c$ and look for its lowest point instead of trying values.

Hint 2/4

A smooth function is lowest where its derivative is $0$: $\frac{d}{dc}\sum_i(x_i-c)^2=-2\sum_i(x_i-c)$.

Hint 3/4

Readings $0,1,2,9$: setting $\sum_i(x_i-c)=0$ gives $0+1+2+9=4c$.

Hint 4/4

$c=12/4=3$, the mean of the readings.

Show solution

Differentiating once is shorter than comparing candidates, and it works for any data.

Set the derivative to zero

$$\begin{aligned}&S'(c)=-2\big[(0-c)+(1-c)\\ &\qquad+(2-c)+(9-c)\big]\\ &\quad=-2(12-4c)\end{aligned}$$

Each squared term contributes $-2(x_i-c)$.

$$S'(c)=0\ \Rightarrow\ c=3$$

$S$ is a parabola opening upward, so this is its minimum.

Answer $$\boxed{c=3}$$
Check

Direct values: $S(3)=9+4+1+36=50$, $S(2)=4+1+0+49=54$, $S(1.5)=S(4.5)=59$.

The K-means M step is this computation, done separately for each cluster.

2§10.4 — a coin that might be biased

A bag holds two coins: a fair one and one that lands heads with probability $0.9$. You draw one at random, flip it twice, and see two heads.

Find(a) What is the probability that you drew the biased coin?
Given
  • fair coin: $\Pr(H)=0.5$; biased coin: $\Pr(H)=0.9$

  • each coin is drawn with probability $1/2$

  • observed: $H,\,H$

Hint 1/4

Ask how much more likely two heads are with one coin than with the other, then weigh that by how likely each coin was to be drawn.

Hint 2/4

Bayes' rule: $\Pr(B\mid D)=\dfrac{\Pr(D\mid B)\Pr(B)}{\Pr(D\mid B)\Pr(B)+\Pr(D\mid F)\Pr(F)}$.

Hint 3/4

$\Pr(HH\mid B)=0.9^2=0.81$, $\Pr(HH\mid F)=0.5^2=0.25$, and $\Pr(B)=\Pr(F)=1/2$.

Hint 4/4

$0.81/(0.81+0.25)=0.764$.

Show solution

Bayes' rule with the two likelihoods; the equal priors cancel at once.

Likelihoods

$$\begin{aligned}&\Pr(HH\mid B)=0.81\\ &\Pr(HH\mid F)=0.25\end{aligned}$$

The two flips are independent given the coin.

Posterior

$$\begin{aligned}&\Pr(B\mid HH)\\ &\quad=\frac{0.81\cdot\frac12}{0.81\cdot\frac12+0.25\cdot\frac12}\\ &\quad=\frac{0.81}{1.06}=0.764\end{aligned}$$

Divide by the total probability of two heads.

Answer $$\boxed{0.764}$$
Check

Odds check: prior odds $1:1$ times the likelihood ratio $0.81/0.25=3.24$ gives $3.24:1$, and $3.24/4.24=0.764$.

EM's E step computes exactly this for every run of flips, with the current guesses in place of the known $0.9$ and $0.5$.

Notation
symbolreads asmeanswatch out
$\{x_i\}_{i=1}^n,\ \ x_i=(x_{i1},\dots,x_{ip})$

the data

$n$ unlabeled points in $\mathbb R^p$

There are no labels $y_i$.

$K$

K

the number of clusters or components

Chosen before the run; neither K-means nor EM estimates it.

$r_{ik}$

r i k

$1$ if point $i$ is in cluster $k$, else $0$

Exactly one $1$ per point: $\sum_kr_{ik}=1$.

$k_i^*$

k i star

the cluster the E step gives point $i$: the index of its nearest prototype

With a tie, the conventions below decide.

$\mu_k$

mu k

the prototype of cluster $k$, or the mean of component $k$

In K-medoids it must be one of the data points.

$J,\ \ \tilde J$

J, J tilde

the distortion: total squared distance (K-means), total dissimilarity (K-medoids)

$J$ adds squared distances, not distances.

$N_k\ \ \text{(K-medoids)}$

N k

the set of points in cluster $k$

In EM, $N_j$ is a number, not a set.

$V(x_i,\mu_k)$

V of x i and mu k

a dissimilarity, such as the Manhattan or the cosine dissimilarity

The cosine dissimilarity is $1-\cos$, not $\cos$.

$\theta_A,\ \theta_B,\ z_i,\ F$

theta A, theta B, z i, F

heads probabilities of coins A and B, the coin of run $i$, flips per run

$z_i$ is hidden in the EM version.

$\mathcal N(x\mid\mu,\Sigma)$

normal density of x given mu and Sigma

the Gaussian density

In one dimension $\Sigma=\sigma^2$, a variance.

$\mathcal N_j(x)$

N j of x

short for $\mathcal N(x\mid\mu_j,\Sigma_j)$

Used in the mistake boxes to keep formulas short.

$\pi_j$

pi j

the mixing coefficient: the share of component $j$

Not $3.14\ldots$; the $\pi_j$ add up to $1$.

$z=(z_1,\dots,z_K)$

z

the hidden one-hot label of a point

$z_j=1$ means component $j$ produced the point.

$\gamma(z_{ij})$

gamma of z i j

the responsibility $p(z_{ij}=1\mid x_i)$

One number per point and component; each point's add up to $1$.

$N_j\ \ \text{(EM)}$

N j

the of component $j$, $\sum_i\gamma(z_{ij})$

Usually not a whole number; $\sum_jN_j=n$.

$l(\pi,\mu,\Sigma)$

l of pi, mu, Sigma

the log-likelihood $\sum_i\log p(x_i)$

Natural log of a sum, per point.

$\theta^{(s)}$

theta at step s

a parameter after $s$ EM iterations

$s=0$ is the start.

Conventions used here
Squared Euclidean distance.

$\lVert x-\mu\rVert^2=\sum_{j=1}^p(x_j-\mu_j)^2$. K-means assigns and scores with it; the square root is never taken.

The nearest prototype is the same with or without the root, and squares add up to J.

Ties in the E step.

A point moves only to a strictly nearer prototype. In the first E step, where no point has a cluster yet, a tie goes to the smaller index $k$.

With this rule J drops strictly whenever a point moves, which is what makes the run stop.

Empty clusters.

If an E step leaves a cluster with no points, its prototype stays where it was. None of the examples here runs into this.

The mean of no points is undefined; some implementations re-seed the prototype instead.

When to stop.

K-means stops when an E step changes no assignment. EM stops when $l$ changes by less than a tolerance, or after a fixed number of iterations.

K-means reaches an exact fixed point; EM usually only approaches one.

Natural logarithm.

$\log$ always means $\ln$, base $e$, in every log-likelihood and log-odds here.

Another base would only rescale l; every derivative on this page assumes base e.

Variances, not standard deviations.

$\mathcal N(\mu,v)$ always has the variance second, so $\mathcal N(x\mid\mu_j,\sigma_j^2)$ is read with $\sigma_j^2$, and a question that gives a standard deviation $\sigma$ means the variance $\sigma^2$. The M step divides the weighted squares by $N_j$.

That is the maximum likelihood estimate the updates come from; mixing the two gets a variance wrong by a square.

Coin priors.

In the coin examples each coin is picked with probability $1/2$, and this prior is not estimated.

Only the two heads probabilities are unknown, as in the lecture's setup.

Four decimals.

Numbers are shown to four decimals and computed from unrounded values, so recomputing from the rounded ones can move the last digit.

Responsibilities close to 0 or 1 need the digits.

10.1K-means: nearest prototype, then cluster mean, until nothing moves

Groups unlabeled points by alternating two easy steps: each point joins its nearest prototype, each prototype moves to its group's mean.

Regression and classification learned from labeled pairs $(x_i,y_i)$; here there are only points $\{x_i\}_{i=1}^n$, and the groups themselves are the unknown.

Solvable with what we have
  • Given two relay positions, send each sensor to the nearer one by comparing squared distances.

  • Given a group of points, find the single point with the smallest total squared distance to them: their mean.

Not solvable yet
  • Choose the groups and the relay positions at the same time.

  • Tell whether a grouping is the best one without scoring every possible split.

Six sensors sit at $x_1=(1,1)$, $x_2=(2,1)$, $x_3=(1,2)$, $x_4=(5,4)$, $x_5=(6,5)$, $x_6=(5,6)$ (km). A radio link costs energy in proportion to its squared length.

  • Put the two relays on $x_1$ and $x_2$.
  • Send every sensor to the nearer relay: $x_3$ joins relay 1; $x_4,x_5,x_6$ join relay 2.
  • Total cost: $J=0+1+0+18+32+34=85$.
Why it fails

Each easy step was used once and never repeated. Relay 2 sits on $x_2$, far from the three sensors it mostly serves. Moving each relay to its group's mean, regrouping and repeating brings $J$ down to $4$.

MethodK-means
Conditions
  • data $\{x_i\}_{i=1}^n$ with $x_i\in\mathbb R^p$; the number of clusters $K$ is fixed in advance

  • hard assignment: $r_{ik}\in\{0,1\}$ and $\sum_{k=1}^Kr_{ik}=1$ for every $i$

  • a start: $K$ initial prototypes $\mu_1,\dots,\mu_K$

$$\boxed{\begin{aligned}&J=\sum_{i=1}^n\sum_{k=1}^K r_{ik}\lVert x_i-\mu_k\rVert^2\\[3pt] &\text{E: }k_i^*=\arg\min_j\lVert x_i-\mu_j\rVert^2\\ &\phantom{\text{E: }}r_{ik}=1\text{ if }k=k_i^*\text{, else }0\\[3pt] &\text{M: }\mu_k=\frac{\sum_{i=1}^n r_{ik}\,x_i}{\sum_{i=1}^n r_{ik}}\end{aligned}}$$

$J$ adds up each point's squared distance to the prototype of its own cluster. The E step holds the prototypes and sends every point to the nearest one; the M step holds the groups and moves every prototype to the mean of its group. Repeat until an E step changes nothing.

Why each step is exact, and why the run stops

E step. With the prototypes fixed, $J$ is a sum of one term per point, $\sum_kr_{ik}\lVert x_i-\mu_k\rVert^2$, and each term is smallest when its single $1$ sits at the nearest prototype.

M step. With the groups fixed, $J$ is quadratic in $\mu_k$, and $\nabla_{\mu_k}J=-2\sum_ir_{ik}(x_i-\mu_k)=0$ gives the mean of cluster $k$. The denominator $\sum_ir_{ik}$ counts its points. $K$ clusters, $K$ means: hence the name.

It stops. Neither step can raise $J$. An E step that moves a point lowers $J$ strictly, because a point only moves to a strictly nearer prototype, so no assignment can come back. There are at most $K^n$ assignments, so the run ends.

Where it stops. At an assignment that neither step can improve: a local minimum that depends on the start. The lecture notes point out that minimizing $J$ exactly is NP-hard, which is why we settle for this.

Looks like this, but is not

Pick $K$ by running K-means for $K=1,2,3,\dots$ and keeping the $K$ with the smallest $J$.

$J$ can only fall as $K$ grows. For the six sensors the best $J$ is $48.17$ at $K=1$, $4$ at $K=2$, $2.33$ at $K=3$ and $0$ at $K=6$, where every sensor is its own prototype. The smallest $J$ always picks the largest $K$.

sensorto μ₁to μ₂cluster

$x_1=(1,1)$

$0.25$

$21.25$

1

$x_2=(2,1)$

$1.25$

$15.25$

1 (was 2)

$x_3=(1,2)$

$0.25$

$16.25$

1

$x_4=(5,4)$

$22.25$

$0.25$

2

$x_5=(6,5)$

$37.25$

$3.25$

2

$x_6=(5,6)$

$36.25$

$4.25$

2

Only $x_2$ changes cluster at this step: $1.25<15.25$, so it leaves relay 2 for relay 1.

K-means on six sensors, starting from relays on sensors 1 and 2

Run K-means with $K=2$ on the six sensors, starting from $\mu_1=x_1$ and $\mu_2=x_2$, until an E step changes no assignment. Report the clusters, the prototypes and $J$ after every half-step.

FindThe final clusters and prototypes, and $J$ after each E and M step.
Given
  • $x_1=(1,1)$, $x_2=(2,1)$, $x_3=(1,2)$, $x_4=(5,4)$, $x_5=(6,5)$, $x_6=(5,6)$ (km)

  • $K=2$; start $\mu_1=(1,1)$, $\mu_2=(2,1)$

  • $J=\sum_i\sum_kr_{ik}\lVert x_i-\mu_k\rVert^2$

Solution

We tabulate squared distances rather than distances: the nearest prototype is the same either way, and the squares add up directly to $J$.

E step 1: each sensor to the nearer relay

$$\begin{aligned}&{\lVert x_3-\mu_1\rVert}^2=1\\ &{\lVert x_3-\mu_2\rVert}^2=2\end{aligned}$$

$x_3$ is nearer to $\mu_1$; $x_1$ and $x_2$ sit on their own relays.

$$\begin{aligned}&x_4,x_5,x_6\text{ to }\mu_2:\ 18,\ 32,\ 34\\ &x_4,x_5,x_6\text{ to }\mu_1:\ 25,\ 41,\ 41\end{aligned}$$

All three far sensors are nearer to $\mu_2=(2,1)$, so cluster 2 is $\{x_2,x_4,x_5,x_6\}$.

$$J=0+1+0+18+32+34=85$$

Each sensor adds its squared distance to its own relay.

M step 1: each relay to its cluster mean

$$\mu_1=\tfrac12\big[(1,1)+(1,2)\big]=(1,\ 1.5)$$

With the clusters fixed, the mean minimizes the squared distances to the members, so cluster 1, $\{x_1,x_3\}$, gets its average.

$$\mu_2=\tfrac14\big[(2,1)+(5,4)+(6,5)+(5,6)\big]=(4.5,\ 4)$$

We divide by the cluster size $4$, not by $n=6$.

$$J=0.25+15.25+0.25+0.25+3.25+4.25=23.5$$

Same groups, better prototypes, so $J$ falls from $85$.

E step 2: sensor 2 switches

$$\begin{aligned}&{\lVert x_2-\mu_1\rVert}^2=1.25\\ &{\lVert x_2-\mu_2\rVert}^2=15.25\end{aligned}$$

$x_2$ is now much nearer to $\mu_1$; the other five keep their clusters.

$$J=0.25+1.25+0.25+0.25+3.25+4.25=9.5$$

Only the term of $x_2$ changed, from $15.25$ to $1.25$.

M step 2, and the stop

$$\begin{aligned}&\mu_1=\big(\tfrac43,\ \tfrac43\big)\\ &\mu_2=\big(\tfrac{16}{3},\ 5\big)\end{aligned}$$

With the clusters fixed, each cluster's mean minimizes its own sum of squared distances.

$$J=\tfrac29+\tfrac59+\tfrac59+\tfrac{10}9+\tfrac49+\tfrac{10}9=4$$

Each sensor's squared distance to its new mean, in ninths.

$$\begin{aligned}&\text{E step 3:}\\ &{\lVert x_4-\mu_2\rVert}^2=\tfrac{10}{9}\\ &{\lVert x_4-\mu_1\rVert}^2=\tfrac{185}{9}\end{aligned}$$

Every sensor is nearest to its own mean, so no assignment changes and the run stops.

Answer $$\boxed{\begin{aligned}&\{x_1,x_2,x_3\},\ \ \mu_1=(\tfrac43,\tfrac43)\\ &\{x_4,x_5,x_6\},\ \ \mu_2=(\tfrac{16}3,5)\\ &J:\ 85\to23.5\to9.5\to4\to4\end{aligned}}$$
Check

Independent check of the final $J$: in a cluster of $m$ points, the squared distances to the mean add up to the sum of all pairwise squared distances divided by $m$. The pairs give $1+1+2=4$ and $2+4+2=8$, so $J=\tfrac43+\tfrac83=4$. Scoring all $31$ two-group splits by computer gives no $J$ below $4$.

Two full iterations and one more E step: $18$ squared distances in all.

This closes the opening attempt: the same two easy steps, repeated until nothing moved, took $J$ from $85$ to $4$.

Four points on a rectangle: a start that traps K-means

The points are $(0,0)$, $(0,2)$, $(6,0)$ and $(6,2)$. Run K-means with $K=2$ from start A, $\mu_1=(3,-1)$ and $\mu_2=(3,3)$, and from start B, $\mu_1=(-1,1)$ and $\mu_2=(7,1)$. Compare the final values of $J$.

FindThe final clusters and $J$ for each start.
Given
  • points $(0,0),\ \allowbreak (0,2),\ \allowbreak (6,0),\ \allowbreak (6,2)$

  • start A: $(3,-1)$ and $(3,3)$; start B: $(-1,1)$ and $(7,1)$

Solution

Each run stops after one E step and one M step, so doing both in full is cheaper than arguing about them.

Start A: top against bottom

$$\begin{aligned}&(0,0),(6,0)\to\mu_1\\ &(0,2),(6,2)\to\mu_2\end{aligned}$$

Each point is $9+1=10$ from its own prototype and $9+9=18$ from the other.

$$\mu_1=(3,0),\quad \mu_2=(3,2),\quad J=4\times9=36$$

Every point is $3$ from its cluster's mean, along the horizontal axis.

$$(0,0):\ \ 9\text{ to }\mu_1,\ \ 13\text{ to }\mu_2$$

The next E step moves no point, so run A stops at $J=36$.

Start B: left against right

$$\begin{aligned}&(0,0),(0,2)\to\mu_1\\ &(6,0),(6,2)\to\mu_2\end{aligned}$$

Each point is $1+1=2$ from its own prototype and $49+1=50$ from the other.

$$\mu_1=(0,1),\quad \mu_2=(6,1),\quad J=4\times1=4$$

Every point is $1$ from its cluster's mean and $37$ from the other, so the next E step moves nothing.

Answer $$\boxed{\begin{aligned}&J_A=36\\ &J_B=4\end{aligned}}$$
Check

Both end states are fixed points. In state A each point is $9$ from its own mean and $13$ from the other, so no E step can move it, although state B has a $J$ nine times smaller.

K-means always stops, but where it stops depends on the start: run it from several starts and keep the smallest $J$.

Checkpoint
§10.1 — one K-means iteration on a line

Five readings on a line are clustered with $K=2$. The run starts from the prototypes $\mu_1=2$ and $\mu_2=3$.

Find(a) After one E step and one M step, what are $\mu_1$ and $\mu_2$?
Given
  • readings: $0,\ 2,\ 3,\ 9,\ 11$

  • start: $\mu_1=2$, $\mu_2=3$

Hint 1/4

First decide which prototype each reading is nearer to; only then average.

Hint 2/4

E step: $r_{ik}=1$ for the nearer prototype. M step: $\mu_k$ is the mean of the readings in cluster $k$.

Hint 3/4

Readings $0,2,3,9,11$ against $\mu_1=2$, $\mu_2=3$: the distances of $0$ are $2$ and $3$, of $3$ are $1$ and $0$, of $9$ are $7$ and $6$.

Hint 4/4

The clusters are $\{0,2\}$ and $\{3,9,11\}$, so $\mu_1=1$ and $\mu_2=23/3\approx7.67$.

Show solution

On a line the squared distance is just $(x-\mu)^2$, so the E step is a comparison of absolute differences.

E step

$$0:\ 4\text{ vs }9;\quad 2:\ 0\text{ vs }1;\quad 3:\ 1\text{ vs }0$$

$0$ and $2$ join $\mu_1$, and $3$ sits on $\mu_2$.

$$9:\ 49\text{ vs }36;\quad 11:\ 81\text{ vs }64$$

Both large readings are nearer to $\mu_2=3$.

M step

$$\begin{aligned}&\mu_1=\tfrac{0+2}{2}=1\\ &\mu_2=\tfrac{3+9+11}{3}=\tfrac{23}{3}\approx7.67\end{aligned}$$

The mean minimizes a cluster's squared distances, so each cluster is averaged over its own members only.

Answer $$\boxed{\begin{aligned}&\mu_1=1\\ &\mu_2=\tfrac{23}{3}\approx7.67\end{aligned}}$$
Check

$J$ check: with the new clusters, $J=4+0+0+36+64=104$ around the old prototypes and $J=2+34.67=36.67$ around the new means, so the M step lowered it, as it must.

Run the E step for every point before touching any prototype.

⚠ Adding distances instead of squared distances

the nearest prototype is the same either way, so the square is easy to drop when adding up

wrong$$J=\sum_i{\lVert x_i-\mu_{k(i)}\rVert}$$
right$$J=\sum_i{\lVert x_i-\mu_{k(i)}\rVert}^2$$
⚠ Dividing by n in the M step

the mean of all the data is the familiar formula

wrong$$\mu_k=\frac1n\sum_ir_{ik}x_i$$
right$$\mu_k=\frac{\sum_ir_{ik}x_i}{\sum_ir_{ik}}$$
⚠ Moving a prototype in the middle of an E step

updating as soon as a point joins feels faster

wrong$$\begin{aligned}&\text{assign }x_1,\ \text{move }\mu_k,\\ &\text{assign }x_2,\ \dots\end{aligned}$$
right$$\begin{aligned}&\text{assign every }x_i,\\ &\text{then move every }\mu_k\end{aligned}$$
0123456701234567x₁ (km)x₂ (km)x₁x₂x₃x₄x₅x₆E step 2: x₂ is now nearer to μ₁J = 9.5ringed x₂: squared distance1.25 to μ₁, 15.25 to μ₂dashed: equally farfrom μ₁ and μ₂

Step through the run of the first worked example. Each sensor takes the color of its cluster, diamonds mark the relays, and the dashed line holds the points equally far from both relays: the E step switches there. Each frame prints $\textcolor{#8250df}{J}$.

At the edges
start both relays in one corner

Relay 2 first serves four sensors, three of them far away, so $J=85$ after the first E step.

E step 3 no change

The assignment repeats E step 2, so $J$ stays at $4$ and the run stops.

10.2K-medoids: any dissimilarity, and prototypes that are data points

Swaps the squared distance for any dissimilarity $V$ and makes each prototype one of its cluster's own points.

The mean is the right prototype only for squared Euclidean distance; other ways of measuring difference need another M step.

MethodK-medoids clustering
Conditions
  • a dissimilarity $V(x_i,\mu_k)\ge0$ chosen for the data

  • Manhattan: $V(x_i,\mu_k)=\sum_{j=1}^p\lvert x_{ij}-\mu_{kj}\rvert$

  • cosine: $V(x_i,\mu_k)=1-x_i^T\mu_k\big/\sqrt{(x_i^Tx_i)(\mu_k^T\mu_k)}$

  • $N_k$ is the set of points in cluster $k$, and $\mu_k$ must be one of them

$$\boxed{\begin{aligned}&\tilde J=\sum_{i=1}^n\sum_{k=1}^K r_{ik}\,V(x_i,\mu_k)\\[3pt] &\text{E: }k_i^*=\arg\min_jV(x_i,\mu_j)\\ &\phantom{\text{E: }}r_{ik}=1\text{ if }k=k_i^*\text{, else }0\\[3pt] &\text{M: }\mu_k=\arg\min_{m\in N_k}\\ &\qquad\qquad\textstyle\sum_{x_i\in N_k}V(x_i,m)\end{aligned}}$$

The E step is the K-means E step with $V$ in place of the squared distance. The M step cannot average, so it tries every member of the cluster as the prototype and keeps the one whose total dissimilarity to the members is smallest.

Looks like this, but is not

K-medoids with $V(x,\mu)=\lVert x-\mu\rVert^2$ is just K-means.

The M step still has to pick a member. For the cluster $\{0,1,5\}$ on a line, K-means puts the prototype at the mean $2$, with total $14$; K-medoids must choose among $0$, $1$ and $5$, and picks $1$, with total $17$.

The medoid of a cluster with an outlier, under Manhattan distance

A cluster holds $(1,1)$, $(2,1)$, $(1,2)$, $(2,2)$ and $(9,9)$. Find its under the Manhattan distance and compare it with the mean. Then move the outlier to $(90,90)$ and repeat.

FindThe medoid and the mean, before and after the outlier moves.
Given
  • members: $(1,1),\ \allowbreak (2,1),\ \allowbreak (1,2),\ \allowbreak (2,2),\ \allowbreak (9,9)$

  • $V(x,m)=\lvert x_1-m_1\rvert+\lvert x_2-m_2\rvert$

Solution

With five members, trying each one as the prototype takes five sums, and that is all the M step of K-medoids does.

Total dissimilarity of each candidate

$$(1,1):\ 1+1+2+16=20$$

Distances to $(2,1)$, $(1,2)$, $(2,2)$ and $(9,9)$; the last one is $8+8$.

$$\begin{aligned}&(2,1):\ 1+2+1+15=19\\ &(1,2):\ 19\end{aligned}$$

The two are mirror images across the diagonal, so their totals agree.

$$\begin{aligned}&(2,2):\ 2+1+1+14=18\\ &(9,9):\ 16+15+15+14=60\end{aligned}$$

The outlier as prototype would be far from everyone.

Compare with the mean

$$\begin{aligned}&\text{medoid}=(2,2)\\ &\bar x=\tfrac15(15,\ 15)=(3,\ 3)\end{aligned}$$

The mean is pulled one unit toward the outlier on each axis, to a spot where no member is.

Move the outlier to (90, 90)

$$\text{each near total grows by }81+81=162$$

The distance from any of the four near members to the outlier grows by $162$, so their order does not change.

$$\begin{aligned}&\text{medoid}=(2,2)\\ &\bar x=(19.2,\ 19.2)\end{aligned}$$

The medoid stays; the mean follows the outlier.

Answer $$\boxed{\begin{aligned}&\text{medoid }(2,2)\\ &\bar x:\ (3,3)\to(19.2,\ 19.2)\end{aligned}}$$
Check

Direct recount after the move: $(2,2)$ has total $2+1+1+176=180$ and $(2,1)$ has $1+2+1+(88+89)=181$, so $(2,2)$ still wins.

A far outlier adds almost the same amount to every candidate's total, so it barely changes which member wins; the mean has no such protection.

Cosine dissimilarity: a short text joins the long article it resembles

Word counts for the words (goal, match, vote) describe a two-line text $x=(1,1,0)$. The prototypes are a long sports article $\mu_1=(30,40,0)$ and a short politics note $\mu_2=(0,1,2)$. Assign $x$ by squared Euclidean distance and by cosine dissimilarity.

FindThe cluster of $x$ under each dissimilarity.
Given
  • $x=(1,1,0)$, $\mu_1=(30,40,0)$, $\mu_2=(0,1,2)$

  • $V(x,\mu)=1-\dfrac{x^T\mu}{\sqrt{(x^Tx)(\mu^T\mu)}}$

Solution

The two measures disagree here, and computing both side by side shows why: one sees length, the other only direction.

Squared Euclidean distance

$$\begin{aligned}&{\lVert x-\mu_1\rVert}^2=29^2+39^2=2362\\ &{\lVert x-\mu_2\rVert}^2=1+0+4=5\end{aligned}$$

The long article is far away simply because it has many more words.

Cosine dissimilarity

$$V(x,\mu_1)=1-\frac{70}{\sqrt2\cdot50}=1-0.9899=0.0101$$

$x^T\mu_1=30+40=70$, $\lVert x\rVert=\sqrt2$ and $\lVert\mu_1\rVert=50$.

$$V(x,\mu_2)=1-\frac{1}{\sqrt2\cdot\sqrt5}=1-0.3162=0.6838$$

The two vectors share only the word match, counted once.

Answer $$\boxed{\begin{aligned}&\text{Euclidean: politics}\\ &\text{cosine: sports}\end{aligned}}$$
Check

Scale check: $V(10x,\mu_1)=V(x,\mu_1)$ because the factor $10$ cancels in the ratio, so a text ten times longer with the same word proportions lands in the same cluster.

Use the cosine when only the proportions of the features matter, as for word counts; use a distance when the size of the vector itself carries meaning.

Checkpoint
§10.2 — the K-medoids M step on a line

After an E step, one K-medoids cluster holds the readings $1,2,6,7,20$, and its prototype until now was $2$. The dissimilarity is $V(x,m)=\lvert x-m\rvert$.

Find(a) Which prototype does the M step choose?
Given
  • cluster members: $1,\ 2,\ 6,\ 7,\ 20$

  • current prototype: $2$

  • $V(x,m)=\lvert x-m\rvert$

Hint 1/4

The new prototype has to be one of the five readings; look for the one that is closest to all the others at once.

Hint 2/4

$\mu_k=\arg\min_{m\in N_k}\sum_{x_i\in N_k}\lvert x_i-m\rvert$.

Hint 3/4

Readings $1,2,6,7,20$. For $m=6$ the total is $5+4+0+1+14$; for $m=7$ it is $6+5+1+0+13$.

Hint 4/4

The totals are $31, 28, 24, 25, 64$, so the prototype is $6$.

Show solution

Five candidates, five sums: the M step compares them directly.

Totals

$$\begin{aligned}&1:\ 0+1+5+6+19=31\\ &2:\ 1+0+4+5+18=28\end{aligned}$$

Each candidate's distances to all five members, itself included as $0$.

$$\begin{aligned}&6:\ 5+4+0+1+14=24\\ &7:\ 6+5+1+0+13=25\\ &20:\ 64\end{aligned}$$

The two middle readings are the serious candidates.

Pick the smallest

$$\mu=6$$

$24$ is the smallest total.

Answer $$\boxed{\mu=6}$$
Check

On a line the sum of absolute distances is smallest at the median, and the median of $1,2,6,7,20$ is $6$, a member.

The old prototype plays no part in the M step; only the current members do.

⚠ Averaging in the K-medoids M step

the K-means M step is the familiar one

wrong$$\mu_k=\frac{1}{\lvert N_k\rvert}\sum_{x_i\in N_k}x_i$$
right$$\mu_k=\arg\min_{m\in N_k}\sum_{x_i\in N_k}V(x_i,m)$$
⚠ Squaring inside the Manhattan distance

the Euclidean formula is the habit

wrong$$V(x_i,\mu_k)=\sum_j(x_{ij}-\mu_{kj})^2$$
right$$V(x_i,\mu_k)=\sum_j\lvert x_{ij}-\mu_{kj}\rvert$$
⚠ Taking the cosine itself as the dissimilarity

the cosine is the familiar quantity, but it is large for similar vectors

wrong$$V=\frac{x^T\mu}{\lVert x\rVert\,{\lVert\mu\rVert}}$$
right$$V=1-\frac{x^T\mu}{\lVert x\rVert\,{\lVert\mu\rVert}}$$

10.3Compressing an image with K-means: K colors and one label per pixel

Stores $K$ colors once plus a short label per pixel: $24K+n\lceil\log_2K\rceil$ bits instead of $24n$.

K-means leaves behind $K$ prototypes and one cluster label per point; keeping only those is a compressed copy of the data.

RuleSize of an image compressed by K-means
Conditions
  • $n$ pixels, each an RGB triplet $x_i=(x_{i1},x_{i2},x_{i3})$ with $8$ bits per channel

  • K-means with $K$ clusters on the $n$ triplets; each pixel is replaced by its cluster's prototype, which segments the image into $K$ color regions

  • labels stored with a fixed-length binary code

$$\boxed{\begin{aligned}&\text{original: }24n\\ &\text{compressed:}\\ &\quad 24K+n\lceil\log_2K\rceil\end{aligned}}$$

Each of the $K$ prototype colors costs $24$ bits, once. Each pixel then stores only which of the $K$ colors it got, and a fixed-length code for $K$ labels needs $\lceil\log_2K\rceil$ bits. When $n$ is much larger than $K$ the ratio is close to $24/\lceil\log_2K\rceil$.

Looks like this, but is not

Three colors need $\log_23\approx1.58$ bits per pixel.

A fixed-length label per pixel uses whole bits: the labels $00,01,10$ need $\lceil\log_23\rceil=2$ bits, the same as for $K=4$, and the code $11$ goes unused. Codes that pack several pixels together get nearer to $1.58$; the scheme here does not.

Bits for a 320 by 200 image with 8 and with 9 colors

An RGB image of $320\times200$ pixels is compressed by K-means. Compare its size with $K=8$ and with $K=9$ against the original.

FindBoth compressed sizes and both compression ratios.
Given
  • $320\times200$ pixels, $8$ bits per channel, three channels

  • $K=8$ or $K=9$

Solution

We plug into the size formula; the only step that needs thought is the ceiling.

Count the pixels and the original

$$\begin{aligned}&n=320\cdot200=64{,}000\\ &24n=1{,}536{,}000\ \text{bits}\end{aligned}$$

Three channels of $8$ bits each for every pixel.

K = 8

$$24\cdot8+64{,}000\cdot\lceil\log_28\rceil=192+192{,}000=192{,}192$$

$\log_28=3$ exactly, so each pixel needs $3$ bits.

$$1{,}536{,}000/192{,}192=7.99$$

Almost $24/3=8$; the palette costs only $192$ bits.

K = 9

$$24\cdot9+64{,}000\cdot\lceil\log_29\rceil=216+256{,}000=256{,}216$$

$\log_29\approx3.17$ rounds up to $4$ bits per pixel.

$$1{,}536{,}000/256{,}216=5.99$$

One more color costs $64{,}024$ more bits.

Answer $$\boxed{\begin{aligned}K=8&:\ 192{,}192\ \text{bits}\\ K=9&:\ 256{,}216\ \text{bits}\end{aligned}}$$
Check

For large $n$ the ratio should be close to $24/\lceil\log_2K\rceil$: $24/3=8$ and $24/4=6$, and the exact ratios sit just below, because of the palette.

Choose $K$ as a power of two when you can: $K=9$ pays for $16$ labels and uses nine.

The squared error of the compressed pixels is J

Four pixels $(200,40,40)$, $(220,60,40)$, $(20,40,200)$ and $(40,40,220)$ are compressed with $K=2$; K-means groups the first two and the last two. Find the prototypes, the total squared color error of the compressed copy, and the bits against the original.

FindThe two prototype colors, the total squared error, and both bit counts.
Given
  • pixels $(200,40,40)$, $(220,60,40)$, $(20,40,200)$, $(40,40,220)$

  • clusters $\{1,2\}$ and $\{3,4\}$

Solution

Replacing each pixel by its prototype is exactly what $J$ measures, so the error we want is the distortion itself.

Prototypes

$$\begin{aligned}&\mu_1=(210,\ 50,\ 40)\\ &\mu_2=(30,\ 40,\ 210)\end{aligned}$$

The squared RGB distance splits into three channel terms, so the mean is taken channel by channel.

Squared error

$${\lVert(200,40,40)-\mu_1\rVert}^2=10^2+10^2+0^2=200$$

The same $200$ comes out for each of the four pixels.

$$J=4\times200=800$$

The total squared error of the copy is the K-means distortion.

Bits

$$24\cdot2+4\cdot\lceil\log_22\rceil=52\ \ \text{against}\ \ 24\cdot4=96$$

With only four pixels the palette is most of the cost.

Answer $$\boxed{\begin{aligned}&\mu_1=(210,50,40)\\ &\mu_2=(30,40,210)\\ &J=800;\ \ 52\text{ bits vs }96\end{aligned}}$$
Check

Pairwise check: pixels 1 and 2 differ by $(20,20,0)$, squared length $800$, and a pair adds half of that to $J$; pixels 3 and 4 add another $400$, so $J=800$. Per channel that is about $8.2$ levels out of $256$.

K-means suits compression because it minimizes exactly what the compressed image loses: the squared error of the replaced pixels.

Checkpoint
§10.3 — the size of a compressed image

An RGB image of $400\times300$ pixels, $8$ bits per channel, is compressed by K-means with $K=16$ and stored as the palette plus a fixed-length label per pixel.

Find(a) How many bits does the compressed image take?
Given
  • $400\times300$ pixels, $24$ bits per pixel in the original

  • $K=16$

Hint 1/4

Split the storage into two parts: the colors, stored once, and the labels, one per pixel.

Hint 2/4

$24K+n\lceil\log_2K\rceil$ bits.

Hint 3/4

Here $n=400\cdot300=120{,}000$, $K=16$ and $\log_216=4$.

Hint 4/4

$384+480{,}000=480{,}384$ bits.

Show solution

Size formula, with the ceiling done first.

Index bits

$$\lceil\log_216\rceil=4\ \Rightarrow\ 120{,}000\cdot4=480{,}000$$

Sixteen labels fit exactly in $4$ bits.

Palette

$$24\cdot16=384\ \Rightarrow\ 480{,}000+384=480{,}384$$

Each of the $16$ colors needs all three $8$-bit channels.

Answer $$\boxed{480{,}384\ \text{bits}}$$
Check

Ratio check: $24n=2{,}880{,}000$ and $2{,}880{,}000/480{,}384=5.995$, just under $24/4=6$.

Compute the index bits first; the palette is a small correction for any real image.

⚠ Using log2 K without rounding up

the formula looks finished before the ceiling

wrong$$n\log_2K$$
right$$n\lceil\log_2K\rceil$$
⚠ Forgetting the palette

the labels are the part that grows with the image

wrong$$n\lceil\log_2K\rceil$$
right$$24K+n\lceil\log_2K\rceil$$
⚠ Counting 8 bits per pixel for a color image

8 bits is the size of one channel

wrong$$8n$$
right$$24n$$

10.4EM on two coins: guess the hidden labels softly, then count

When the coin behind each run is hidden, split every run between the coins by its posterior, then re-estimate by counting.

K-means alternated a guess of the groups with a fit of the prototypes; EM does the same with probabilities in place of hard labels.

MethodEM for two coins with hidden labels
Conditions
  • run $i$ picks coin A or coin B with probability $1/2$ each, independently of the other runs, and flips it $F$ times

  • $x_i$: heads in run $i$; $z_i$: the coin used, not observed

  • current guesses $\theta_A^{(s)}$ and $\theta_B^{(s)}$

$$\boxed{\begin{aligned}a_i&=\theta_A^{x_i}(1-\theta_A)^{F-x_i}\\ b_i&=\theta_B^{x_i}(1-\theta_B)^{F-x_i}\\[3pt] \text{E: }\ \gamma_{iA}&=\frac{a_i}{a_i+b_i}\\[3pt] \text{M: }\ \theta_A^{(s+1)}&=\frac{\sum_i\gamma_{iA}\,x_i}{F\sum_i\gamma_{iA}}\\ \theta_B^{(s+1)}&=\frac{\sum_i(1-\gamma_{iA})\,x_i}{F\sum_i(1-\gamma_{iA})}\end{aligned}}$$

E step: with the current guesses, compute for each run the probability that coin A was used. M step: credit coin A with that share of the run's heads and flips, coin B with the rest, and divide heads by flips for each coin. With known coins every share is $0$ or $1$ and this is the ordinary estimate.

Where the two steps come from

E step. Bayes' rule gives $$\Pr(z_i=A\mid x_i)=\dfrac{\frac12\Pr(x_i\mid\theta_A)}{\frac12\Pr(x_i\mid\theta_A)+\frac12\Pr(x_i\mid\theta_B)}.$$ The factor $\binom{F}{x_i}$ sits in both binomial probabilities, so it cancels along with the $\tfrac12$.

M step. Weight each run's complete-data log-likelihood by its posterior and add: $\sum_i\gamma_{iA}\big[x_i\log\theta_A+(F-x_i)\log(1-\theta_A)\big]$, plus the same with $1-\gamma_{iA}$ for coin B. The lecture notes call this the expected likelihood.

Setting its derivative in $\theta_A$ to zero gives $\sum_i\gamma_{iA}x_i/\theta_A=\sum_i\gamma_{iA}(F-x_i)/(1-\theta_A)$, whose solution is the weighted fraction of heads in the box.

Looks like this, but is not

Skip the probabilities: give each run to the more likely coin and count, as K-means would.

That is a different algorithm. Here it jumps to $\theta_A=0.75$, $\theta_B=0.35$ and never moves, while EM keeps the run with $4$ heads split and ends at $0.7333$ and $0.3709$. The log-likelihood of the heads counts is $-8.0400$ at EM's answer and $-8.0649$ at the hard one.

runheadsratio a/bγ for AA: heads, tailsB: heads, tails

1

$8$

$11.3906$

$0.9193$

$7.3544,\ 1.8386$

$0.6456,\ 0.1614$

2

$3$

$0.1975$

$0.1649$

$0.4948,\ 1.1546$

$2.5052,\ 5.8454$

3

$7$

$5.0625$

$0.8351$

$5.8454,\ 2.5052$

$1.1546,\ 0.4948$

4

$4$

$0.4444$

$0.3077$

$1.2308,\ 1.8462$

$2.7692,\ 4.1538$

total

$22$

$14.9253,\ 7.3445$

$7.0747,\ 10.6555$

Coin A is credited with $14.9253$ heads out of $22.2699$ flips and coin B with $7.0747$ out of $17.7301$: those two fractions are the M step.

Two coins with known labels: the complete-data estimate

Four runs of $10$ flips each: coin A gave $8$ and $7$ heads, coin B gave $3$ and $4$. Estimate $\theta_A$ and $\theta_B$ by maximum likelihood.

Find$\hat\theta_A$ and $\hat\theta_B$.
Given
  • coin A: $8$ and $7$ heads; coin B: $3$ and $4$ heads

  • $F=10$ flips per run

Solution

With the coins known, the log-likelihood splits into one part per coin, and each part is maximized on its own.

Split by coin

$$\begin{aligned}&\log L=15\log\theta_A\\ &\quad+5\log(1-\theta_A)\\ &\quad+7\log\theta_B\\ &\quad+13\log(1-\theta_B)+c\end{aligned}$$

Coin A shows $15$ heads in $20$ flips, coin B $7$ in $20$; $c$ holds the binomial coefficients.

Maximize each part

$$\frac{15}{\theta_A}=\frac{5}{1-\theta_A}\ \Rightarrow\ \theta_A=0.75$$

The derivative of the first bracket is zero there.

$$\frac{7}{\theta_B}=\frac{13}{1-\theta_B}\ \Rightarrow\ \theta_B=0.35$$

The log-likelihood splits into a $\theta_A$ bracket and a $\theta_B$ bracket, so each coin is maximized on its own.

Answer $$\boxed{\begin{aligned}&\hat\theta_A=0.75\\ &\hat\theta_B=0.35\end{aligned}}$$
Check

Each estimate is its coin's fraction of heads, $15/20$ and $7/20$, the binomial estimate from the section on maximum likelihood.

With labels there is nothing to iterate: we count coin by coin.

One EM iteration for two coins whose labels were lost

The same four runs, with $8,3,7,4$ heads out of $10$, but nobody recorded the coins. Each run used A or B with probability $1/2$. Start from $\theta_A^{(0)}=0.6$, $\theta_B^{(0)}=0.4$ and do one EM iteration.

FindThe posteriors $\gamma_{iA}$ and the new estimates $\theta_A^{(1)},\theta_B^{(1)}$.
Given
  • heads $x_i$: $8,\ 3,\ 7,\ 4$ out of $F=10$

  • $\Pr(z_i=A)=\Pr(z_i=B)=1/2$

  • $\theta_A^{(0)}=0.6$, $\theta_B^{(0)}=0.4$

Solution

Because $\theta_A^{(0)}=1-\theta_B^{(0)}$, the likelihood ratio collapses to a power of $1.5$, so each posterior takes one line.

E step: the posterior of coin A

$$\begin{aligned}\frac{a_i}{b_i}&=\Big(\frac{0.6}{0.4}\Big)^{x_i}\Big(\frac{0.4}{0.6}\Big)^{10-x_i}\\ &=1.5^{\,2x_i-10}\end{aligned}$$

The binomial coefficient and the prior $1/2$ cancel in the ratio.

$$\begin{aligned}&\gamma_{iA}=\frac{1.5^{2x_i-10}}{1+1.5^{2x_i-10}}\\ &0.9193,\ 0.1649,\ 0.8351,\ 0.3077\end{aligned}$$

For $x=8,3,7,4$ the ratio is $11.39$, $0.1975$, $5.0625$ and $0.4444$.

Split the heads and the flips

$$\begin{aligned}H_A&=8(0.9193)+3(0.1649)\\ &\quad+7(0.8351)+4(0.3077)\\ &=14.9253\end{aligned}$$

Coin A is credited with its posterior share of every run's heads.

$$F_A=10\,(0.9193+0.1649+0.8351+0.3077)=22.2699$$

It gets the same share of every run's $10$ flips.

$$\begin{aligned}&H_B=22-14.9253=7.0747\\ &F_B=40-22.2699=17.7301\end{aligned}$$

Coin B gets the rest of the $22$ heads and $40$ flips.

M step

$$\begin{aligned}&\theta_A^{(1)}=\frac{14.9253}{22.2699}=0.6702\\ &\theta_B^{(1)}=\frac{7.0747}{17.7301}=0.3990\end{aligned}$$

Heads over flips for each coin, as with known coins but with fractional counts.

Answer $$\boxed{\theta_A^{(1)}=0.6702,\quad \theta_B^{(1)}=0.3990}$$
Check

The log-likelihood of the heads counts, $\sum_i\log\big[\tfrac12\Pr(x_i\mid\theta_A)+\tfrac12\Pr(x_i\mid\theta_B)\big]$, rises from $-8.5300$ at the start to $-8.1784$.

Continuing, EM settles within $10$ iterations at $\theta_A=0.7333$, $\theta_B=0.3709$, with $l=-8.0400$.

Each EM iteration is the known-coin estimate with fractional counts; the posteriors decide the fractions.

Checkpoint
§10.4 — the E step for one run of flips

Coin A lands heads with probability $0.8$ and coin B with probability $0.5$; a run picks one of them with probability $1/2$ each. One run of $10$ flips shows $6$ heads.

Find(a) What is $\Pr(z=A\mid 6\text{ heads})$?
Given
  • $\theta_A=0.8$, $\theta_B=0.5$

  • $\Pr(z=A)=\Pr(z=B)=1/2$

  • $6$ heads in $F=10$ flips

Hint 1/4

Compare how well each coin explains six heads and four tails, then weigh by the equal priors.

Hint 2/4

$\gamma_A=\dfrac{a}{a+b}$ with $a=\theta_A^x(1-\theta_A)^{F-x}$ and $b=\theta_B^x(1-\theta_B)^{F-x}$.

Hint 3/4

Here $x=6$, $F=10$: $a/b=(0.8/0.5)^6\,(0.2/0.5)^4$.

Hint 4/4

$a/b=0.4295$, so $\gamma_A=0.4295/1.4295=0.30$.

Show solution

The likelihood ratio is the fastest route: every common factor cancels in it.

Likelihood ratio

$$\begin{aligned}\frac{a}{b}&=\Big(\frac{0.8}{0.5}\Big)^6\Big(\frac{0.2}{0.5}\Big)^4\\ &=16.777\times0.0256=0.4295\end{aligned}$$

Heads favor A, but four tails favor B much more strongly.

Posterior

$$\gamma_A=\frac{0.4295}{1+0.4295}=0.3005$$

Equal priors cancel and the two posteriors add to $1$, so $\gamma_A=r/(1+r)$ with $r=a/b$.

Answer $$\boxed{\gamma_A=0.30}$$
Check

Direct check with the binomial probabilities: $\Pr(6\mid0.8)=0.0881$ and $\Pr(6\mid0.5)=0.2051$, and $0.0881/(0.0881+0.2051)=0.3005$.

Six heads in ten sounds like the heads-heavy coin, but the tails decide: always keep both factors.

⚠ Forgetting to normalize the posterior

the unnormalized product already looks like a probability

wrong$$\gamma_{iA}=\theta_A^{x_i}{(1-\theta_A)}^{F-x_i}$$
right$$\gamma_{iA}=\frac{a_i}{a_i+b_i}$$
⚠ Dividing coin A's heads by all the flips

each run has F flips, so the total number of flips looks like the right denominator

wrong$$\theta_A=\frac{\sum_i\gamma_{iA}x_i}{F\cdot(\text{number of runs})}$$
right$$\theta_A=\frac{\sum_i\gamma_{iA}x_i}{F\sum_i\gamma_{iA}}$$
⚠ Dropping the tails factor

the heads are what the question counts

wrong$$a_i=\theta_A^{x_i}$$
right$$a_i=\theta_A^{x_i}{(1-\theta_A)}^{F-x_i}$$

10.5A mixture of Gaussians: pick a hidden component, then draw from its Gaussian

Models data from several hidden sources as a weighted sum of Gaussian densities; the weights are the sources' shares.

The coins had a hidden label and a known distribution for each label; replace the binomial by a Gaussian and two coins by $K$ components.

DefinitionMixture of Gaussians, with its latent variable
Conditions
  • $K$ components with means $\mu_j$ and covariance matrices $\Sigma_j$

  • mixing coefficients $0\le\pi_j\le1$ with $\sum_{j=1}^K\pi_j=1$

  • $z=(z_1,\dots,z_K)$ with $z_j\in\{0,1\}$ and $\sum_jz_j=1$: a one-hot label

$$\boxed{\begin{aligned}&\textcolor{#8250df}{p(x)}=\sum_{j=1}^K\pi_j\,\mathcal N(x\mid\mu_j,\Sigma_j)\\[3pt] &p(z_j=1)=\pi_j\\ &p(z)=\textstyle\prod_j\pi_j^{z_j}\\[3pt] &p(x\mid z_j=1)=\mathcal N(x\mid\mu_j,\Sigma_j)\\[3pt] &l(\pi,\mu,\Sigma)=\textstyle\sum_{i=1}^n\log p(x_i)\end{aligned}}$$

To draw one point, pick component $j$ with probability $\pi_j$, then draw $x$ from that Gaussian. Summing out the hidden choice gives the mixture density. Each term of the log-likelihood is $\log\sum_j\pi_j\mathcal N(x_i\mid\mu_j,\Sigma_j)$, a sum inside a logarithm, which is why no formula maximizes it in one step.

Why p(x) is a density, and where it comes from

$p(x)\ge0$, and $\int p(x)\,dx=\sum_j\pi_j\int\mathcal N(x\mid\mu_j,\Sigma_j)\,dx=\sum_j\pi_j=1$.

By the law of total probability over the $K$ possible values of $z$, $p(x)=\sum_zp(z)\,p(x\mid z)$; the $z$ with $z_j=1$ contributes $\pi_j\,\mathcal N(x\mid\mu_j,\Sigma_j)$.

Written with exponents, $p(x\mid z)=\prod_j\mathcal N(x\mid\mu_j,\Sigma_j)^{z_j}$: only the factor with $z_j=1$ is not raised to the power $0$.

Looks like this, but is not

The mixture of $\mathcal N(500,4)$ and $\mathcal N(510,4)$ with weights $0.6$ and $0.4$ is the distribution of $0.6X_1+0.4X_2$, for independent $X_1\sim\mathcal N(500,4)$ and $X_2\sim\mathcal N(510,4)$.

A weighted sum of independent Gaussians is again one Gaussian, here $\mathcal N(504,\ 2.08)$, with a single hump at $504$. The mixture does not add the two variables; it picks one of them, which is how it gets two humps.

weight x (g)mixture p(x)one Gaussian N(x | 504, 28)

$496$

$0.0162$

$0.0240$

$500$

$0.1197$

$0.0567$

$504$

$0.0171$

$0.0754$

$506$

$0.0121$

$0.0702$

$510$

$0.0798$

$0.0396$

$514$

$0.0108$

$0.0126$

The single Gaussian gives $0.0754$ at $504$, over four times the mixture's $0.0171$, and less than half the mixture's value at $500$.

Mean and variance of the bag-weight mixture

Bags come from machine 1 with probability $0.6$, weights $\mathcal N(500,4)$, and from machine 2 with probability $0.4$, weights $\mathcal N(510,4)$, in grams. Find the mean and the variance of a random bag's weight, and the single Gaussian with the same two numbers.

Find$E[X]$, $\operatorname{Var}X$, and the matching single Gaussian.
Given
  • $\pi_1=0.6$, $\mu_1=500$, $\sigma_1^2=4$

  • $\pi_2=0.4$, $\mu_2=510$, $\sigma_2^2=4$

Solution

Condition on the hidden machine: each conditional moment is known, and the law of total expectation combines them.

Mean

$$E[X]=0.6\cdot500+0.4\cdot510=504$$

Law of total expectation over the machine.

Second moment

$$\begin{aligned}&E[X^2]=0.6\,(4+500^2)\\ &\qquad+0.4\,(4+510^2)\\ &\quad=254{,}044\end{aligned}$$

For each machine $E[X^2\mid j]=\sigma_j^2+\mu_j^2$.

Variance

$$\operatorname{Var}X=254{,}044-504^2=28$$

Only $4$ of it is spread inside a machine; the other $24$ is the gap between the machines.

Answer $$\boxed{\begin{aligned}&E[X]=504\\ &\operatorname{Var}X=28\end{aligned}}$$
Check

Split check: $\sum_j\pi_j\sigma_j^2+\sum_j\pi_j(\mu_j-504)^2=4+(0.6\cdot16+0.4\cdot36)=4+24=28$.

Matching the mean and variance gives $\mathcal N(504,28)$, one wide hump centered in the valley between the machines; the mixture keeps the two humps.

How many numbers a Gaussian mixture needs

Count the free parameters of a mixture of $K$ Gaussians in $p$ dimensions with full covariance matrices. Evaluate the count for $K=3$, $p=2$ and for $K=3$, $p=10$.

FindThe number of free parameters, in general and in the two cases.
Given$K$ components, each with $\pi_j$, $\mu_j\in\mathbb R^p$ and a $p\times p$ covariance $\Sigma_j$
Solution

Count per component, then subtract one for the constraint on the weights.

Weights

$$K-1$$

The $K$ weights add to $1$, so the last one follows from the others.

Means

$$Kp$$

Each component has its own mean, a free vector of $p$ numbers.

Covariances

$$K\,\tfrac{p(p+1)}{2}$$

A covariance matrix is symmetric, so only the diagonal and one triangle are free.

Totals

$$K=3,\ p=2:\ \ 2+6+9=17$$

Weights, means and covariances are chosen independently, so their counts add: $K-1=2$, $Kp=6$, $K\cdot3=9$.

$$K=3,\ p=10:\ \ 2+30+165=197$$

The covariances take most of the count as $p$ grows.

Answer $$\boxed{(K-1)+Kp+K\,\tfrac{p(p+1)}{2}}$$
Check

Edge check $K=1$, $p=2$: $0+2+3=5$, one mean and one $2\times2$ covariance with three free entries, as for a single Gaussian.

In high dimensions the covariances dominate the count; with diagonal covariances the last term drops to $Kp$.

Checkpoint
§10.5 — a mixture density at one point

A mixture of two one-dimensional Gaussians has $p(x)=0.25\,\mathcal N(x\mid0,1)+0.75\,\mathcal N(x\mid2,1)$. We need its value at $x=0$.

Find(a) What is $p(0)$?
Given
  • $p(x)=0.25\,\mathcal N(x\mid0,1)+0.75\,\mathcal N(x\mid2,1)$

  • $\mathcal N(x\mid\mu,\sigma^2)=\dfrac{1}{\sqrt{2\pi\sigma^2}}e^{-(x-\mu)^2/(2\sigma^2)}$

Hint 1/4

Each component contributes its own density at $0$, scaled by how often it is chosen.

Hint 2/4

$p(x)=\sum_j\pi_j\,\mathcal N(x\mid\mu_j,\sigma_j^2)$.

Hint 3/4

At $x=0$: $\mathcal N(0\mid0,1)=0.3989$ and $\mathcal N(0\mid2,1)=0.0540$, with weights $0.25$ and $0.75$.

Hint 4/4

$p(0)=0.0997+0.0405=0.140$.

Show solution

Evaluate each component at the point, weight it, and add.

Component densities

$$\begin{aligned}&\mathcal N(0\mid0,1)=\frac{1}{\sqrt{2\pi}}=0.3989\\ &\mathcal N(0\mid2,1)=\frac{e^{-2}}{\sqrt{2\pi}}=0.0540\end{aligned}$$

The second component is two standard deviations away.

Weighted sum

$$\begin{aligned}&p(0)=0.25(0.3989)\\ &\qquad+0.75(0.0540)\\ &\quad=0.0997+0.0405=0.1402\end{aligned}$$

Each density enters with its mixing coefficient.

Answer $$\boxed{p(0)=0.140}$$
Check

Size check: $p(0)$ must lie between the smaller and the larger density, $0.054$ and $0.399$, since it is a weighted average of them; $0.140$ does.

A mixture density at a point is a weighted average of the component densities there.

⚠ Reading a mixture as a sum of variables

the weights look like coefficients of a linear combination

wrong$$X=0.6X_1+0.4X_2$$
right$$X=X_j\ \text{with probability }\pi_j$$
⚠ Taking the logarithm inside the sum

the log of a product splits, and the habit carries over

wrong$$\log\sum_j\pi_j\mathcal N_j(x)=\sum_j\pi_j\log\mathcal N_j(x)$$
right$$\log\sum_j\pi_j\mathcal N_j(x)\ \text{does not split}$$
⚠ Weights that do not add up to one

each weight looks reasonable on its own

wrong$$\pi=(0.5,\ 0.3,\ 0.3)$$
right$$\textstyle\sum_j\pi_j=1,\ \text{e.g. }\pi=(0.5,\ 0.3,\ 0.2)$$

10.6Responsibilities: the probability that component j produced x

Bayes' rule with prior $\pi_j$ turns each point into $K$ probabilities, one per component: a soft version of the K-means assignment.

The mixture says how a point is generated from a hidden $z$; we need the reverse: given $x$, how probable is each value of $z$?

DefinitionResponsibility of component j for a point x
Conditions
  • parameters $\pi_j,\mu_j,\Sigma_j$ known, or the current guesses

  • for the data point $x_i$ we write $\gamma(z_{ij})$

$$\boxed{\begin{aligned}\gamma(z_j)&=p(z_j=1\mid x)\\[3pt] &=\frac{\pi_j\,\mathcal N(x\mid\mu_j,\Sigma_j)}{\sum_k\pi_k\,\mathcal N(x\mid\mu_k,\Sigma_k)}\end{aligned}}$$

The share of component $j$ times its density at $x$, divided by the same product summed over all components. $\pi_j$ is the probability of component $j$ before seeing $x$, and $\gamma(z_j)$ is the probability after seeing it. The $K$ responsibilities of a point add up to $1$.

Bayes' rule, and what it does to the likelihood equations

Bayes' rule: $p(z_j=1\mid x)=p(z_j=1)\,p(x\mid z_j=1)/p(x)$, with $p(z_j=1)=\pi_j$, $p(x\mid z_j=1)=\mathcal N(x\mid\mu_j,\Sigma_j)$ and $p(x)$ the mixture.

Differentiating $l$ in $\mu_j$ produces the responsibilities by themselves: $\nabla_{\mu_j}l=\sum_i\gamma(z_{ij})\,\Sigma_j^{-1}(x_i-\mu_j)$.

Setting it to zero gives $\mu_j=\sum_i\gamma(z_{ij})x_i\big/\sum_i\gamma(z_{ij})$, a weighted mean. But the weights depend on $\mu_j$, so this is an equation, not a formula; the next block turns it into an iteration.

Looks like this, but is not

$\gamma(z_{i1})=0.7$ says component 1 produced $7$ out of every $10$ points of the data.

That is $\pi_1$, one number for the whole data. $\gamma(z_{i1})$ belongs to one point: among many points with this same value, about $7$ in $10$ came from component 1. Averaging $\gamma(z_{i1})$ over all points estimates $\pi_1$.

Which machine filled the 506 g bag?

Machine 1 fills $60$ of every $100$ bags, with weights $\mathcal N(500,4)$; machine 2 fills the other $40$, with weights $\mathcal N(510,4)$, in grams. Find the responsibilities of both machines for a $506$ g bag and for a $505$ g bag.

Find$\gamma_1$ and $\gamma_2$ for each bag.
Given
  • $\pi_1=0.6$, $\mathcal N(500,4)$; $\pi_2=0.4$, $\mathcal N(510,4)$

  • bags of $506$ g and $505$ g

Solution

Both machines have the variance $4$, so the normalizing constants cancel and only the exponents and the shares matter.

The two products at 506 g

$$\begin{aligned}&\pi_1\mathcal N(506\mid500,4)\\ &\quad=0.6\cdot\frac{e^{-36/8}}{\sqrt{8\pi}}\\ &\quad=0.6\cdot0.00222=0.00133\end{aligned}$$

$506$ g is $6$ g, three standard deviations, above machine 1's mean.

$$\begin{aligned}&\pi_2\mathcal N(506\mid510,4)\\ &\quad=0.4\cdot\frac{e^{-16/8}}{\sqrt{8\pi}}\\ &\quad=0.4\cdot0.02700=0.01080\end{aligned}$$

It is only $4$ g, two standard deviations, below machine 2's mean.

Normalize

$$\begin{aligned}&\gamma_2=\frac{0.01080}{0.00133+0.01080}\\ &\quad=0.890\\ &\gamma_1=0.110\end{aligned}$$

Divide each product by their sum; the two responsibilities add up to $1$.

The midpoint 505 g

$$\begin{aligned}&\mathcal N(505\mid500,4)\\ &\quad=\mathcal N(505\mid510,4)\\ &\Rightarrow\ \gamma_1=\frac{0.6}{0.6+0.4}=0.6\end{aligned}$$

Equal distances and equal variances make the densities equal, so only the shares are left.

Answer $$\boxed{\begin{aligned}506\text{ g}&:\ \gamma_2=0.89\\ 505\text{ g}&:\ \gamma_1=0.6\end{aligned}}$$
Check

Log-odds route: $\log\frac{\gamma_2}{\gamma_1}=\log\frac{0.4}{0.6}+\frac{36-16}{8}=-0.405+2.5=2.095$, and $1/(1+e^{-2.095})=0.890$.

This answers the opening question: out of $100$ bags that weigh $506$ g, about $89$ come from machine 2. Near the middle, where the densities are close, the shares decide.

Two equally distant means, unequal responsibilities

Two components in the plane have $\pi_1=\pi_2=0.5$, $\mu_1=(0,0)$ with $\Sigma_1=I$, and $\mu_2=(4,0)$ with $\Sigma_2=4I$. Find the responsibilities for $x=(2,1)$, which is $\sqrt5$ from both means.

Find$\gamma(z_1)$ and $\gamma(z_2)$.
Given
  • $\pi_1=\pi_2=0.5$

  • $\mu_1=(0,0)$, $\Sigma_1=I$; $\mu_2=(4,0)$, $\Sigma_2=4I$

  • $x=(2,1)$

Solution

We evaluate each density from the multivariate formula, because the determinant $\lvert\Sigma_j\rvert$ differs between the two components and does not cancel.

Component 1

$$\mathcal N(x\mid\mu_1,I)=\frac{e^{-5/2}}{2\pi}=0.01306$$

$(x-\mu_1)^T(x-\mu_1)=4+1=5$ and $(2\pi)^{p/2}\lvert\Sigma_1\rvert^{1/2}=2\pi$ for $p=2$.

Component 2

$$\mathcal N(x\mid\mu_2,4I)=\frac{e^{-5/8}}{2\pi\cdot4}=0.02130$$

$\Sigma_2^{-1}=\tfrac14I$ gives the quadratic form $5/4$, and $\lvert\Sigma_2\rvert^{1/2}=4$.

Normalize

$$\begin{aligned}&0.5\cdot0.02130=0.01065\\ &0.5\cdot0.01306=0.00653\\ &\gamma(z_2)=\frac{0.01065}{0.01718}=0.620\end{aligned}$$

The equal shares cancel.

Answer $$\boxed{\begin{aligned}\gamma(z_1)&=0.380\\ \gamma(z_2)&=0.620\end{aligned}}$$
Check

Log-ratio route: $\log\frac{\mathcal N_2}{\mathcal N_1}=-\frac58+\frac52-\log4=0.4887$, and $1/(1+e^{-0.4887})=0.620$.

At equal distance the wider component wins: a spread-out Gaussian explains a far point better than a tight one does.

Checkpoint
§10.6 — one responsibility in one dimension

A two-component mixture on a line has $\pi_1=\pi_2=0.5$, means $\mu_1=0$ and $\mu_2=2$, and variances $\sigma_1^2=\sigma_2^2=1$. A point sits at $x=1.5$.

Find(a) What is the responsibility $\gamma(z_2)$ of component 2 for this point?
Given
  • $\pi=(0.5,\ 0.5)$, $\mu=(0,\ 2)$, $\sigma^2=(1,\ 1)$

  • $x=1.5$

Hint 1/4

Compare how well each component explains $x=1.5$, then turn the comparison into a probability.

Hint 2/4

$$\gamma(z_2)=\dfrac{\pi_2\mathcal N(x\mid\mu_2,\sigma_2^2)}{\sum_{k=1}^2\pi_k\mathcal N(x\mid\mu_k,\sigma_k^2)}$$

Hint 3/4

With $\pi=(0.5,0.5)$, $\mu=(0,2)$, $\sigma^2=(1,1)$ and $x=1.5$: the log-odds of component 2 is $(1.5^2-0.5^2)/2$.

Hint 4/4

The log-odds is $1$, so $\gamma(z_2)=1/(1+e^{-1})=0.73$.

Show solution

Equal shares and variances cancel, so the log-odds is a difference of two squared distances.

Log-odds

$$\log\frac{\mathcal N(1.5\mid2,1)}{\mathcal N(1.5\mid0,1)}=\frac{1.5^2-0.5^2}{2}=1$$

Equal shares and equal variances make the prefactors identical, so they cancel and only the exponents are left.

Responsibility

$$\gamma(z_2)=\frac{1}{1+e^{-1}}=0.731$$

With two components $\gamma=r/(1+r)$ for the odds $r=e^{1}$, which is the logistic function of the log-odds.

Answer $$\boxed{\gamma(z_2)=0.731}$$
Check

Direct values: $\mathcal N(1.5\mid2,1)=0.3521$ and $\mathcal N(1.5\mid0,1)=0.1295$, and $0.3521/(0.3521+0.1295)=0.731$.

With equal shares and variances the responsibility depends only on the two squared distances.

⚠ Dropping the shares from the responsibility

the densities alone look like the whole story

wrong$$\gamma(z_j)=\frac{\mathcal N_j(x)}{\sum_k\mathcal N_k(x)}$$
right$$\gamma(z_j)=\frac{\pi_j\mathcal N_j(x)}{\sum_k\pi_k\mathcal N_k(x)}$$
⚠ Normalizing over the points instead of the components

a table of products has two directions to sum in

wrong$$\gamma(z_{ij})=\frac{\pi_j\mathcal N_j(x_i)}{\sum_{i'}\pi_j\mathcal N_j(x_{i'})}$$
right$$\gamma(z_{ij})=\frac{\pi_j\mathcal N_j(x_i)}{\sum_k\pi_k\mathcal N_k(x_i)}$$
⚠ Giving the point to the nearest mean

that is what K-means does

wrong$$\gamma(z_j)=1\ \text{for the nearest }\mu_j$$
right$$\gamma(z_j)\ \text{also depends on }\pi_j\text{ and }\Sigma_j$$

10.7EM for a Gaussian mixture: responsibilities, then weighted means, covariances and shares

Alternates responsibilities with refitting each Gaussian to the points weighted by them; the log-likelihood never goes down.

The likelihood equations said $\mu_j$ is the $\gamma$-weighted mean, but $\gamma$ depends on $\mu_j$. EM breaks the circle the way K-means did: fix one, solve for the other.

MethodThe EM algorithm for a mixture of Gaussians
Conditions
  • data $\{x_i\}_{i=1}^n$ and a number of components $K$

  • a start for every $\pi_j,\mu_j,\Sigma_j$, for example from a K-means run

  • every $\Sigma_j$ stays invertible during the run

$$\boxed{\begin{aligned}&\text{E step:}\\ &\gamma(z_{ij})=\\ &\frac{\pi_j\mathcal N(x_i\mid\mu_j,\Sigma_j)}{\sum_k\pi_k\mathcal N(x_i\mid\mu_k,\Sigma_k)}\\[4pt] &\text{M step:}\\ &N_j=\textstyle\sum_i\gamma(z_{ij})\\[3pt] &\pi_j^{\text{new}}=\dfrac{N_j}{n}\\[3pt] &\mu_j^{\text{new}}=\dfrac{1}{N_j}\textstyle\sum_i\gamma(z_{ij})\,x_i\\[3pt] &\Sigma_j^{\text{new}}=\dfrac{1}{N_j}\textstyle\sum_i\gamma(z_{ij})\\ &\quad\times(x_i-\mu_j^{\text{new}})(x_i-\mu_j^{\text{new}})^T\end{aligned}}$$

E step: hold the parameters and compute every point's responsibilities. M step: hold the responsibilities and refit each component as if its data were the points weighted by $\gamma$: a weighted mean, a weighted covariance around the new mean, and a share equal to its effective number of points $N_j$ over $n$. Repeat until $l$ stops changing.

Where the M step comes from

Means. With the $\gamma(z_{ij})$ held fixed, $\nabla_{\mu_j}l=\sum_i\gamma(z_{ij})\,\Sigma_j^{-1}(x_i-\mu_j)=0$ gives $\mu_j^{\text{new}}$. The covariance follows the same way, around the new mean.

Shares. Maximize $l+\lambda\big(\sum_k\pi_k-1\big)$. The derivative in $\pi_j$ is $\sum_i\mathcal N(x_i\mid\mu_j,\Sigma_j)/p(x_i)+\lambda=0$; multiplying by $\pi_j$ turns it into $N_j+\lambda\pi_j=0$.

Summing over $j$ gives $n+\lambda=0$, so $\lambda=-n$ and $\pi_j^{\text{new}}=N_j/n$.

Never downhill. An EM iteration cannot lower $l$. This is a general property of EM whose proof uses Jensen's inequality (further reading); every worked iteration here checks it with numbers.

Looks like this, but is not

The larger the log-likelihood, the better the mixture, so EM should push $l$ as high as it can go.

Put $\mu_2$ on one data point and shrink $\sigma_2$: that point's density grows without limit, so $l\to\infty$ while component 2 describes a single number. These are further reading; in practice one restarts EM or keeps every variance above a small floor.

One full EM iteration on five points

Fit $K=2$ Gaussians to the numbers $1,3,4,8,9$, starting from $\pi=(0.5,0.5)$, $\mu=(2,8)$ and $\sigma^2=(4,4)$. Carry out one E step and one M step, and compare the log-likelihood before and after.

Find$\gamma(z_{i1})$ for every point, then $N_j$, $\pi_j$, $\mu_j$, $\sigma_j^2$, and $l$ before and after.
Given
  • data: $1,\ 3,\ 4,\ 8,\ 9$

  • start: $\pi_1=\pi_2=0.5$, $\mu_1=2$, $\mu_2=8$, $\sigma_1^2=\sigma_2^2=4$

Solution

With equal shares and equal variances the E step reduces to a log-odds that is linear in $x$, which is quicker than evaluating ten densities.

E step through the log-odds

$$\log\frac{\pi_1\mathcal N(x\mid2,4)}{\pi_2\mathcal N(x\mid8,4)}=\frac{(x-8)^2-{(x-2)}^2}{8}=7.5-1.5x$$

Equal shares and equal variances cancel, leaving the exponents.

$$\begin{aligned}&\gamma(z_{i1})=\frac{1}{1+e^{-(7.5-1.5x_i)}}\\ &0.9975,\ 0.9526,\ 0.8176,\\ &0.0110,\ 0.0025\end{aligned}$$

The log-odds are $6,\ \allowbreak 3,\ \allowbreak 1.5,\ \allowbreak -4.5,\ \allowbreak -6$ for $x=1,3,4,8,9$; $\gamma(z_{i2})=1-\gamma(z_{i1})$.

Effective counts and shares

$$\begin{aligned}&N_1=2.7811\\ &N_2=5-N_1=2.2189\end{aligned}$$

Each point's two responsibilities add to $1$, so the counts add to $n=5$.

$$\begin{aligned}&\pi_1=\frac{2.7811}{5}=0.5562\\ &\pi_2=0.4438\end{aligned}$$

Component 1 now explains a little more than half the data, mostly through the point $4$.

Weighted means

$$\begin{aligned}\mu_1&=\tfrac{1}{2.7811}\big[0.9975(1)\\ &\quad+0.9526(3)+0.8176(4)\\ &\quad+0.0110(8)+0.0025(9)\big]\\ &=2.6017\end{aligned}$$

The point $4$ pulls $\mu_1$ up with weight $0.82$.

$$\begin{aligned}\mu_2&=\tfrac{1}{2.2189}\big[0.0025(1)\\ &\quad+0.0474(3)+0.1824(4)\\ &\quad+0.9890(8)+0.9975(9)\big]\\ &=8.0060\end{aligned}$$

Without the small shares of $3$ and $4$ it would be almost $8.5$, the mean of $8$ and $9$.

Weighted variances around the new means

$$\sigma_1^2=\frac{1}{N_1}\sum_i\gamma(z_{i1}){(x_i-2.6017)}^2=1.7008$$

The spread shrinks from $4$, because component 1 now sits on $1,3,4$.

$$\sigma_2^2=\frac{1}{N_2}\sum_i\gamma(z_{i2}){(x_i-8.0060)}^2=2.3539$$

Wider than component 1, because $3$ and $4$ still carry some weight here.

The log-likelihood

$$l:\ -12.1352\ \to\ -11.1747$$

$l=\sum_i\log p(x_i)$, evaluated with the old and then with the new parameters.

Answer $$\boxed{\begin{aligned}\pi&=(0.5562,\ 0.4438)\\ \mu&=(2.6017,\ 8.0060)\\ \sigma^2&=(1.7008,\ 2.3539)\\ l&=-11.1747\end{aligned}}$$
Check

Two independent checks: $N_1+N_2=5=n$, and $\pi_1\mu_1+\pi_2\mu_2=0.5562(2.6017)+0.4438(8.0060)=5.0$, the plain mean of the data, which every M step must reproduce.

Five log-odds, then two counts, two means and two variances: about $30$ multiplications.

One iteration moved the means from $(2,8)$ to $(2.60,\ 8.01)$ and cut both variances; the next iteration repeats the same five lines from the new values.

The covariance update in two dimensions

In an M step, component $j$ has responsibilities $1$, $0.5$ and $0.5$ for the points $(0,0)$, $(2,0)$ and $(2,2)$, and $0$ for every other point. Find $N_j$, $\mu_j$ and $\Sigma_j$.

Find$N_j$, $\mu_j^{\text{new}}$ and $\Sigma_j^{\text{new}}$.
Given
  • $x_1=(0,0)$, $x_2=(2,0)$, $x_3=(2,2)$

  • $\gamma(z_{1j})=1$, $\gamma(z_{2j})=\gamma(z_{3j})=0.5$

Solution

The mean comes first, because the covariance is centered on the new mean; then one outer product per point.

Count and mean

$$N_j=1+0.5+0.5=2$$

Points with zero responsibility add nothing.

$$\mu_j=\tfrac12\big[1(0,0)+0.5(2,0)+0.5(2,2)\big]=(1,\ 0.5)$$

The weighted mean, divided by $N_j$, not by the number of points.

Outer products around the new mean

$$(x_1-\mu_j){(x_1-\mu_j)}^T=\begin{pmatrix}1&0.5\\0.5&0.25\end{pmatrix}$$

$x_1-\mu_j=(-1,\ -0.5)$.

$$\begin{aligned}(x_2-\mu_j)(\cdot)^T&=\begin{pmatrix}1&-0.5\\-0.5&0.25\end{pmatrix}\\[3pt] (x_3-\mu_j)(\cdot)^T&=\begin{pmatrix}1&1.5\\1.5&2.25\end{pmatrix}\end{aligned}$$

$x_2-\mu_j=(1,\ -0.5)$ and $x_3-\mu_j=(1,\ 1.5)$.

Weight and divide

$$\begin{aligned}\Sigma_j=\tfrac12\Big[&1\cdot\begin{pmatrix}1&0.5\\0.5&0.25\end{pmatrix}\\ &+0.5\begin{pmatrix}1&-0.5\\-0.5&0.25\end{pmatrix}\\ &+0.5\begin{pmatrix}1&1.5\\1.5&2.25\end{pmatrix}\Big]\end{aligned}$$

Each outer product enters with its point's responsibility.

$$\Sigma_j=\tfrac12\begin{pmatrix}2&1\\1&1.5\end{pmatrix}=\begin{pmatrix}1&0.5\\0.5&0.75\end{pmatrix}$$

The covariance is a weighted average like the mean, so the divisor is the total weight $N_j=2$, not a count of points.

Answer $$\boxed{\begin{aligned}&N_j=2,\quad \mu_j=(1,\ 0.5)\\ &\Sigma_j=\begin{pmatrix}1&0.5\\0.5&0.75\end{pmatrix}\end{aligned}}$$
Check

Trace check: the trace of $\Sigma_j$ must equal the weighted mean squared distance to $\mu_j$, $\tfrac12\big[1(1.25)+0.5(1.25)+0.5(3.25)\big]=1.75$, and $1+0.75=1.75$. The determinant $0.75-0.25=0.5>0$, so $\Sigma_j$ is a valid covariance.

In several dimensions the M step is the same weighted average, applied to outer products.

Checkpoint
§10.7 — the M step from given responsibilities

An E step on the four numbers $0,2,4,10$ has given component 1 the responsibilities $1,\ 0.8,\ 0.4,\ 0$, in that order.

Find(a) What is $\mu_1^{\text{new}}$?
Given
  • data $x=(0,\ 2,\ 4,\ 10)$

  • $\gamma(z_{i1})=(1,\ 0.8,\ 0.4,\ 0)$

Hint 1/4

The new mean is an average in which each point counts as much as its responsibility.

Hint 2/4

$\mu_1^{\text{new}}=\sum_i\gamma(z_{i1})x_i\big/N_1$ with $N_1=\sum_i\gamma(z_{i1})$.

Hint 3/4

Here $x=(0,2,4,10)$ and $\gamma(z_{i1})=(1,0.8,0.4,0)$, so the weighted sum is $0+1.6+1.6+0$.

Hint 4/4

$N_1=2.2$ and $\mu_1^{\text{new}}=3.2/2.2=1.45$.

Show solution

The column sum $N_1$ is needed by both formulas, so it comes first.

Effective count

$$N_1=1+0.8+0.4+0=2.2$$

Each responsibility is the fraction of a point that component 1 owns, so their sum is its effective number of points.

Mean and share

$$\begin{aligned}\mu_1&=\tfrac{1}{2.2}\big[1(0)+0.8(2)\\ &\quad+0.4(4)+0(10)\big]\\ &=3.2/2.2=1.4545\end{aligned}$$

Divide the weighted sum by $N_1$, not by $n=4$.

$$\pi_1=\frac{2.2}{4}=0.55$$

A share is a fraction of all $n=4$ points, so here the divisor is $n$, not $N_1$.

Answer $$\boxed{\begin{aligned}&\mu_1^{\text{new}}=1.45\\ &\pi_1^{\text{new}}=0.55\end{aligned}}$$
Check

Range check: $\mu_1$ is a weighted average of $0,2,4$ with most weight on $0$ and $2$, so it must lie between $0$ and $4$ and nearer the low end; $1.45$ does.

A column sum first, then everything divides by it; only $\pi_j$ divides by $n$.

⚠ Dividing by n instead of N_j

the plain mean divides by the number of points

wrong$$\mu_j^{\text{new}}=\frac1n\sum_i\gamma(z_{ij})\,x_i$$
right$$\mu_j^{\text{new}}=\frac1{N_j}\sum_i\gamma(z_{ij})\,x_i$$
⚠ Centering the covariance on the old mean

the old mean is the one already on the page

wrong$$\Sigma_j^{\text{new}}=\tfrac1{N_j}\textstyle\sum_i\gamma(z_{ij})(x_i-\mu_j^{\text{old}}){(x_i-\mu_j^{\text{old}})}^T$$
right$$\Sigma_j^{\text{new}}=\tfrac1{N_j}\textstyle\sum_i\gamma(z_{ij})(x_i-\mu_j^{\text{new}}){(x_i-\mu_j^{\text{new}})}^T$$
⚠ Averaging the counts over K

the shares are one per component

wrong$$\pi_j^{\text{new}}=N_j/K$$
right$$\pi_j^{\text{new}}=N_j/n$$
49550050551051500.050.10.15bag weight x (g)densityiteration 7: l = −37.13π = (0.50, 0.50) μ = (499.9, 507.8) σ² = (3.9, 19.4)one bar per bag: its γ₁ (blue) and γ₂ (orange)

Step through EM on thirteen bag weights, from a poor start with both components near the middle. The curves are $\textcolor{#1f6feb}{\pi_1\mathcal N(x\mid\mu_1,\sigma_1^2)}$ and $\textcolor{#d1690a}{\pi_2\mathcal N(x\mid\mu_2,\sigma_2^2)}$, and each bar splits one bag between the machines. By iteration $18$ the means are $500.0$ and $510.0$ and the shares $8/13$ and $5/13$.

At the edges
iteration 0 l = −40.82

Both components are wide and overlap, so every bag is split between them.

iteration 18 l = −35.57

Each bag belongs almost entirely to one machine, and the shares are the counts $8$ and $5$ over $13$.

Running K-means by hand

A question gives points, $K$ and starting prototypes, and asks for the clusters, the prototypes or $J$ after some steps.

  1. Table

    One row per point, one column per prototype, holding squared distances.

  2. Assign

    Mark the smallest entry in each row; a point moves only to a strictly nearer prototype.

  3. Average

    Replace each prototype by the mean of its marked points, dividing by the cluster size.

  4. Score

    Add each point's squared distance to its own prototype: that is $J$.

  5. Stop

    Repeat until an E step marks the same entries as the one before.

Where it goes wrong
  • An empty cluster: keep its prototype where it was, and say so.

  • Distances instead of squared distances in $J$.

  • Moving a prototype before every point is assigned.

EM for hidden coins by hand

Runs of flips with an unknown coin each time; the question gives starting biases and asks for one or more EM iterations.

  1. Ratio

    For each run, $a_i/b_i=(\theta_A/\theta_B)^{x_i}\big((1-\theta_A)/(1-\theta_B)\big)^{F-x_i}$.

  2. Posterior

    $\gamma_{iA}=\dfrac{a_i/b_i}{1+a_i/b_i}$, and coin B gets $1-\gamma_{iA}$.

  3. Credit

    Coin A gets $\gamma_{iA}x_i$ heads and $\gamma_{iA}F$ flips from run $i$; coin B gets the rest.

  4. Divide

    Each coin's new $\theta$ is its credited heads over its credited flips.

  5. Check

    The credited heads add up to the total heads, and the log-likelihood went up.

Where it goes wrong
  • Unequal priors: multiply $a_i/b_i$ by $\Pr(A)/\Pr(B)$ before step 2.

  • Dividing coin A's heads by all the flips instead of its credited flips.

One EM iteration for a Gaussian mixture by hand

A question gives data, $K$ and starting $\pi$, $\mu$, $\sigma^2$, and asks for the responsibilities or the next parameters.

  1. Products

    For each point and component, $\pi_j\mathcal N(x_i\mid\mu_j,\sigma_j^2)$; with two components use the log-odds.

  2. Normalize

    Divide each row by its sum: a point's responsibilities add up to $1$.

  3. Count

    Column sums give $N_j$; check that they add up to $n$.

  4. Refit

    $\mu_j$ as the weighted mean, then $\sigma_j^2$ around the new $\mu_j$, both over $N_j$; $\pi_j=N_j/n$.

  5. Check

    $\sum_j\pi_j\mu_j$ equals the plain mean of the data, and $l$ did not go down.

Where it goes wrong
  • Leaving $\pi_j$ out of the products.

  • Normalizing down a column instead of across a row.

  • Using the old mean inside the variance.

K-means places a 505.1 g bag with machine 2

K-means has settled on the prototypes $500$ g and $510$ g. A bag weighs $505.1$ g. Which cluster does the E step give it?

FindThe cluster of the bag.
Given
  • prototypes $\mu_1=500$, $\mu_2=510$

  • bag $x=505.1$ g

Solution

K-means compares squared distances and nothing else.

Compare squared distances

$$\begin{aligned}&{(505.1-500)}^2=26.01\\ &{(505.1-510)}^2=24.01\end{aligned}$$

The bag is $0.1$ g nearer to $510$.

Answer $$\boxed{\text{cluster 2}}$$
Check

The K-means cut is the midpoint $505$, and $505.1$ lies above it.

A hard assignment flips at the midpoint, whatever the shares and the spreads.

EM's responsibilities for the same 505.1 g bag

The mixture has $\pi=(0.6,0.4)$, $\mu=(500,510)$ and $\sigma^2=(4,4)$. Find the responsibilities for $x=505.1$ g.

Find$\gamma_1$ and $\gamma_2$.
Given
  • $\pi=(0.6,\ 0.4)$, $\mu=(500,\ 510)$, $\sigma^2=(4,\ 4)$

  • bag $x=505.1$ g

Solution

With equal variances the log-odds is the log of the shares plus the difference of the squared distances over $2\sigma^2$.

Log-odds of machine 2

$$\begin{aligned}&\log\frac{\gamma_2}{\gamma_1}=\log\frac{0.4}{0.6}\\ &\qquad+\frac{26.01-24.01}{8}\\ &\quad=-0.4055+0.25\\ &\quad=-0.1555\end{aligned}$$

The distances favor machine 2 by $0.25$; the shares favor machine 1 by $0.41$.

Responsibilities

$$\begin{aligned}&\gamma_2=\frac{1}{1+e^{0.1555}}=0.461\\ &\gamma_1=0.539\end{aligned}$$

The log-odds is negative, so machine 1 is the likelier source.

Answer $$\boxed{\begin{aligned}&\gamma_1=0.539\\ &\gamma_2=0.461\end{aligned}}$$
Check

The two machines are equally likely at $505.16$ g, and $505.1$ lies just below it, on machine 1's side.

Near the cut the shares tip a balance that the distances leave almost even.

K-means asks only which prototype is nearer, so the $505.1$ g bag goes to machine 2; EM also weighs how common each machine is, and machine 1 comes out slightly more likely.

How to tell them apart

If a question gives shares and variances or covariances, it wants responsibilities; if it gives only prototypes, it wants the nearest one.

The new share of machine 1 after an E step

An E step on four bags of $499$, $502$, $507$ and $511$ g gave machine 1 the responsibilities $1.0000$, $0.9996$, $0.0100$ and $0.0000$. What share of the bags does the M step give machine 1?

Find$\pi_1^{\text{new}}$.
Given$\gamma(z_{i1})=1.0000,\ \allowbreak 0.9996,\ \allowbreak 0.0100,\ \allowbreak 0.0000$ for four bags
Solution

A share is the average responsibility over all points, so we add the column and divide by $n$.

Average the column

$$\begin{aligned}\pi_1^{\text{new}}&=\tfrac14\big(1.0000+0.9996\\ &\qquad+0.0100+0.0000\big)\\ &=0.5024\end{aligned}$$

One number for the whole data set.

Answer $$\boxed{\pi_1^{\text{new}}=0.50}$$
Check

Two of the four bags are clearly machine 1's and two clearly machine 2's, so a share near $0.5$ is what these data say.

A share describes the belt, not a bag.

The responsibility of machine 1 for one 503 g bag

With $\pi=(0.6,0.4)$, $\mu=(500,510)$ and $\sigma^2=(4,4)$, find the responsibility of machine 1 for a $503$ g bag.

Find$\gamma_1$ at $503$ g.
Given
  • $\pi=(0.6,\ 0.4)$, $\mu=(500,\ 510)$, $\sigma^2=(4,\ 4)$

  • bag $x=503$ g

Solution

The same log-odds route: equal variances leave the shares and the squared distances.

Log-odds of machine 1

$$\begin{aligned}\log\frac{\gamma_1}{\gamma_2}&=\log\frac{0.6}{0.4}+\frac{49-9}{8}\\ &=0.405+5=5.405\end{aligned}$$

The bag is $3$ g from machine 1's mean and $7$ g from machine 2's.

Responsibility

$$\gamma_1=\frac{1}{1+e^{-5.405}}=0.9955$$

Almost certainly machine 1.

Answer $$\boxed{\gamma_1=0.9955}$$
Check

Direct densities: $0.6\,\mathcal N(503\mid500,4)=0.03886$ and $0.4\,\mathcal N(503\mid510,4)=0.00017$, and $0.03886/0.03903=0.9955$.

A responsibility describes one bag, and it can be close to $1$ while the share is only $0.6$.

$\pi_1$ answers what share of all bags machine 1 fills; $\gamma(z_{i1})$ answers how likely it is that this one bag came from machine 1.

How to tell them apart

One number for the whole data set is a share $\pi_j$; one number per point is a responsibility. The M step links them: the new share is the average responsibility.

Scaffolding comes off
The common skeleton
  1. E step: for each point and component compute $\pi_j\mathcal N(x_i\mid\mu_j,\sigma_j^2)$, then divide each point's row by its sum to get $\gamma(z_{ij})$.

  2. Counts: $N_j=\sum_i\gamma(z_{ij})$, which must add up to $n$.

  3. Means: $\mu_j=\sum_i\gamma(z_{ij})x_i/N_j$.

  4. Variances: $\sigma_j^2=\sum_i\gamma(z_{ij})(x_i-\mu_j)^2/N_j$, around the new means.

  5. Shares: $\pi_j=N_j/n$; then check that $l$ went up.

1 · fully worked

One EM iteration on five numbers with unequal starting variances

Fit $K=2$ Gaussians to $1,2,4,7,8$, starting from $\pi=(0.5,0.5)$, $\mu=(1,5)$ and $\sigma^2=(1,4)$. Carry out one EM iteration.

FindThe responsibilities, then $N_j$, $\mu_j$, $\sigma_j^2$, $\pi_j$ and the change in $l$.
Given
  • data: $1,\ 2,\ 4,\ 7,\ 8$

  • start: $\pi=(0.5,\ 0.5)$, $\mu=(1,\ 5)$, $\sigma^2=(1,\ 4)$

Solution

The variances differ, so the normalizing constants do not cancel; we evaluate the ten products directly.

E step: products and responsibilities

$$\begin{aligned}x=1&:\ 0.1995,\ 0.0135\\ x=2&:\ 0.1210,\ 0.0324\end{aligned}$$

$\pi_1\mathcal N(x\mid1,1)$ and $\pi_2\mathcal N(x\mid5,4)$ for the two small points.

$$\begin{aligned}x=4&:\ 0.0022,\ 0.0880\\ x=7&:\ 0.0000,\ 0.0605\\ x=8&:\ 0.0000,\ 0.0324\end{aligned}$$

The three large points are far out in component 1's narrow tail.

$$\gamma(z_{i1})=0.9366,\ 0.7889,\ 0.0246,\ 0,\ 0$$

Bayes' rule: component 1's product over the total $p(x_i)$, the sum of both products in that row.

Counts and shares

$$\begin{aligned}&N_1=1.7501,\quad N_2=3.2499\\ &\pi=(0.3500,\ 0.6500)\end{aligned}$$

The wide component 2 takes $4$ as well as $7$ and $8$.

Means and variances

$$\begin{aligned}\mu_1&=\tfrac{1}{1.7501}\big[0.9366(1)\\ &\quad+0.7889(2)+0.0246(4)\big]\\ &=1.4929\end{aligned}$$

Terms with a zero responsibility drop out.

$$\begin{aligned}\mu_2&=\tfrac{1}{3.2499}\big[0.0634(1)\\ &\quad+0.2111(2)+0.9754(4)\\ &\quad+7+8\big]=5.9655\end{aligned}$$

Component 2 moves up toward $7$ and $8$.

$$\begin{aligned}&\sigma_1^2=0.3341\\ &\sigma_2^2=4.2648\end{aligned}$$

The maximizing mean does not depend on the variance, so the spreads are measured around the new means; the divisor is the total weight $N_j$.

Check the log-likelihood

$$l:\ -12.0624\ \to\ -10.7230$$

It went up, as every EM iteration must.

Answer $$\boxed{\begin{aligned}\pi&=(0.35,\ 0.65)\\ \mu&=(1.4929,\ 5.9655)\\ \sigma^2&=(0.3341,\ 4.2648)\end{aligned}}$$
Check

Mean check: $0.35(1.4929)+0.65(5.9655)=4.4$, the plain mean of $1,2,4,7,8$.

A narrow component gives up far points quickly; here component 1 kept only $1$ and most of $2$.

2 · you write the reasoning

Easier: the responsibilities are given, so only the M step is left. The data are $0,1,5,6$, and component 1 has $\gamma(z_{i1})=1,\ \allowbreak 0.8,\ \allowbreak 0.2,\ \allowbreak 0$. For each line, write why it is allowed.

  1. $$\begin{aligned}&N_1=1+0.8+0.2+0=2\\ &N_2=4-2=2\end{aligned}$$

    reasoning

    Each count is a column sum of the responsibilities; they add up to $n=4$ because every row adds to $1$.

  2. $$\begin{aligned}\mu_1&=\tfrac12\big[1(0)+0.8(1)\\ &\quad+0.2(5)+0(6)\big]=0.9\\ \mu_2&=\tfrac12\big[0(0)+0.2(1)\\ &\quad+0.8(5)+1(6)\big]=5.1\end{aligned}$$

    reasoning

    Weighted means: each point counts as much as its responsibility, and we divide by $N_j$, not by $4$.

  3. $$\begin{aligned}\sigma_1^2&=\tfrac12\big[1(0.81)+0.8(0.01)\\ &\quad+0.2(16.81)+0(26.01)\big]\\ &=2.09\end{aligned}$$

    reasoning

    Squared distances to the new mean $0.9$ are $0.81$, $0.01$, $16.81$ and $26.01$, weighted by $\gamma(z_{i1})$.

  4. $$\begin{aligned}\sigma_2^2&=\tfrac12\big[0(26.01)+0.2(16.81)\\ &\quad+0.8(0.01)+1(0.81)\big]\\ &=2.09\end{aligned}$$

    reasoning

    The same around $5.1$: data and responsibilities are mirror images, so the variance agrees.

  5. $$\pi_1=\pi_2=\frac{2}{4}=0.5$$

    reasoning

    Shares are counts over $n$; equal counts give equal shares.

3 · find the buried error

Harder, and the solution below hides two errors. Fit $K=2$ Gaussians to $2,3,5,9$ from $\pi=(0.7,\ 0.3)$, $\mu=(3,\ 8)$ and $\sigma^2=(1,\ 4)$, and carry out one EM iteration.

  1. Step 1. E step for the four points.

    $$\gamma(z_{i1})=\frac{\mathcal N(x_i\mid3,1)}{\mathcal N(x_i\mid3,1)+\mathcal N(x_i\mid8,4)}:\ 0.9909,\ 0.9785,\ 0.4547,\ 0$$

  2. Step 2. Column sums.

    $$\begin{aligned}&N_1=2.4241\\ &N_2=4-2.4241=1.5759\end{aligned}$$

  3. Step 3. Weighted mean of component 1.

    $$\begin{aligned}\mu_1&=\tfrac{1}{2.4241}\big[0.9909(2)\\ &\quad+0.9785(3)+0.4547(5)\\ &\quad+0(9)\big]=2.9663\end{aligned}$$

  4. Step 4. Weighted mean of component 2.

    $$\begin{aligned}\mu_2&=\tfrac{1}{1.5759}\big[0.0091(2)\\ &\quad+0.0215(3)+0.5453(5)\\ &\quad+1(9)\big]=7.4937\end{aligned}$$

  5. Step 5. Weighted variances around the new means.

    $$\sigma_1^2=\frac14\sum_i\gamma(z_{i1}){(x_i-2.9663)}^2=0.7017,\quad \sigma_2^2=1.5920$$

  6. Step 6. Shares.

    $$\begin{aligned}&\pi_1=\frac{2.4241}{4}=0.6060\\ &\pi_2=0.3940\end{aligned}$$

the two buried errors (2)
⚠ step 1

The E step leaves out the shares. With $\pi=(0.7,0.3)$ the products are $0.7\,\mathcal N(x_i\mid3,1)$ and $0.3\,\mathcal N(x_i\mid8,4)$.

With equal shares the $\pi_j$ cancel, and the habit of dropping them survives into problems where they do not.

right

$\gamma(z_{i1})=0.9961,\ \allowbreak 0.9907,\ \allowbreak 0.6605,\ \allowbreak 0$; then $N_1=2.6472$, $\mu_1=3.1227$, $\mu_2=7.9345$ and $\pi=(0.6618,\ 0.3382)$.

⚠ step 5

The variances are divided by $n=4$ instead of by $N_1$ and $N_2$.

A sample variance divides by the number of points, and $4$ is the number on the page.

right

Divide by $N_j$. With the corrected responsibilities, $\sigma_1^2=1.3592$ and $\sigma_2^2=3.2702$.

4 · the bare problem
§10.7 — one EM iteration from start to finish

Four readings $0,2,3,7$ are modeled by a mixture of two Gaussians. The current parameters are $\pi=(0.5,0.5)$, $\mu=(1,7)$ and $\sigma^2=(1,4)$.

Find
  1. (a) Compute the responsibilities $\gamma(z_{i1})$.

  2. (b) Compute the new $\pi_j$, $\mu_j$ and $\sigma_j^2$.

Given
  • data $0,\ 2,\ 3,\ 7$

  • $\pi=(0.5,\ 0.5)$, $\mu=(1,\ 7)$, $\sigma^2=(1,\ 4)$

Hint 1/4

One EM iteration is five lines: responsibilities, counts, means, variances, shares. Start with the point that sits between the two means.

Hint 2/4

$$\gamma(z_{i1})=\dfrac{\pi_1\mathcal N(x_i\mid\mu_1,\sigma_1^2)}{\sum_k\pi_k\mathcal N(x_i\mid\mu_k,\sigma_k^2)}$$ then $N_j=\sum_i\gamma(z_{ij})$, $\mu_j=\sum_i\gamma(z_{ij})x_i/N_j$, $\sigma_j^2=\sum_i\gamma(z_{ij})(x_i-\mu_j)^2/N_j$, $\pi_j=N_j/n$.

Hint 3/4

Data $0,2,3,7$ with $\pi=(0.5,0.5)$, $\mu=(1,7)$, $\sigma^2=(1,4)$. At $x=3$ the two products are $0.5\,\mathcal N(3\mid1,1)=0.0270$ and $0.5\,\mathcal N(3\mid7,4)=0.0135$.

Hint 4/4

$\gamma(z_{i1})=(0.9982,\ 0.9650,\ 0.6667,\ 0)$, $\pi=(0.6575,\ 0.3425)$, $\mu=(1.4944,\ 5.8901)$, $\sigma^2=(1.5161,\ 3.3629)$.

Show solution

The same five lines as the fully worked rung; the point $3$ is the one to watch.

E step

$$x=3:\ \ 0.5\,\mathcal N(3\mid1,1)=0.0270,\quad 0.5\,\mathcal N(3\mid7,4)=0.0135$$

Both are $2$ standard deviations out, and the narrower density is twice as tall.

$$\gamma(z_{i1})=0.9982,\ 0.9650,\ 0.6667,\ 0.0000$$

The point $3$ gets exactly $2/3$ from the factor of two above.

M step

$$\begin{aligned}&N_1=2.6299\\ &N_2=1.3701\end{aligned}$$

Each point splits one unit of weight between the components, so the column sums are effective counts and must add to $n=4$.

$$\begin{aligned}&\mu_1=1.4944\\ &\mu_2=5.8901\end{aligned}$$

Each point counts toward a mean as much as it belongs to that component, so the weighted sum is divided by $N_j$, not by $4$.

$$\begin{aligned}&\sigma_1^2=1.5161\\ &\sigma_2^2=3.3629\end{aligned}$$

The maximizing mean does not depend on the variance, so each $\sigma_j^2$ is fitted around the new $\mu_j$, again over $N_j$.

$$\begin{aligned}&\pi_1=0.6575\\ &\pi_2=0.3425\end{aligned}$$

A share is a fraction of all the points, so we divide by $n=4$, not by $N_j$.

Answer $$\boxed{\begin{aligned}\pi&=(0.6575,\ 0.3425)\\ \mu&=(1.4944,\ 5.8901)\\ \sigma^2&=(1.5161,\ 3.3629)\end{aligned}}$$
Check

Mean check: $0.6575(1.4944)+0.3425(5.8901)=3.0$, the plain mean of $0,2,3,7$; and $l$ rose from $-9.6986$ to $-8.7503$.

When one point sits between the components, its split decides most of the update, so compute it first.

Full exam-style question

From K-means to EM on six readings, and a reading in betweenexam format

Six sensor readings are $1,2,3,7,8,12$.

  • (a) Run K-means with $K=2$ from $\mu_1=1$, $\mu_2=12$ until it stops, and give $J$.
  • (b) Start a two-component Gaussian mixture from the result: shares from the cluster sizes, means from the prototypes, variances from the clusters.
  • (c) A new reading $x=5$ arrives. Which cluster does K-means give it, and what are the mixture's responsibilities?
  • (d) Explain the difference in one sentence.
Find(a) the clusters and $J$; (b) $\pi$, $\mu$, $\sigma^2$; (c) the K-means cluster and the responsibilities of $x=5$; (d) the reason they differ.
Given
  • readings $1,\ 2,\ 3,\ 7,\ 8,\ 12$

  • K-means start $\mu_1=1$, $\mu_2=12$

  • new reading $x=5$

Solution

K-means first, because its clusters are the cheapest good start for EM; the responsibilities then come from the log-densities, because the two variances differ.

(a) K-means

$$\begin{aligned}&\text{E: }\{1,2,3\},\ \{7,8,12\}\\ &J=0+1+4+25+16+0\\ &\quad=46\end{aligned}$$

$7$ is $6$ from $\mu_1=1$ and $5$ from $\mu_2=12$, so it joins cluster 2.

$$\begin{aligned}&\text{M: }\mu_1=2,\ \ \mu_2=9\\ &J=1+0+1+4+1+9=16\end{aligned}$$

With the clusters fixed, each prototype moves to its cluster mean, the minimizer of its squared distances.

$$\text{E: }3\text{ is }1\text{ from }\mu_1,\ \ 7\text{ is }2\text{ from }\mu_2$$

No reading changes cluster, so K-means stops at $J=16$.

(b) Start the mixture

$$\begin{aligned}&\pi=(0.5,\ 0.5)\\ &\mu=(2,\ 9)\end{aligned}$$

Three readings in each cluster; the prototypes become the means.

$$\begin{aligned}&\sigma_1^2=\tfrac{1+0+1}{3}=\tfrac23\\ &\sigma_2^2=\tfrac{4+1+9}{3}=\tfrac{14}{3}\end{aligned}$$

Divide by the cluster size, as the M step would.

(c) The reading 5

$$\lvert5-2\rvert=3<\lvert5-9\rvert=4\ \Rightarrow\ \text{K-means: cluster 1}$$

K-means looks only at distances.

$$\begin{aligned}&\log\mathcal N(5\mid2,\tfrac23)\\ &\quad=-\tfrac{9}{4/3}-\tfrac12\log\big(2\pi\cdot\tfrac23\big)\\ &\quad=-6.750-0.716=-7.466\end{aligned}$$

The squared distance $9$ over $2\sigma_1^2=4/3$, minus half the log of $2\pi\sigma_1^2$.

$$\begin{aligned}&\log\mathcal N(5\mid9,\tfrac{14}3)\\ &\quad=-\tfrac{16}{28/3}-\tfrac12\log\big(2\pi\cdot\tfrac{14}3\big)\\ &\quad=-1.714-1.689=-3.403\end{aligned}$$

The squared distance $16$ over $2\sigma_2^2=28/3$.

$$\begin{aligned}\gamma(z_2)&=\frac{1}{1+e^{-(7.466-3.403)}}\\ &=\frac{1}{1+e^{-4.063}}=0.983\end{aligned}$$

Equal shares cancel; the log-odds of component 2 is $4.063$.

(d) Why they differ

$$\begin{aligned}&\frac{5-2}{\sqrt{2/3}}=3.67\\ &\frac{9-5}{\sqrt{14/3}}=1.85\end{aligned}$$

Measured in standard deviations, $5$ is far from the tight cluster and near the wide one.

Answer $$\boxed{\begin{aligned}&\text{(a) }\{1,2,3\},\\ &\qquad\{7,8,12\},\ J=16\\ &\text{(b) }\pi=(0.5,\ 0.5)\\ &\qquad\mu=(2,\ 9)\\ &\qquad\sigma^2=(\tfrac23,\ \tfrac{14}3)\\ &\text{(c) K-means: cluster 1}\\ &\qquad\gamma(z_2)=0.983\end{aligned}}$$
Check

(c) through the densities: $\mathcal N(5\mid2,\tfrac23)=0.000572$ and $\mathcal N(5\mid9,\tfrac{14}3)=0.0333$, and $0.0333/(0.0333+0.000572)=0.983$. One EM iteration from this start moves the means only to $1.9947$ and $8.9601$.

Two E steps and one M step of K-means, then two log-densities.

K-means is a cheap way to start EM, but its hard cut and EM's responsibilities disagree wherever the clusters have different spreads.

Practice

A · concept 4 questions
1§10.1 — does K-means always find the best split?

A classmate says that every iteration of K-means lowers $J$ until it reaches the smallest $J$ over all ways of splitting the data into $K$ groups.

Find(a) Is the claim true or false?
Given
  • K-means with a fixed $K$ and a given start

  • $J=\sum_i\sum_kr_{ik}\lVert x_i-\mu_k\rVert^2$

Hint 1/4

Split the claim in two, whether $J$ goes down and whether it ends at the best split, and check each part on its own.

Hint 2/4

Each step minimizes $J$ over its own unknowns, so $J$ cannot rise; a stopping point is only a state that neither step can improve.

Hint 3/4

Test case: the corners $(0,0), \allowbreak (0,2), \allowbreak (6,0), \allowbreak (6,2)$ with the start $\mu_1=(3,-1)$, $\mu_2=(3,3)$.

Hint 4/4

That run stops at $J=36$ while the left-right split has $J=4$, so the claim is false.

Show solution

One counterexample settles a claim about every run, so we look for a start that stalls.

The first half holds

$$\begin{aligned}&J_{\text{after E}}\le J_{\text{before}}\\ &J_{\text{after M}}\le J_{\text{after E}}\end{aligned}$$

Each step is the exact minimizer over its own unknowns.

The second half fails

$$\begin{aligned}&\text{top-bottom split: }J=36\\ &\text{left-right split: }J=4\end{aligned}$$

From $(3,-1)$ and $(3,3)$ the run splits top from bottom and stops: each corner is $9$ from its mean and $13$ from the other.

Answer $$\boxed{\text{False}}$$
Check

The left-right split is also a fixed point, and a better one; K-means can end at either, depending on where it starts.

Restart K-means from several starts and keep the run with the smallest $J$.

2§10.5 — can a mixture density exceed 1?

A classmate claims that a Gaussian mixture density $p(x)=\sum_j\pi_j\mathcal N(x\mid\mu_j,\sigma_j^2)$ can be larger than $1$ at some $x$, even though its mixing coefficients add up to $1$.

Find(a) Is the claim true or false?
Given
  • $\pi_j\ge0$, $\sum_j\pi_j=1$

  • test case: $p(x)=0.5\,\mathcal N(x\mid0,\ 0.01)+0.5\,\mathcal N(x\mid3,\ 1)$

Hint 1/4

A density is not a probability; ask what limits its height and what limits its area.

Hint 2/4

$\mathcal N(\mu\mid\mu,\sigma^2)=1/\sqrt{2\pi\sigma^2}$, which grows without limit as $\sigma^2\to0$.

Hint 3/4

In the test case $\sigma_1^2=0.01$, so $\mathcal N(0\mid0,0.01)=1/\sqrt{0.0628}=3.99$, with weight $0.5$.

Hint 4/4

$p(0)\approx0.5(3.99)+0.5(0.004)=2.0>1$, so the claim is true.

Show solution

One evaluation at the narrow component's peak decides the claim.

The two densities

$$\begin{aligned}&\mathcal N(0\mid0,0.01)=\frac{1}{\sqrt{2\pi\cdot0.01}}\\ &\quad=3.9894\\ &\mathcal N(0\mid3,1)=0.0044\end{aligned}$$

The narrow Gaussian is tall at its center; the other is three standard deviations away.

The mixture

$$p(0)=0.5(3.9894)+0.5(0.0044)=1.9969$$

A weighted average of the two.

Answer $$\boxed{\text{True: }p(0)\approx2.0}$$
Check

The area is still $1$: $0.5\cdot1+0.5\cdot1$. A tall, narrow peak has little area.

Heights of densities are not probabilities; only areas are.

3§10.6 — what a responsibility of 0.7 says

After a two-component mixture is fitted, one data point $x_i$ has $\gamma(z_{i1})=0.7$, while the fitted share of component 1 is $\pi_1=0.4$.

Find(a) Which statement is correct?
Given
  • $\gamma(z_{i1})=0.7$, $\gamma(z_{i2})=0.3$

  • $\pi_1=0.4$, $\pi_2=0.6$

Hint 1/4

Ask whether $0.7$ describes this one point or the data as a whole.

Hint 2/4

$\gamma(z_{i1})=p(z_{i1}=1\mid x_i)$ is a posterior for one point; $\pi_1=p(z_1=1)$ is the prior share of all points.

Hint 3/4

Here $\gamma(z_{i1})=0.7$ for the point $x_i$, and $\pi_1=0.4$ for the data.

Hint 4/4

Among many points with this same value, about $7$ in $10$ come from component 1.

Show solution

Writing both as probabilities shows at once which one is conditioned on the value $x_i$.

Two different probabilities

$$\begin{aligned}&\gamma(z_{i1})=p(z_{i1}=1\mid x_i)=0.7\\ &\pi_1=p(z_1=1)=0.4\end{aligned}$$

The first conditions on the value of the point; the second does not.

Answer $$\boxed{p(z_{i1}=1\mid x_i)=0.7}$$
Check

Frequency reading: of $1000$ points that all take this value, about $700$ come from component 1; of $1000$ points drawn at random, about $400$ do.

A responsibility can be large for component 1 at some values and small at others; its average over all points is the share.

4§10.2 — K-medoids with the squared distance

A classmate says that if K-medoids uses the squared Euclidean distance as its dissimilarity, it gives exactly the same prototypes as K-means.

Find(a) Is the claim true or false?
Given
  • K-medoids M step: $\mu_k=\arg\min_{m\in N_k}\sum_{x_i\in N_k}V(x_i,m)$

  • $V(x,m)=\lVert x-m\rVert^2$

  • test cluster: $\{0,\ 1,\ 5\}$ on a line

Hint 1/4

Compare what each M step is allowed to choose, not only what it minimizes.

Hint 2/4

K-means may put $\mu_k$ anywhere, and the minimizer is the mean; K-medoids must pick one of the cluster's own points.

Hint 3/4

For $\{0,1,5\}$ the mean is $2$; the totals of squared distances are $26$ at $0$, $17$ at $1$ and $41$ at $5$.

Hint 4/4

K-medoids picks $1$ and K-means picks $2$, so the claim is false.

Show solution

A single small cluster is enough to separate the two M steps.

K-means

$$\begin{aligned}&\mu=\tfrac{0+1+5}{3}=2\\ &\textstyle\sum(x-2)^2=4+1+9=14\end{aligned}$$

The mean minimizes the total squared distance over all real numbers.

K-medoids

$$\begin{aligned}&0:\ 26\\ &1:\ 17\\ &5:\ 41\end{aligned}$$

Only the three members are allowed, and $1$ has the smallest total.

Answer $$\boxed{\text{False: }2\text{ against }1}$$
Check

$14<17$: K-means reaches a lower total because it may leave the data points; K-medoids pays for the restriction.

Same dissimilarity, different candidates: that alone separates the two methods.

B · computation 8 questions
1§10.1 — K-means on six parcel weights

Six parcel weights, in kg, are clustered with K-means and $K=2$. The run starts from the prototypes $\mu_1=1$ and $\mu_2=4$.

Find
  1. (a) Run K-means until an E step changes nothing. Give the final clusters and prototypes.

  2. (b) Give $J$ after each M step.

Given
  • weights: $1,\ 3,\ 4,\ 9,\ 10,\ 15$

  • start: $\mu_1=1$, $\mu_2=4$

Hint 1/4

Alternate the two steps and keep a list of the clusters; stop when the list repeats.

Hint 2/4

E step: nearest prototype by $(x-\mu)^2$. M step: cluster means. $J=\sum_i(x_i-\mu_{k(i)})^2$.

Hint 3/4

Weights $1,3,4,9,10,15$ from $\mu=(1,4)$: in the first E step only the weight $1$ is nearer to $\mu_1=1$.

Hint 4/4

Final clusters $\{1,3,4\}$ and $\{9,10,15\}$ with $\mu=(8/3,\ 34/3)$; $J=94.8$ after the first M step and $25.33$ after the second.

Show solution

On a line each E step is a comparison of two absolute differences, so the run is quick to trace.

Iteration 1

$$\text{E: }\{1\},\ \{3,4,9,10,15\}$$

$3$ is $2$ from $\mu_1$ but $1$ from $\mu_2=4$.

$$\begin{aligned}&\text{M: }\mu=(1,\ 8.2)\\ &J=0+27.04+17.64\\ &\quad+0.64+3.24+46.24\\ &\quad=94.8\end{aligned}$$

The mean of the five large weights is $41/5$.

Iteration 2

$$\text{E: }\{1,3,4\},\ \{9,10,15\}$$

$3$ and $4$ are now nearer to $1$ than to $8.2$.

$$\begin{aligned}&\text{M: }\mu=\big(\tfrac83,\ \tfrac{34}3\big)\\ &J=\tfrac{76}{3}\approx25.33\end{aligned}$$

Measured around the new means, $J$ cannot exceed its value around the old prototypes.

Iteration 3

$$\begin{aligned}&4\text{ is }1.33\text{ from }\mu_1\\ &9\text{ is }2.33\text{ from }\mu_2\end{aligned}$$

No weight changes cluster, so the run stops.

Answer $$\boxed{\begin{aligned}&\{1,3,4\},\ \ \mu_1=\tfrac83\\ &\{9,10,15\},\ \ \mu_2=\tfrac{34}3\\ &J=25.33\end{aligned}}$$
Check

Pairwise check: the pairs of $\{1,3,4\}$ give $4+9+1=14$ and those of $\{9,10,15\}$ give $1+36+25=62$; $(14+62)/3=25.33$.

A far start can hand most points to one prototype at first; the M step then pulls the prototypes apart.

2§10.1 — three clusters in the plane

Seven delivery points in the plane, in km, are clustered with K-means and $K=3$. The run starts from three of the points themselves.

Find
  1. (a) Carry out the first E step and the first M step.

  2. (b) Continue until nothing changes; give the final prototypes and $J$.

Given
  • points: $(0,0),\ \allowbreak (1,0),\ \allowbreak (0,2),\ \allowbreak (5,5),\ \allowbreak (6,5),\ \allowbreak (9,0),\ \allowbreak (10,2)$

  • start: $\mu_1=(0,0)$, $\mu_2=(5,5)$, $\mu_3=(6,5)$

Hint 1/4

With three prototypes each point has three squared distances; the points that sit between two prototypes decide the run.

Hint 2/4

E: nearest prototype. M: mean of each cluster. $J$ adds each point's squared distance to its own prototype.

Hint 3/4

The point $(6,5)$ is itself the third prototype, so the first E step puts it with $(9,0)$ and $(10,2)$.

Hint 4/4

After two iterations $\mu=(\tfrac13,\tfrac23),\ (5.5,5),\ (9.5,1)$ and $J=19/3\approx6.33$.

Show solution

Only $(6,5)$, $(9,0)$ and $(10,2)$ are close calls, so we check those three in full and the rest at a glance.

E step 1

$$\begin{aligned}&(9,0):\ 81,\ 41,\ 34\\ &(10,2):\ 104,\ 34,\ 25\end{aligned}$$

Squared distances to $\mu_1,\mu_2,\mu_3$: both far points pick $\mu_3=(6,5)$.

$$J=0+1+4+0+0+34+25=64$$

$(5,5)$ and $(6,5)$ sit on their own prototypes.

M step 1

$$\mu_1=(\tfrac13,\tfrac23),\quad \mu_2=(5,5),\quad \mu_3=(\tfrac{25}3,\tfrac73)$$

Cluster 2 still holds only $(5,5)$.

$$J=\tfrac{30}{9}+0+\tfrac{64}{3}=24.67$$

Cluster 3's squared deviations add up to $64/3$.

E step 2 and M step 2

$$(6,5):\ 1\text{ to }\mu_2,\ \ 12.56\text{ to }\mu_3$$

So $(6,5)$ moves to cluster 2.

$$\begin{aligned}&\mu_2=(5.5,\ 5),\quad \mu_3=(9.5,\ 1)\\ &J=\tfrac{10}3+0.5+2.5=\tfrac{19}3\end{aligned}$$

The next E step changes nothing, so the run stops.

Answer $$\boxed{\begin{aligned}&\mu=(\tfrac13,\tfrac23),\ (5.5,5),\ (9.5,1)\\ &J=\tfrac{19}{3}\approx6.33\end{aligned}}$$
Check

Pairwise check for cluster 3: $(9,0)$ and $(10,2)$ are $1+4=5$ apart, and $5/2=2.5$ is its share of $J$.

Starting two prototypes next to each other is risky; here the M step separated them within one iteration.

3§10.2 — K-medoids on a street grid

Six kiosks on a street grid, in blocks, are grouped with K-medoids and the Manhattan distance, starting from the medoids $(0,0)$ and $(7,7)$.

Find
  1. (a) Do one E step and one M step.

  2. (b) Does a second iteration change anything? Give the final $\tilde J$.

Given
  • kiosks: $(0,0),\ \allowbreak (1,0),\ \allowbreak (0,2),\ \allowbreak (5,5),\ \allowbreak (6,3),\ \allowbreak (7,7)$

  • start: medoids $(0,0)$ and $(7,7)$

  • $V(x,m)=\lvert x_1-m_1\rvert+\lvert x_2-m_2\rvert$

Hint 1/4

Street distances add the horizontal and the vertical blocks; first decide which medoid each kiosk is closer to.

Hint 2/4

E: nearest medoid by $V$. M: in each cluster, the member with the smallest total $V$ to the members.

Hint 3/4

The first three kiosks are $0$, $1$ and $2$ blocks from $(0,0)$; $(5,5)$ and $(6,3)$ are $4$ and $5$ from $(7,7)$.

Hint 4/4

Cluster 2's totals are $7$ for $(5,5)$, $8$ for $(6,3)$ and $9$ for $(7,7)$, so the medoids become $(0,0)$ and $(5,5)$; nothing changes after that, and $\tilde J=10$.

Show solution

Each cluster has three members, so the M step is three sums per cluster.

E step

$$\begin{aligned}&(5,5):\ 10\text{ vs }4\\ &(6,3):\ 9\text{ vs }5\end{aligned}$$

Distances to $(0,0)$ and $(7,7)$; the near three kiosks stay with $(0,0)$.

$$\tilde J=0+1+2+4+5+0=12$$

Each kiosk's distance to its own medoid.

M step

$$(0,0):\ 3;\quad (1,0):\ 4;\quad (0,2):\ 5$$

Cluster 1 keeps $(0,0)$.

$$(5,5):\ 3+4=7;\quad (6,3):\ 3+5=8;\quad (7,7):\ 4+5=9$$

Cluster 2 switches to $(5,5)$.

$$\tilde J=0+1+2+0+3+4=10$$

Same clusters, a better medoid.

Second iteration

$$(6,3):\ 9\text{ to }(0,0),\ \ 3\text{ to }(5,5)$$

No kiosk changes cluster, and the medoids stay.

Answer $$\boxed{\text{medoids }(0,0),\ (5,5);\ \ \tilde J=10}$$
Check

$\tilde J$ fell from $12$ to $10$ and then stayed, as a run that has stopped must.

Street distances and data-point prototypes make K-medoids natural for sites on a grid.

4§10.3 — two palettes for one image

A $256\times256$ RGB image, $8$ bits per channel, is compressed by K-means, once with $K=5$ colors and once with $K=32$.

Find
  1. (a) Give both compressed sizes and both ratios to the original.

  2. (b) Which other values of $K$ cost exactly as many bits per label as $K=5$?

Given
  • $256\times256$ pixels, $24$ bits per pixel in the original

  • $K=5$ and $K=32$

Hint 1/4

The label length depends only on how many colors must be told apart; find it before multiplying.

Hint 2/4

Size $=24K+n\lceil\log_2K\rceil$; the original takes $24n$.

Hint 3/4

$n=256\cdot256=65{,}536$; $\lceil\log_25\rceil=3$ and $\log_232=5$.

Hint 4/4

$K=5$: $196{,}728$ bits, ratio $8.00$; $K=32$: $328{,}448$ bits, ratio $4.79$; $K=6,7,8$ also need $3$ bits per label.

Show solution

Label bits first; they are the whole story up to a few hundred bits.

K = 5

$$24\cdot5+65{,}536\cdot3=120+196{,}608=196{,}728$$

$\log_25\approx2.32$ rounds up to $3$.

$$1{,}572{,}864/196{,}728=8.00$$

The palette's $120$ bits are tiny next to the labels, so the ratio is almost $24$ bits per pixel over $3$.

K = 32

$$24\cdot32+65{,}536\cdot5=768+327{,}680=328{,}448$$

$\log_232=5$ exactly.

$$1{,}572{,}864/328{,}448=4.79$$

The palette adds only $768$ bits, so the ratio sits just under $24/5=4.8$.

Same label length as K = 5

$$\lceil\log_2K\rceil=3\iff5\le K\le8$$

Three bits name up to $8$ colors.

Answer $$\boxed{\begin{aligned}K=5&:\ 196{,}728\ (\times8.00)\\ K=32&:\ 328{,}448\ (\times4.79)\\ &K=6,7,8\text{ as }K=5\end{aligned}}$$
Check

The ratios sit just below $24/3$ and $24/5$, by the palette's share.

Between powers of two, extra colors are free in label bits and cost only $24$ bits each.

5§10.4 — three runs with lost coin labels

Three runs of $10$ flips were made, each with coin A or coin B picked with probability $1/2$, and the coins were not recorded. The heads counts were $9$, $2$ and $6$.

Find
  1. (a) Compute the posteriors $\gamma_{iA}$.

  2. (b) Compute $\theta_A^{(1)}$ and $\theta_B^{(1)}$.

Given
  • heads: $9,\ 2,\ 6$ out of $10$

  • start: $\theta_A^{(0)}=0.7$, $\theta_B^{(0)}=0.4$

  • each coin picked with probability $1/2$

Hint 1/4

Start from how much better one coin explains each run than the other; the binomial coefficient will cancel.

Hint 2/4

$a_i/b_i=(\theta_A/\theta_B)^{x_i}\big((1-\theta_A)/(1-\theta_B)\big)^{10-x_i}$ and $\gamma_{iA}=\frac{a_i/b_i}{1+a_i/b_i}$; then heads over flips for each coin.

Hint 3/4

With $\theta_A=0.7$ and $\theta_B=0.4$ the two factors are $1.75$ and $0.5$; the heads are $9,2,6$.

Hint 4/4

$\gamma_{iA}=(0.9872,\ 0.0118,\ 0.6422)$, so $\theta_A^{(1)}=0.7776$ and $\theta_B^{(1)}=0.3119$.

Show solution

The ratio $a_i/b_i=1.75^{x_i}0.5^{10-x_i}$ gives each posterior in one line.

E step

$$\frac{a_i}{b_i}=76.968,\ \ 0.01196,\ \ 1.7952$$

The binomial coefficient and the prior $1/2$ are the same for both coins, so they cancel in the ratio, leaving $1.75^{x}\,0.5^{10-x}$ for $x=9,2,6$.

$$\gamma_{iA}=0.9872,\ \ 0.0118,\ \ 0.6422$$

A run's two posteriors add to $1$, so with $r=a_i/b_i$ we get $\gamma_{iA}=r/(1+r)$ without evaluating any binomial probability.

Credit

$$H_A=9(0.9872)+2(0.0118)+6(0.6422)=12.7617$$

Coin A made each run with probability $\gamma_{iA}$, so it is credited with that fraction of the run's heads.

$$F_A=10(0.9872+0.0118+0.6422)=16.4124$$

The same fraction of each run's $10$ flips, so heads and flips are credited on the same footing.

$$\begin{aligned}&H_B=17-12.7617=4.2383\\ &F_B=30-16.4124=13.5876\end{aligned}$$

Every run is split between the two coins, so B's credit is the total $17$ heads and $30$ flips minus A's.

M step

$$\begin{aligned}&\theta_A^{(1)}=\frac{12.7617}{16.4124}=0.7776\\ &\theta_B^{(1)}=\frac{4.2383}{13.5876}=0.3119\end{aligned}$$

With the credited counts in hand, the M step is the known-coin estimate, heads over flips, applied to fractional counts.

Answer $$\boxed{\theta_A^{(1)}=0.7776,\quad \theta_B^{(1)}=0.3119}$$
Check

The credited heads add up: $12.7617+4.2383=17=9+2+6$, and the flips: $16.4124+13.5876=30$.

The run with $6$ heads is the only uncertain one, and it is where the two coins share the credit.

6§10.5 — parameters of a mixture in three dimensions

A mixture of $K=4$ Gaussians is fitted to data with $p=3$ features. We compare two versions of the model before fitting.

Find
  1. (a) How many free parameters does the full-covariance version have?

  2. (b) How many does the diagonal version have?

Given
  • $K=4$ components, $p=3$ dimensions

  • version (a): full covariance matrices; version (b): diagonal covariance matrices

Hint 1/4

Count the three kinds of parameters one at a time: shares, means, covariances.

Hint 2/4

$(K-1)+Kp+K\,\tfrac{p(p+1)}{2}$ for full covariances; a diagonal covariance has only $p$ free entries.

Hint 3/4

$K=4$ and $p=3$, so $p(p+1)/2=6$.

Hint 4/4

Full: $3+12+24=39$. Diagonal: $3+12+12=27$.

Show solution

The general formula, then the diagonal change in its last term.

Shares and means

$$\begin{aligned}&K-1=3\\ &Kp=12\end{aligned}$$

The shares lose one to their constraint.

Covariances

$$\begin{aligned}&\text{full: }4\cdot6=24\\ &\text{diagonal: }4\cdot3=12\end{aligned}$$

A symmetric $3\times3$ matrix has $6$ free entries; a diagonal one has $3$.

Answer $$\boxed{39\ \text{and}\ 27}$$
Check

Edge check with $p=1$: both versions give $3+4+4=11$, as they must, since a $1\times1$ covariance is diagonal.

Diagonal covariances save $K\,p(p-1)/2$ numbers, the off-diagonal ones.

7§10.6 — responsibilities with unequal spreads

Two components in the plane: component 1 has $\pi_1=0.3$, $\mu_1=(0,0)$, $\Sigma_1=\operatorname{diag}(1,4)$; component 2 has $\pi_2=0.7$, $\mu_2=(3,0)$, $\Sigma_2=I$. A point is observed at $x=(1,2)$.

Find
  1. (a) Compute both densities at $x$.

  2. (b) Compute $\gamma(z_1)$.

Given
  • $\pi=(0.3,\ 0.7)$

  • $\mu_1=(0,0)$, $\Sigma_1=\operatorname{diag}(1,4)$

  • $\mu_2=(3,0)$, $\Sigma_2=I$

  • $x=(1,2)$

Hint 1/4

Evaluate each Gaussian at the point first; the shares enter only at the end.

Hint 2/4

In two dimensions $$\mathcal N(x\mid\mu,\Sigma)=\frac{1}{2\pi\lvert\Sigma\rvert^{1/2}}\exp\big(-\tfrac12(x-\mu)^T\Sigma^{-1}(x-\mu)\big)$$ then $\gamma(z_1)=\pi_1\mathcal N_1/(\pi_1\mathcal N_1+\pi_2\mathcal N_2)$.

Hint 3/4

$x-\mu_1=(1,2)$ with $\Sigma_1^{-1}=\operatorname{diag}(1,\tfrac14)$; $x-\mu_2=(-2,2)$ with $\Sigma_2^{-1}=I$; $\pi=(0.3,0.7)$.

Hint 4/4

$\mathcal N_1=e^{-1}/(4\pi)=0.0293$ and $\mathcal N_2=e^{-4}/(2\pi)=0.0029$, so $\gamma(z_1)=0.81$.

Show solution

Diagonal covariances make each quadratic form a sum of two scaled squares.

Component 1

$${(x-\mu_1)}^T\Sigma_1^{-1}(x-\mu_1)=\frac{1^2}{1}+\frac{2^2}{4}=2$$

The vertical step of $2$ counts only a quarter, because that direction has variance $4$.

$$\mathcal N_1=\frac{e^{-1}}{2\pi\cdot2}=0.02927$$

$\lvert\Sigma_1\rvert^{1/2}=\sqrt4=2$.

Component 2

$$\begin{aligned}&{(x-\mu_2)}^T(x-\mu_2)=4+4=8\\ &\mathcal N_2=\frac{e^{-4}}{2\pi}=0.00292\end{aligned}$$

The identity covariance gives the plain squared distance.

Responsibility

$$\begin{aligned}&0.3(0.02927)=0.00878\\ &0.7(0.00292)=0.00204\\ &\gamma(z_1)=\frac{0.00878}{0.01082}=0.8115\end{aligned}$$

Bayes' rule weighs each density by its share; component 1's density is ten times larger, which outweighs a share less than half as big.

Answer $$\boxed{\gamma(z_1)=0.8115}$$
Check

Log-odds route: $\log\frac{0.3}{0.7}+(-1-\log(4\pi))-(-4-\log(2\pi))=-0.847+3-0.693=1.460$, and $1/(1+e^{-1.460})=0.8115$.

Stretching halves a component's peak here ($\lvert\Sigma_1\rvert^{1/2}=2$) but pays back in the exponent: with $\Sigma_1=I$ the same point would give $\gamma(z_1)=0.66$, with the stretch $0.81$.

8§10.7 — an M step from a table of responsibilities

An E step on five numbers has produced the responsibilities of component 1 below; component 2 has the rest of each point.

Find
  1. (a) Compute $N_1$, $N_2$, $\pi_1$ and $\pi_2$.

  2. (b) Compute $\mu_1$, $\mu_2$, $\sigma_1^2$ and $\sigma_2^2$.

Given
  • data: $2,\ 4,\ 5,\ 10,\ 11$

  • $\gamma(z_{i1})=1,\ \allowbreak 0.9,\ \allowbreak 0.6,\ \allowbreak 0.1,\ \allowbreak 0$

Hint 1/4

Everything in the M step divides by a column sum, so compute the two column sums first.

Hint 2/4

$N_j=\sum_i\gamma(z_{ij})$, $\pi_j=N_j/n$, $\mu_j=\sum_i\gamma(z_{ij})x_i/N_j$, $\sigma_j^2=\sum_i\gamma(z_{ij})(x_i-\mu_j)^2/N_j$.

Hint 3/4

Data $2,4,5,10,11$; $\gamma(z_{i1})=1, \allowbreak 0.9, \allowbreak 0.6, \allowbreak 0.1, \allowbreak 0$ and $\gamma(z_{i2})=0, \allowbreak 0.1, \allowbreak 0.4, \allowbreak 0.9, \allowbreak 1$.

Hint 4/4

$N=(2.6,\ 2.4)$, $\pi=(0.52,\ 0.48)$, $\mu=(3.6923,\ 9.3333)$, $\sigma^2=(3.0592,\ 5.6389)$.

Show solution

Column sums first, then means, then variances around the new means.

Counts and shares

$$\begin{aligned}&N_1=2.6,\quad N_2=2.4\\ &\pi=(0.52,\ 0.48)\end{aligned}$$

$N_1$ is the column sum $1+0.9+0.6+0.1+0$; $N_2=5-N_1$ because each point's two responsibilities add to $1$, and a share is a count over all $n=5$ points.

Means

$$\begin{aligned}&\mu_1=\frac{2+3.6+3+1+0}{2.6}\\ &\quad=3.6923\\ &\mu_2=\frac{0+0.4+2+9+11}{2.4}\\ &\quad=9.3333\end{aligned}$$

Each point enters the mean with its responsibility as weight, so the divisor is the total weight $N_j$, not $5$.

Variances

$$\begin{aligned}\sigma_1^2&=\tfrac{1}{2.6}\big(2.8639+0.0852\\ &\quad+1.0260+3.9787+0\big)\\ &=3.0592\end{aligned}$$

The maximizing mean does not depend on the variance, so $\sigma_1^2$ is fitted around the new $\mu_1=3.6923$, each squared deviation with its point's weight.

$$\begin{aligned}\sigma_2^2&=\tfrac{1}{2.4}\big(0+2.8444+7.5111\\ &\quad+0.4000+2.7778\big)\\ &=5.6389\end{aligned}$$

The same rule for component 2 around $9.3333$; its weights $0, \allowbreak 0.1, \allowbreak 0.4, \allowbreak 0.9, \allowbreak 1$ are one minus component 1's.

Answer $$\boxed{\begin{aligned}\pi&=(0.52,\ 0.48)\\ \mu&=(3.6923,\ 9.3333)\\ \sigma^2&=(3.0592,\ 5.6389)\end{aligned}}$$
Check

$0.52(3.6923)+0.48(9.3333)=6.4$, the plain mean of $2,4,5,10,11$.

A point with a small responsibility can still dominate a variance: $10$, with weight only $0.1$, adds $3.98$ to the weighted sum, about $1.5$ of $\sigma_1^2=3.06$, because it is far from $\mu_1$.

C · exam level 5 questions
1§10.7 — the new mean after one EM iteration

A two-component mixture is fitted to the numbers $2,5,6,9$. The current parameters are $\pi=(0.5,0.5)$, $\mu=(2,6)$ and $\sigma^2=(4,4)$.

Find(a) After one EM iteration, what is $\mu_1^{\text{new}}$?
Given
  • data $2,\ 5,\ 6,\ 9$

  • $\pi=(0.5,\ 0.5)$, $\mu=(2,\ 6)$, $\sigma^2=(4,\ 4)$

Hint 1/4

Responsibilities first, then a weighted mean; with equal shares and variances each responsibility comes from one log-odds.

Hint 2/4

$\log\frac{\gamma(z_{i1})}{\gamma(z_{i2})}=\frac{(x_i-\mu_2)^2-(x_i-\mu_1)^2}{2\sigma^2}$, then $\mu_1^{\text{new}}=\sum_i\gamma(z_{i1})x_i/\sum_i\gamma(z_{i1})$.

Hint 3/4

With $\mu=(2,6)$ and $\sigma^2=4$ the log-odds is $((x-6)^2-(x-2)^2)/8=4-x$, for $x=2,5,6,9$.

Hint 4/4

$\gamma(z_{i1})=0.8808,\ \allowbreak 0.2689,\ \allowbreak 0.1192,\ \allowbreak 0.0067$, so $\mu_1^{\text{new}}=3.8816/1.2756=3.04$.

Show solution

The log-odds is linear in $x$ here, which avoids four density evaluations per component.

E step

$$\frac{(x-6)^2-{(x-2)}^2}{8}=4-x:\ \ 2,\ -1,\ -2,\ -5$$

Equal shares and equal variances cancel in the ratio, so the log-odds is the difference of squared distances over $2\sigma^2=8$, a line in $x$.

$$\gamma(z_{i1})=\frac{1}{1+e^{-(4-x_i)}}=0.8808,\ 0.2689,\ 0.1192,\ 0.0067$$

With two components $\gamma_1=r/(1+r)$ for the odds $r$, which is the logistic function of the log-odds; no density needs evaluating.

Weighted mean

$$\begin{aligned}\mu_1^{\text{new}}&=\tfrac{1}{1.2756}\big(1.7616+1.3445\\ &\quad+0.7152+0.0603\big)\\ &=3.8816/1.2756=3.043\end{aligned}$$

Each point pulls $\mu_1$ with its responsibility as weight, so we divide by the total weight $N_1=1.2756$, not by the $4$ points.

Answer $$\boxed{\mu_1^{\text{new}}=3.04}$$
Check

Range check: $\mu_1^{\text{new}}$ is a weighted average of $2,5,6,9$ with most weight on $2$, so it lies between $2$ and $5.5$; $3.04$ does.

The point $5$, with responsibility only $0.27$, still moves $\mu_1$ by about $0.63$, most of the shift from $2$ to $3.04$.

2§10.1 — where a K-means run on a rectangle stops

K-means with $K=2$ runs on the corners $(0,0)$, $(0,4)$, $(2,0)$ and $(2,4)$ of a rectangle, starting from $\mu_1=(-1,2)$ and $\mu_2=(3,2)$.

Find(a) What is $J$ when the run stops?
Given
  • points $(0,0),\ \allowbreak (0,4),\ \allowbreak (2,0),\ \allowbreak (2,4)$

  • start $\mu_1=(-1,2)$, $\mu_2=(3,2)$

Hint 1/4

Follow the run step by step instead of assuming it finds the best split.

Hint 2/4

E: nearest prototype. M: cluster means. Stop when an E step changes nothing.

Hint 3/4

From $(-1,2)$ and $(3,2)$, each corner is $1+4=5$ from the prototype on its own side and $9+4=13$ from the other.

Hint 4/4

The run splits left from right, with means $(0,2)$ and $(2,2)$, and stops at $J=16$.

Show solution

Two half-steps settle it, so we trace them.

E step

$$\begin{aligned}&\{(0,0),(0,4)\},\ \{(2,0),(2,4)\}\\ &J=4\times5=20\end{aligned}$$

Each corner is $5$ from the prototype on its side.

M step

$$\begin{aligned}&\mu_1=(0,2),\quad \mu_2=(2,2)\\ &J=4\times4=16\end{aligned}$$

Each corner is $2$ from its mean.

Next E step

$$(0,0):\ 4\text{ to }\mu_1,\ \ 8\text{ to }\mu_2$$

Nothing moves, so the run stops at $16$.

Answer $$\boxed{J=16}$$
Check

The top-bottom split, with means $(1,0)$ and $(1,4)$, has $J=4\times1=4$, so $16$ is a local minimum four times the best.

On an elongated shape, prototypes that start on the long sides split it the wrong way.

3§10.7 — the Lagrange multiplier for the shares

To maximize $l(\pi,\mu,\Sigma)$ over the shares, the derivation adds $\lambda\big(\sum_k\pi_k-1\big)$ and sets the derivative in each $\pi_j$ to zero. For every $j$ this gives $\sum_i\mathcal N(x_i\mid\mu_j,\Sigma_j)/p(x_i)+\lambda=0$, where the data have $n$ points and the mixture $K$ components.

Find(a) What is $\lambda$?
Given
  • $\sum_{i=1}^n\mathcal N(x_i\mid\mu_j,\Sigma_j)/p(x_i)+\lambda=0$ for $j=1,\dots,K$

  • $\sum_j\pi_j=1$; $p(x_i)=\sum_k\pi_k\mathcal N(x_i\mid\mu_k,\Sigma_k)$

Hint 1/4

The $K$ equations share one unknown; combine them so that the constraint $\sum_j\pi_j=1$ appears.

Hint 2/4

Multiply equation $j$ by $\pi_j$: since $\pi_j\mathcal N(x_i\mid\mu_j,\Sigma_j)/p(x_i)=\gamma(z_{ij})$, it becomes $\sum_i\gamma(z_{ij})+\lambda\pi_j=0$.

Hint 3/4

Sum over $j=1,\dots,K$: each point's responsibilities add to $1$, and $\sum_j\pi_j=1$.

Hint 4/4

$n+\lambda=0$, so $\lambda=-n$ and $\pi_j=N_j/n$.

Show solution

Multiplying by $\pi_j$ turns each condition into responsibilities, which sum neatly.

Multiply by the share

$$\sum_i\gamma(z_{ij})+\lambda\pi_j=0,\ \ \text{i.e. }N_j+\lambda\pi_j=0$$

$\pi_j\mathcal N(x_i\mid\mu_j,\Sigma_j)/p(x_i)$ is the responsibility.

Sum over j

$$\sum_jN_j+\lambda\sum_j\pi_j=n+\lambda=0$$

Every point's responsibilities add to $1$.

$$\lambda=-n\ \Rightarrow\ \pi_j=N_j/n$$

Substituting $\lambda=-n$ into $N_j+\lambda\pi_j=0$ isolates $\pi_j$, and it satisfies the constraint by construction.

Answer $$\boxed{\lambda=-n}$$
Check

The resulting shares add up to $\sum_jN_j/n=1$, so the constraint holds, as it must.

Whenever a constraint says weights add to one, summing the multiplied conditions finds $\lambda$.

4§10.4 — the first EM update of a coin bias

Two runs of $10$ flips were made, each with a hidden coin, A or B with probability $1/2$. They showed $7$ and $2$ heads. EM starts from $\theta_A^{(0)}=0.6$ and $\theta_B^{(0)}=0.4$.

Find(a) What is $\theta_A^{(1)}$?
Given
  • heads $7$ and $2$ out of $10$

  • $\theta_A^{(0)}=0.6$, $\theta_B^{(0)}=0.4$; priors $1/2$

Hint 1/4

The E step first: how likely is coin A for each run? Only then count.

Hint 2/4

$\gamma_{iA}=\frac{a_i/b_i}{1+a_i/b_i}$ with $a_i/b_i=1.5^{2x_i-10}$ for these guesses; $\theta_A^{(1)}=\sum_i\gamma_{iA}x_i\big/\big(10\sum_i\gamma_{iA}\big)$.

Hint 3/4

Heads $7$ and $2$: the ratios are $1.5^4=5.0625$ and $1.5^{-6}=0.0878$.

Hint 4/4

$\gamma_A=(0.8351,\ 0.0807)$, so $\theta_A^{(1)}=6.0068/9.1576=0.656$.

Show solution

With $\theta_A=1-\theta_B$ the ratio is a power of $1.5$.

E step

$$\begin{aligned}&\gamma_{1A}=\frac{5.0625}{6.0625}=0.8351\\ &\gamma_{2A}=\frac{0.0878}{1.0878}=0.0807\end{aligned}$$

With $\theta_A=1-\theta_B$ each head multiplies the ratio by $1.5$ and each tail divides it by $1.5$, so $7$ heads and $3$ tails give $1.5^{4}$, and $2$ and $8$ give $1.5^{-6}$.

M step

$$\theta_A^{(1)}=\frac{7(0.8351)+2(0.0807)}{10(0.8351+0.0807)}=\frac{6.0068}{9.1576}=0.656$$

Each run gives A the fraction $\gamma_{iA}$ of its heads and of its flips, and the M step treats these as if they were observed counts.

Answer $$\boxed{\theta_A^{(1)}=0.656}$$
Check

Coin B gets $2.9932$ heads out of $10.8424$ flips, $0.276$, and the heads add up: $6.0068+2.9932=9$.

Coin A ends below $0.7$ because EM still credits it with $8\%$ of the $2$-head run; the $7$-head run alone gives exactly $0.7$, whatever its share.

5§10.3 — the largest palette that fits a budget

A $500\times400$ RGB image, $8$ bits per channel, must be stored in at most $600{,}000$ bits as a K-means palette plus a fixed-length label per pixel.

Find(a) What is the largest $K$ that fits?
Given
  • $500\times400$ pixels

  • budget: $600{,}000$ bits

  • size $=24K+n\lceil\log_2K\rceil$

Hint 1/4

The label length jumps just after powers of two, so check the values of $K$ on either side of each jump.

Hint 2/4

The condition is $24K+n\lceil\log_2K\rceil\le600{,}000$.

Hint 3/4

$n=200{,}000$; labels of $3$ bits alone already take $600{,}000$ bits.

Hint 4/4

Only $2$-bit labels fit, so $K\le4$, and $K=4$ takes $400{,}096$ bits.

Show solution

The label bits jump in steps, so we test the step edges.

Three-bit labels

$$K=5:\ 120+600{,}000=600{,}120>600{,}000$$

Five colors need $3$-bit labels, which alone fill the $600{,}000$ budget; the palette's $120$ bits push it over.

Two-bit labels

$$K=4:\ 96+400{,}000=400{,}096\le600{,}000$$

Four colors still fit in $2$-bit labels, and every $K$ from $5$ to $8$ costs more than $K=5$ did.

Answer $$\boxed{K=4}$$
Check

Every $K$ from $5$ to $8$ also needs $3$ bits per label and is over budget; $K=4$ is the edge.

Budgets on compressed size are decided by the label length first and the palette second.

D · interleaved 4 questions
1§10.5 — six readings and two models

Six readings are $1,2,3,7,8,9$. Model A is one Gaussian fitted by maximum likelihood. Model B is the mixture $0.5\,\mathcal N(x\mid2,\tfrac23)+0.5\,\mathcal N(x\mid8,\tfrac23)$.

Find
  1. (a) Fit model A: give $\hat\mu$ and $\hat\sigma^2$.

  2. (b) Compare the two densities at $x=5$ and at $x=2$.

  3. (c) Compare the log-likelihoods of the six readings under the two models.

Given
  • readings $1,\ 2,\ 3,\ 7,\ 8,\ 9$

  • model B: $p(x)=0.5\,\mathcal N(x\mid2,\tfrac23)+0.5\,\mathcal N(x\mid8,\tfrac23)$

Hint 1/4

Fit A with the usual estimates, then evaluate both models where the readings are and where they are not.

Hint 2/4

Gaussian MLE: $\hat\mu=\bar x$, $\hat\sigma^2=\frac1n\sum_i(x_i-\bar x)^2$; a log-likelihood is $\sum_i\log p(x_i)$.

Hint 3/4

Readings $1,2,3,7,8,9$: $\bar x=5$ and $\sum_i(x_i-5)^2=58$; model B has means $2$ and $8$ and variance $2/3$.

Hint 4/4

$\hat\sigma^2=9.667$; at $5$, A gives $0.128$ and B $0.0006$; at $2$, A gives $0.081$ and B $0.244$; $l_A=-15.32<l_B=-11.46$.

Show solution

The single Gaussian has closed-form estimates; model B only needs evaluating.

Fit model A

$$\begin{aligned}&\hat\mu=\tfrac{30}{6}=5\\ &\hat\sigma^2=\tfrac{16+9+4+4+9+16}{6}\\ &\quad=\tfrac{58}{6}=9.667\end{aligned}$$

The maximum likelihood estimates divide by $n$.

Densities

$$\begin{aligned}\text{A: }&\mathcal N(5\mid5,9.667)=0.1283\\ &\mathcal N(2\mid5,9.667)=0.0806\end{aligned}$$

A puts its peak at $5$, where there is no reading.

$$\begin{aligned}&\text{B: }p(5)=\mathcal N(5\mid2,\tfrac23)\\ &\qquad=0.00057\\ &p(2)=0.5\,\mathcal N(2\mid2,\tfrac23)\\ &\qquad=0.2443\end{aligned}$$

At $5$ both components are $3$ away; at $2$ only the first one counts.

Log-likelihoods

$$l_A=-\tfrac62\log(2\pi\cdot9.667)-\tfrac62=-15.32$$

For the MLE fit the squared deviations sum to $n\hat\sigma^2$, which gives this closed form.

$$l_B=2\big[2\log0.1154+\log0.2443\big]=-11.46$$

Readings $1,3,7,9$ each have $p=0.1154$, readings $2$ and $8$ have $0.2443$.

Answer $$\boxed{\begin{aligned}&\hat\mu=5,\ \ \hat\sigma^2=9.667\\ &l_A=-15.32,\ \ l_B=-11.46\end{aligned}}$$
Check

Ratio check at $x=5$: $0.1283/0.00057\approx220$, so A believes the gap between the groups is the most likely place for a reading, which the data contradict.

Maximum likelihood fits the model it is given; if that model has one hump, it cannot see two groups.

2§10.6 — a resistor from one of two suppliers

A lab buys $80$ of every $100$ resistors from supplier 1, whose values follow $\mathcal N(100,\ 1)$ in ohms, and the rest from supplier 2, whose values follow $\mathcal N(103,\ 4)$. A resistor from the drawer measures $102$ ohms.

Find(a) What is the probability that the resistor came from supplier 2?
Given
  • supplier 1: share $0.8$, values $\mathcal N(100,1)$

  • supplier 2: share $0.2$, values $\mathcal N(103,4)$

  • measured value: $102$ ohms

Hint 1/4

Two things matter: how common each supplier is, and how typical $102$ ohms is for each.

Hint 2/4

Bayes' rule: $\Pr(2\mid x)=\dfrac{\pi_2\,p_2(x)}{\pi_1\,p_1(x)+\pi_2\,p_2(x)}$.

Hint 3/4

$\pi=(0.8,0.2)$; $102$ is $2$ standard deviations above supplier 1's mean ($\sigma=1$) and half a standard deviation below supplier 2's ($\sigma=2$).

Hint 4/4

$0.2(0.1760)/\big(0.8(0.0540)+0.2(0.1760)\big)=0.0352/0.0784=0.449$.

Show solution

Bayes' rule with two Gaussian likelihoods; the variances differ, so we evaluate both densities.

Densities

$$\begin{aligned}&p_1(102)=\frac{e^{-2}}{\sqrt{2\pi}}=0.0540\\ &p_2(102)=\frac{e^{-1/8}}{\sqrt{8\pi}}=0.1760\end{aligned}$$

$2$ standard deviations out against half of one.

Posterior

$$\begin{aligned}&\Pr(2\mid102)\\ &\quad=\frac{0.2(0.1760)}{0.8(0.0540)+0.2(0.1760)}\\ &\quad=\frac{0.0352}{0.0784}=0.449\end{aligned}$$

Bayes' rule: each density is weighted by its prior share, and the denominator is the total probability of $102$.

Answer $$\boxed{0.449}$$
Check

Odds check: prior odds $0.2/0.8=0.25$ times the density ratio $0.1760/0.0540=3.26$ gives $0.815$, and $0.815/1.815=0.449$.

This is a responsibility under another name: a mixture of two suppliers.

3§10.7 — five fitted mixtures and one table

Mixtures with $K=1,\dots,5$ components were fitted by EM to $120$ training readings, keeping the best of $20$ starts for each $K$. Each fit was then scored by its log-likelihood on the training readings and on $60$ held-out readings.

Find
  1. (a) Which $K$ would the training log-likelihood choose, and why is that no help?

  2. (b) Which $K$ do the held-out readings support?

  3. (c) What do the tiny variances at $K=4$ and $K=5$ tell you?

Given
  • training $l$ for $K=1,\dots,5$: $-326.8,\ \allowbreak -313.7,\ \allowbreak -306.1,\ \allowbreak -301.7,\ \allowbreak -297.1$

  • held-out $l$ for $K=1,\dots,5$: $-159.2,\ \allowbreak -155.4,\ \allowbreak -153.4,\ \allowbreak -157.2,\ \allowbreak -162.3$

  • the fits with $K=4$ and $K=5$ contain components with variances $0.05$ and $0.02$

Hint 1/4

Ask which of the two columns can get worse when the model gets more flexible.

Hint 2/4

A mixture with more components contains every smaller one, so its best training $l$ cannot be lower; a held-out log-likelihood measures fit to new data, as in cross-validation.

Hint 3/4

Training: $-326.8, \allowbreak -313.7, \allowbreak -306.1, \allowbreak -301.7, \allowbreak -297.1$. Held out: $-159.2, \allowbreak -155.4, \allowbreak -153.4, \allowbreak -157.2, \allowbreak -162.3$.

Hint 4/4

Training picks $K=5$ by construction; the held-out column peaks at $K=3$; the tiny variances are components wrapped around a few training readings.

Show solution

The training column cannot decide, so we look for the peak of the held-out column.

Training column

$$-326.8<-313.7<-306.1<-301.7<-297.1$$

It rises at every $K$, so it always points to the largest.

Held-out column

$$-159.2<-155.4<-153.4>-157.2>-162.3$$

It peaks at $K=3$.

The tiny variances

$$\sigma^2=0.05,\ 0.02$$

Such narrow components sit on a few training readings; new readings rarely land exactly there, which lowers the held-out $l$.

Answer $$\boxed{K=3}$$
Check

The readings were simulated from a mixture with three components, so $K=3$ is the right answer here.

Choose $K$ on data the fit has not seen; the training log-likelihood always asks for more components.

4§10.7 — a gradient step against an EM step

A two-component mixture is fitted to $1,3,4,8,9$ with the current parameters $\pi=(0.5,0.5)$, $\mu=(2,8)$ and $\sigma^2=(4,4)$. The responsibilities of component 1 at these parameters are $0.9975,\ \allowbreak 0.9526,\ \allowbreak 0.8176,\ \allowbreak 0.0110,\ \allowbreak 0.0025$.

Find
  1. (a) Compute $\partial l/\partial\mu_1$ at the current parameters.

  2. (b) Take one gradient ascent step with $\eta=0.5$.

  3. (c) Show that the EM update of $\mu_1$ is a gradient step, and find its step size.

Given
  • data $1,\ 3,\ 4,\ 8,\ 9$; $\pi=(0.5,\ 0.5)$, $\mu=(2,\ 8)$, $\sigma^2=(4,\ 4)$

  • $\gamma(z_{i1})=0.9975,\ \allowbreak 0.9526,\ \allowbreak 0.8176,\ \allowbreak 0.0110,\ \allowbreak 0.0025$

  • gradient ascent: $\mu_1\leftarrow\mu_1+\eta\,\partial l/\partial\mu_1$

Hint 1/4

Differentiate the log-likelihood in $\mu_1$, look for the responsibilities in the result, then compare it with the EM formula.

Hint 2/4

In one dimension $\dfrac{\partial l}{\partial\mu_1}=\sum_i\gamma(z_{i1})\dfrac{x_i-\mu_1}{\sigma_1^2}$.

Hint 3/4

With $\mu_1=2$ and $\sigma_1^2=4$ the deviations are $-1,1,2,6,7$ and the weights $0.9975, \allowbreak 0.9526, \allowbreak 0.8176, \allowbreak 0.0110, \allowbreak 0.0025$; $N_1=2.7811$.

Hint 4/4

The gradient is $0.4184$; $\eta=0.5$ gives $\mu_1=2.2092$; EM is the step with $\eta=\sigma_1^2/N_1=1.4383$, which lands at $2.6017$.

Show solution

The gradient already contains the responsibilities, so the two updates can be put side by side.

Gradient

$$\begin{aligned}\frac{\partial l}{\partial\mu_1}&=\tfrac14\big(-0.9975+0.9526\\ &\quad+1.6352+0.0659\\ &\quad+0.0173\big)=0.4184\end{aligned}$$

Each term is $\gamma(z_{i1})(x_i-2)$, divided by $\sigma_1^2=4$.

Gradient ascent

$$\mu_1\leftarrow2+0.5(0.4184)=2.2092$$

Gradient ascent moves along the gradient by a step size we choose; here $\eta=0.5$ is given.

EM as a gradient step

$$\mu_1^{\text{EM}}=\frac{\sum_i\gamma(z_{i1})x_i}{N_1}=\mu_1+\frac{\sum_i\gamma(z_{i1})(x_i-\mu_1)}{N_1}$$

Add and subtract $\mu_1$ inside the weighted mean.

$$=\mu_1+\frac{\sigma_1^2}{N_1}\,\frac{\partial l}{\partial\mu_1}=2+1.4383(0.4184)=2.6017$$

The step size is $\sigma_1^2/N_1=4/2.7811$.

Answer $$\boxed{\begin{aligned}&\partial l/\partial\mu_1=0.4184\\ &\eta=0.5:\ \mu_1=2.2092\\ &\eta_{\text{EM}}=1.4383:\ \mu_1=2.6017\end{aligned}}$$
Check

$2.6017$ is the $\mu_1^{\text{new}}$ of the full EM iteration on the same data in this section, computed there as a weighted mean.

EM chooses its own step size for the means, $\sigma_j^2/N_j$; gradient ascent needs one chosen by hand.

Mistake ledger (21 entries)
⚠ Adding distances instead of squared distances

The nearest prototype is the same either way, so the square is easy to drop when adding up.

wrong$$J=\sum_i{\lVert x_i-\mu_{k(i)}\rVert}$$
right$$J=\sum_i{\lVert x_i-\mu_{k(i)}\rVert}^2$$
⚠ Dividing by n in the M step

The mean of all the data is the familiar formula.

wrong$$\mu_k=\frac1n\sum_ir_{ik}x_i$$
right$$\mu_k=\frac{\sum_ir_{ik}x_i}{\sum_ir_{ik}}$$
⚠ Moving a prototype in the middle of an E step

Updating as soon as a point joins feels faster.

wrong$$\begin{aligned}&\text{assign }x_1,\ \text{move }\mu_k,\\ &\text{assign }x_2,\ \dots\end{aligned}$$
right$$\begin{aligned}&\text{assign every }x_i,\\ &\text{then move every }\mu_k\end{aligned}$$
⚠ Averaging in the K-medoids M step

The K-means M step is the familiar one.

wrong$$\mu_k=\frac{1}{\lvert N_k\rvert}\sum_{x_i\in N_k}x_i$$
right$$\mu_k=\arg\min_{m\in N_k}\sum_{x_i\in N_k}V(x_i,m)$$
⚠ Squaring inside the Manhattan distance

The Euclidean formula is the habit.

wrong$$V(x_i,\mu_k)=\sum_j(x_{ij}-\mu_{kj})^2$$
right$$V(x_i,\mu_k)=\sum_j\lvert x_{ij}-\mu_{kj}\rvert$$
⚠ Taking the cosine itself as the dissimilarity

The cosine is the familiar quantity, but it is large for similar vectors.

wrong$$V=\frac{x^T\mu}{\lVert x\rVert\,{\lVert\mu\rVert}}$$
right$$V=1-\frac{x^T\mu}{\lVert x\rVert\,{\lVert\mu\rVert}}$$
⚠ Using log2 K without rounding up

The formula looks finished before the ceiling.

wrong$$n\log_2K$$
right$$n\lceil\log_2K\rceil$$
⚠ Forgetting the palette

The labels are the part that grows with the image.

wrong$$n\lceil\log_2K\rceil$$
right$$24K+n\lceil\log_2K\rceil$$
⚠ Counting 8 bits per pixel for a color image

8 bits is the size of one channel.

wrong$$8n$$
right$$24n$$
⚠ Forgetting to normalize the posterior

The unnormalized product already looks like a probability.

wrong$$\gamma_{iA}=\theta_A^{x_i}{(1-\theta_A)}^{F-x_i}$$
right$$\gamma_{iA}=\frac{a_i}{a_i+b_i}$$
⚠ Dividing coin A's heads by all the flips

Each run has F flips, so the total number of flips looks like the right denominator.

wrong$$\theta_A=\frac{\sum_i\gamma_{iA}x_i}{F\cdot(\text{number of runs})}$$
right$$\theta_A=\frac{\sum_i\gamma_{iA}x_i}{F\sum_i\gamma_{iA}}$$
⚠ Dropping the tails factor

The heads are what the question counts.

wrong$$a_i=\theta_A^{x_i}$$
right$$a_i=\theta_A^{x_i}{(1-\theta_A)}^{F-x_i}$$
⚠ Reading a mixture as a sum of variables

The weights look like coefficients of a linear combination.

wrong$$X=0.6X_1+0.4X_2$$
right$$X=X_j\ \text{with probability }\pi_j$$
⚠ Taking the logarithm inside the sum

The log of a product splits, and the habit carries over.

wrong$$\log\sum_j\pi_j\mathcal N_j(x)=\sum_j\pi_j\log\mathcal N_j(x)$$
right$$\log\sum_j\pi_j\mathcal N_j(x)\ \text{does not split}$$
⚠ Weights that do not add up to one

Each weight looks reasonable on its own.

wrong$$\pi=(0.5,\ 0.3,\ 0.3)$$
right$$\textstyle\sum_j\pi_j=1,\ \text{e.g. }\pi=(0.5,\ 0.3,\ 0.2)$$
⚠ Dropping the shares from the responsibility

The densities alone look like the whole story.

wrong$$\gamma(z_j)=\frac{\mathcal N_j(x)}{\sum_k\mathcal N_k(x)}$$
right$$\gamma(z_j)=\frac{\pi_j\mathcal N_j(x)}{\sum_k\pi_k\mathcal N_k(x)}$$
⚠ Normalizing over the points instead of the components

A table of products has two directions to sum in.

wrong$$\gamma(z_{ij})=\frac{\pi_j\mathcal N_j(x_i)}{\sum_{i'}\pi_j\mathcal N_j(x_{i'})}$$
right$$\gamma(z_{ij})=\frac{\pi_j\mathcal N_j(x_i)}{\sum_k\pi_k\mathcal N_k(x_i)}$$
⚠ Giving the point to the nearest mean

That is what K-means does.

wrong$$\gamma(z_j)=1\ \text{for the nearest }\mu_j$$
right$$\gamma(z_j)\ \text{also depends on }\pi_j\text{ and }\Sigma_j$$
⚠ Dividing by n instead of N_j

The plain mean divides by the number of points.

wrong$$\mu_j^{\text{new}}=\frac1n\sum_i\gamma(z_{ij})\,x_i$$
right$$\mu_j^{\text{new}}=\frac1{N_j}\sum_i\gamma(z_{ij})\,x_i$$
⚠ Centering the covariance on the old mean

The old mean is the one already on the page.

wrong$$\Sigma_j^{\text{new}}=\tfrac1{N_j}\textstyle\sum_i\gamma(z_{ij})(x_i-\mu_j^{\text{old}}){(x_i-\mu_j^{\text{old}})}^T$$
right$$\Sigma_j^{\text{new}}=\tfrac1{N_j}\textstyle\sum_i\gamma(z_{ij})(x_i-\mu_j^{\text{new}}){(x_i-\mu_j^{\text{new}})}^T$$
⚠ Averaging the counts over K

The shares are one per component.

wrong$$\pi_j^{\text{new}}=N_j/K$$
right$$\pi_j^{\text{new}}=N_j/n$$
Formula card
K-means
$$\begin{aligned}J&=\textstyle\sum_i\sum_kr_{ik}{\lVert x_i-\mu_k\rVert}^2\\ \text{E: }r_{ik}&=1\text{ for the nearest }\mu_k\\ \text{M: }\mu_k&=\frac{\sum_ir_{ik}x_i}{\sum_ir_{ik}}\end{aligned}$$

$K$ fixed; a point moves only to a strictly nearer prototype

K-medoids
$$\begin{aligned}\tilde J&=\textstyle\sum_i\sum_kr_{ik}V(x_i,\mu_k)\\ \mu_k&=\arg\min_{m\in N_k}\textstyle\sum_{x_i\in N_k}V(x_i,m)\end{aligned}$$

any dissimilarity $V$; prototypes are data points

Dissimilarities
$$\begin{aligned}&\text{Manhattan: }\textstyle\sum_j\lvert x_{ij}-\mu_{kj}\rvert\\ &\text{cosine: }1-\frac{x_i^T\mu_k}{\sqrt{(x_i^Tx_i)(\mu_k^T\mu_k)}}\end{aligned}$$

the cosine ignores vector length

Compressed image
$$24K+n\lceil\log_2K\rceil\ \text{ bits, against }24n$$

RGB, $8$ bits per channel, fixed-length labels

EM for two coins
$$\begin{aligned}a_i&=\theta_A^{x_i}{(1-\theta_A)}^{F-x_i}\\ \gamma_{iA}&=\frac{a_i}{a_i+b_i}\\ \theta_A^{\text{new}}&=\frac{\sum_i\gamma_{iA}x_i}{F\sum_i\gamma_{iA}}\end{aligned}$$

each coin picked with probability $1/2$; $b_i$ as $a_i$ with $\theta_B$

Mixture of Gaussians
$$\begin{aligned}p(x)&=\textstyle\sum_j\pi_j\mathcal N(x\mid\mu_j,\Sigma_j)\\ l&=\textstyle\sum_i\log p(x_i)\end{aligned}$$

$\pi_j\ge0$, $\sum_j\pi_j=1$; $p(z_j=1)=\pi_j$, $p(x\mid z_j=1)=\mathcal N(x\mid\mu_j,\Sigma_j)$

Mixture moments and parameter count
$$\begin{aligned}E[X]&=\textstyle\sum_j\pi_j\mu_j\\ \#&=(K-1)+Kp\\ &\quad+K\tfrac{p(p+1)}2\end{aligned}$$

count with full covariance matrices

Responsibility
$$\gamma(z_{ij})=\frac{\pi_j\mathcal N(x_i\mid\mu_j,\Sigma_j)}{\sum_k\pi_k\mathcal N(x_i\mid\mu_k,\Sigma_k)}$$

current or known parameters; each point's add up to $1$

EM for a Gaussian mixture
$$\begin{aligned}N_j&=\textstyle\sum_i\gamma(z_{ij}),\ \ \pi_j=N_j/n\\ \mu_j&=\tfrac{1}{N_j}\textstyle\sum_i\gamma(z_{ij})x_i\\ \Sigma_j&=\tfrac{1}{N_j}\textstyle\sum_i\gamma(z_{ij})\\ &\quad\times(x_i-\mu_j){(x_i-\mu_j)}^T\end{aligned}$$

the new $\mu_j$ inside $\Sigma_j$; repeat until $l$ settles

Checks for an EM iteration
$$\begin{aligned}&\textstyle\sum_jN_j=n\\ &\sum_j\pi_j\mu_j=\bar x\\ &l^{\text{new}}\ge l^{\text{old}}\end{aligned}$$

any mixture of Gaussians

Check yourself

Close the page and write down from memory:

  • the K-means objective and its two steps;
  • the K-medoids M step and the two dissimilarities;
  • the size of an image compressed with K colors;
  • the E and M steps for two hidden coins;
  • the mixture density, its latent variable and its log-likelihood;
  • the responsibility formula;
  • the EM updates for a Gaussian mixture, and where the share update comes from.

Then reopen the page and compare; whatever is missing is your reread list.

  • Run K-means by hand on a few points, keep track of $J$, and give a start that stops at a worse split?

    c-kmeans

  • Pick the medoid of a small cluster under the Manhattan distance, and assign a vector by cosine dissimilarity?

    c-kmedoids

  • Compute the size of a compressed image for a given $K$, with the ceiling right?

    c-compression

  • Do one EM iteration for two hidden coins, including the credited heads and flips?

    c-coins

  • Write a mixture's density, latent variable and log-likelihood, and count its parameters?

    c-mixture

  • Compute a responsibility, and explain why it can disagree with the nearest mean?

    c-responsibility

  • Do one full EM iteration for a one-dimensional mixture, derive $\pi_j=N_j/n$, and check that $l$ went up?

    c-em-gmm

Glossary (26 terms)
clusteringkümeleme

Splitting unlabeled data into groups of similar points, with no labels to learn from.

clusterküme

One of the groups a clustering method finds.

K-meansK ortalamalar

A clustering method that alternates assigning each point to its nearest prototype and moving each prototype to the mean of its points, lowering the distortion $J$ at every step.

prototypeprototip

The vector $\mu_k$ that represents cluster $k$; in K-means it is the cluster's mean.

distortion measure

The K-means objective $J$: the total squared distance of the points to the prototypes of their clusters.

hard assignment

Each point belongs to exactly one cluster, coded by $r_{ik}\in\{0,1\}$.

K-medoids

A variant of K-means that uses a general dissimilarity $V$ and requires each prototype to be one of the data points.

medoid

The member of a cluster with the smallest total dissimilarity to the other members.

dissimilaritybenzemezlik ölçüsü

A nonnegative score $V(x,\mu)$ that is small for similar vectors, such as a distance.

Manhattan distanceManhattan uzaklığı

The sum of absolute coordinate differences, $\sum_j\lvert x_j-\mu_j\rvert$; far points count less than under squared distance.

cosine dissimilaritykosinüs uzaklığı

One minus the cosine of the angle between two vectors; it ignores their lengths.

outlieraykırı değer

A point far away from the rest of the data.

image segmentationgörüntü bölütleme

Splitting an image into regions of similar appearance, here by clustering pixel colors.

görüntü sıkıştırma

Storing an image in fewer bits; with K-means, as $K$ colors plus one label per pixel.

latent variablegizli değişken

A variable of the model that is never observed, such as the coin behind a run or the component behind a point.

tam veri

The observed data together with the values of the latent variables.

missing dataeksik veri

Values that were not recorded; here, the latent labels, so only the observed part is available.

mixture of GaussiansGauss karışım modeli

The density $p(x)=\sum_j\pi_j\mathcal N(x\mid\mu_j,\Sigma_j)$: pick component $j$ with probability $\pi_j$, then draw from its Gaussian.

mixing coefficientkarışım katsayısı

The weight $\pi_j$ of component $j$ in a mixture; the weights are nonnegative and add up to $1$.

responsibility

The posterior probability $\gamma(z_{ij})=p(z_{ij}=1\mid x_i)$ that component $j$ produced the point $x_i$.

soft assignment

An assignment of each point to every cluster with a probability, as the responsibilities do.

beklenti maksimizasyonu

An iterative method for maximum likelihood with latent variables: compute their posteriors (E step), then maximize the expected complete-data log-likelihood (M step).

effective number of points

$N_j=\sum_i\gamma(z_{ij})$, the number of points component $j$ accounts for; usually not a whole number.

local minimumyerel minimum

A state that no single step of the method can improve, although a better one exists elsewhere.

Lagrange multiplierLagrange çarpanı

The extra variable $\lambda$ that handles an equality constraint, here $\sum_j\pi_j=1$.

singular solution

A degenerate maximum of a mixture likelihood in which one component shrinks onto a single data point and its variance goes to zero.

What comes next
§11 · Feature selection

Here every point kept all of its features, and we asked which group it belongs to. Next the question turns to the features themselves: which of them are worth keeping at all.

Sources
  • textbookT. Hastie, R. Tibshirani, J. Friedman, The Elements of Statistical Learning, Springer (course textbook) The weekly line names no chapter of the book, so no section numbers are cited here.
  • course materialEEE 485 lecture slides and lecture notes, chapter 10: Clustering Scope, order of topics and notation (r_ik, mu_k, J, V, J tilde, N_k, theta_A, theta_B, pi_j, z, gamma(z_ij), N_j, l) follow these materials; all explanations, data, figures and exercises here are original.
  • course materialEEE 485 syllabus page on STARS, Fall 2026-27, printed 21 September 2026 Assessment weights, the weekly topic list and the recommended books.
  • textbookC. M. Bishop, Pattern Recognition and Machine Learning, Springer One of the recommended books on the syllabus; the lecture's K-means and EM illustrations come from it.
  • standard resultC. B. Do and S. Batzoglou, a primer on the EM algorithm, Nature Biotechnology 26(8), 2008 The article the lecture cites for its two-coin experiment; the coin data on this page are new.
  • standard resultBayes' rule, the binomial and Gaussian distributions, and Lagrange multipliers Standard results used in the derivations. Every number and figure on this page was computed for it.

Spotted something missing or wrong? tell us · share your own notes or an old exam.

Last updated .