⌂ Course home
Artificial Intelligence and Machine Learning · Lecture 16 of 20

Clustering · Part 1

K-Means

Find groups in unlabeled observations, fit centroids and decide how many groups are useful.

7.1 Clustering
7.2 K-Means
7.2.1 Initialization
7.2.2 Number of clusters
7.1 · Clustering

Clustering finds groups in unlabeled data

Clustering is an unsupervised learning task. Measure each item, then group similar items using those measurements. The data come without class labels.

Sort produce

Group fruit by size, shape and color to identify batches that may need different handling.

Plan delivery routes

Group nearby stops into service zones that can be assigned to different drivers.

Monitor machinery

Group sensor readings into operating patterns and flag isolated readings for inspection.

A cluster can help you sort, plan or investigate. A person still has to decide whether the grouping is useful for the task.

7.1 · Clustering

Three ways to group the same observations

Different algorithms describe the structure of the same cloud in different ways.

K-Means

Assign each point to the nearest cluster mean. The crosses are the means.

Gaussian Mixture Clustering

Give each point a probability of belonging to each overlapping component.

Cut

Hierarchical Clustering

Merge nearby groups into a tree. A horizontal cut chooses a partition.

Each dot is an observation. These methods return a hard partition, membership probabilities, or a tree of nested groups.

7.1 · Clustering

PCA changes how we represent the same observations

Parts 4 and 5 use principal component analysis (PCA) to study the features and prepare them for further analysis.

PC1

Feature analysis with principal components

Find the directions of greatest spread. Projecting onto one direction gives one score per point.

PCA scoresWhitened scores

PCA for preprocessing

Transform the features before another method sees them. Whitening rescales the principal scores.

The three clustering methods group observations. PCA describes their variation and can be used before a clustering step.

Clustering · Part 1

What we will learn

  1. Assign points to centroids and recompute the means.
  2. Explain why distortion falls as more centroids are allowed.
  3. Use an elbow or mean silhouette to compare useful values of K.
7.1 · Clustering

Could we group apples and pears without labels?

Imagine a basket of mixed fruit. Shape, color, and taste give us clues about which pieces belong together, even before anyone names the groups.

In classification, a target label tells us the category to learn. In clustering, shape, color, and taste are all features. The task is to discover groups whose members resemble one another and differ from those in other groups.

7.1 · Clustering

From measurements to feature vectors

Each row is one fruit. The two measurement columns give m=2 features per fruit.

Measurements for three pieces of fruit
ObservationWeight (g) X1Diameter (mm) X2
x114570
x217876
x312558
X=(X1,…,Xm),xi=(xi1,…,xim)∈ℝm

Xj is the j-th feature. The entry xij is feature j of observation i. Here x21=178 g, and the whole second row is x2=(178,76). A distance compares two such feature vectors.

7.1 · Clustering

How many groups do you see?

Inspect this unlabeled cloud. Which points seem close to one another, and where are the gaps?

7.1 · Clustering

What makes a collection of points a cluster?

Points within a group should be similar. Points in different groups should be relatively dissimilar.

C1,…,CK

A grouping depends on which features and distance are useful for the task. With no supplied targets, accuracy against known labels is unavailable during fitting. Domain knowledge and geometric checks help interpret the result.

7.2 · K-Means

Represent each group by its centroid

Assume there are K groups. Represent group k by an average observation, its centroid μk.

μk∈ℝm,k=1,…,K

A centroid has the same m coordinates as a data row. It can lie between observations. K-means learns the centroids together with the group assignments.

7.2 · K-Means

One-hot encoding

With K=3 clusters, give each cluster a column. Put a 1 in the assigned cluster’s column and 0 in the other two.

Fruit x2

Assigned to C2

One-hot row r2
C1C2C3
010
rik={1if xi∈Ck0otherwise,∑k=1Krik=1

The membership vector ri=(ri1,…,riK) is the row for observation i. The collection 𝒓={r1,…,rn} contains one membership vector for each of the n observations. In r22, the first 2 identifies the fruit and the second identifies the cluster.

7.2 · K-Means

What are the two K-means steps trying to minimize?

From initial centroids, assign points to the nearest centroid, then recalculate each centroid as its group mean. Repeat to reduce the distortion J.

(𝝁^,𝒓^)=argmin𝝁∈ℝK×m, 𝒓∈{0,1}n×KJ(𝝁,𝒓)=argmin𝝁∈ℝK×m, 𝒓∈{0,1}n×K∑i=1n∑k=1Krik‖xi−μk‖2subject to ∑k=1Krik=1(i=1,…,n)

The double sum adds the squared distance of each of the n observations to its assigned centroid. The constraint keeps each row one-hot. The hats mark the minimizing centroids and assignments.

7.2 · K-Means

Which terms enter the distortion?

Fix the centroids at μ1=1 and μ2=5. Move the observation xi to see its squared distances, membership row and contribution Ji.

At position 0, choose cluster 1

Centroid 1 is closer, so its entry in the membership row is 1.

‖xi−μ1‖2=(0−1)2=1‖xi−μ2‖2=(0−5)2=25ri=(1,0)Ji=∑k=12rik‖xi−μk‖2=1×1+0×25=1

Each flag rik is either 0 or 1, so differentiation does not directly choose the assignment. Add the selected squared distances Ji over all observations to get J.

7.2 · K-Means

Step 1 fixes the centroids

To minimize J with the centroids fixed, choose the membership flags rik∈{0,1}. These are discrete choices, so the usual method of setting a derivative to zero does not apply directly.

𝒓^=argmin𝒓∈{0,1}n×KJ(𝝁,𝒓)=argmin𝒓∈{0,1}n×K∑i=1n∑k=1Krik‖xi−μk‖2subject to ∑k=1Krik=1(i=1,…,n)

For each observation, compare the squared distances and put its only 1 in the column of the nearest centroid.

7.2 · K-Means

Pick the smallest distance in each row

For observation i, all but one flag are zero. Its contribution to J is the squared distance to the centroid whose flag is 1, so choose the smallest squared distance.

rik={1if k=argminℓ∈{1,…,K}‖xi−μℓ‖20otherwise

Read the argmin as “the index ℓ with the smallest distance”. If the current centroid is tied for closest, keep that assignment. Use a fixed order for any other tie.

7.2 · K-Means

Step 2 fixes the assignments

Keep the assignments fixed and find the new centroid μ^k for each nonempty cluster Ck.

𝝁^=argmin𝝁∈ℝK×mJ(𝝁,𝒓)=argmin𝝁∈ℝK×m∑i=1n∑k=1Krik‖xi−μk‖2μ^k=∑i=1nrikxi∑i=1nrik=∑i:xi∈Ckxi|Ck|

Only points with rik=1 contribute to cluster k’s squared distances. The update adds those same points and divides by their count |Ck| to get the cluster mean.

7.2 · K-Means

Why does the mean minimize distortion?

Differentiate with respect to μk. At the minimum, set the gradient to zero and collect the terms containing μk.

∂J∂μk=2∑i=1nrik(μk−xi)∂J∂μk=0⟹μk∑i=1nrik=∑i=1nrikxi⟹μk=∑i=1nrikxi∑i=1nrik

The numerator adds the observations assigned to Ck, and the denominator counts them. Dividing gives the average of all observations in cluster Ck. For a nonempty cluster, this mean uniquely minimizes the convex quadratic. An empty cluster needs a separate rule.

7.2 · K-Means

Move a centroid to its group mean

Drag the trial center for the points 0, 2 and 4. Where does their sum of squared distances reach its minimum?

J = 0 + 4 + 16 = 20

Try moving the centroid closer to the mean at 2.

7.2 · K-Means

Why alternate the two K-means steps?

One update of 𝒓 already finds the best assignments for the current centers. One update of 𝝁 already finds the best centers for the current assignments.

Assign → assign again

The centers stayed put. The same distances give the same memberships.

Average → average again

The groups stayed the same. Averaging the same members gives the same centroids.

Moving the centers can change the nearest cluster. Changing the members can change the mean.

7.2 · K-Means

Why K-means eventually stops

With finitely many data points, there are finitely many ways to assign them to K clusters. Each round either changes assignments and lowers J, or leaves the assignments stable.

Assignments change

Every point that switches goes to a strictly closer center. This lowers the distortion J.

Centroids move to means

The mean is the best center for a nonempty cluster, so this step cannot raise J.

No assignments change

The same members give the same means. Both the assignments and the centers are stable.

During a tie, keep the current assignment if it is one of the nearest. Keep the previous center for an empty cluster. Each partition has a fixed distortion once its means are computed, so a strictly improving run cannot revisit it.

7.2 · K-Means

Watch the centroids settle

Advance through the five frames. Track one cross and the points with its color.

7.2 · K-Means

Inspect assignment and movement separately

Use Step to see which changes first. Then try a different initialization or change K.

7.2.1 · Initialization

A stable fit can miss the global minimum

Each update improves one part of the fit with the other part fixed. A different partition may require changing assignments and centers together.

012781213

Start at 7 and 12 → final J = 53.7

The left cluster keeps five points. Its mean is 3.6 and the right mean is 12.5.

012781213

Start at 0 and 13 → final J = 28

The left cluster keeps three points. Its mean is 1 and the right mean is 10.

Same observations and same K=2. Both fits are stable, but J=28 beats J=53.7. Try several starting points and keep the lowest distortion you actually find.

7.2.2 · Number of clusters

Why does distortion keep falling with K?

One centroid summarizes the whole dataset. More centroids make it possible to fit smaller groups more tightly.

The best achievable distortion cannot increase with K. At K=n, placing one centroid at each observation gives J=0. That solution remembers each observation separately. Individual runs can end at higher local solutions.

7.2.2 · Number of clusters

What changes from one cluster to one per point?

Choose K from 1 to n and press Run K-means. Compare the partition, the centroids and distortion on the same 12 observations.

7.2.2.1 · Elbow method

Elbow method

Fit the same data for each K. Look for a bend where adding clusters starts to buy much less reduction in distortion.

7.2.2.1 · Elbow method

Find the elbow by measuring the bend

Draw a line between the first and last tested points. For each intermediate K, compute g(K)=Jline(K)−J(K), then pick the largest positive gap.

K = 2 gives a gap of 17.5

The line is at 54.5 and the fitted distortion is 37. Subtract the distortion from the line height. The candidate gaps are 17.5, 25, and 13.5, so the largest is at K = 3.

020406012345KJGap 17.5

The dashed line gives Jline(K). In this example, it drops from 70 to 8 in four equal steps of 15.5. Small gaps throughout mean there is little evidence of an elbow.

7.2.2.2 · Silhouette method

Silhouette method

To compare choices of K, first score each point. Start with aK(xi), the average squared distance from xi to the other points in its own cluster.

aK(xi)=d¯(xi,C(xi))=1|C(xi)|−1∑xi′∈C(xi)i′≠i‖xi′−xi‖2

C(xi) is the cluster of xi. The index i′ identifies another observation. Exclude xi itself, so the denominator is the cluster size minus 1.

7.2.2.2 · Silhouette method

Which other cluster is the best alternative?

For each other group, compute the average squared distance from xi to its members. Keep the smallest of those averages as bK(xi).

bK(xi)=minCk≠C(xi)d¯(xi,Ck)=minCk≠C(xi)1|Ck|∑xi′∈Ck‖xi′−xi‖2

Ck is another cluster and |Ck| counts its members. First average within each cluster, then compare the averages across clusters.

7.2.2.2 · Silhouette method

What does the sign of a silhouette score tell us?

A positive score favors the current cluster. A score near zero signals a close call. A negative score means another cluster is closer on average.

s(xi)={bK(xi)−aK(xi)max(aK(xi),bK(xi))if |C(xi)|>1 and max(aK(xi),bK(xi))>00otherwise,s(xi)∈[−1,1]

The gap can be no larger in magnitude than the larger average. Dividing by that average scales the score to [−1,1]. A point alone in its cluster gets 0 by convention. Use 0 when both averages are zero. Compare partitions with 2≤K<n.

7.2.2.2 · Silhouette method

Work out the silhouette of one point

How well does the ringed point fit its current cluster? Compare its average squared distance to its own cluster with the smallest average for the other clusters.

2448810Selected point

Labels show squared distances to the selected point.

Own cluster
aK(xi)=2+42=3
Other cluster A
4+82=6
Other cluster B
8+102=9
Best alternative
bK(xi)=min(6,9)=6
s(xi)=bK(xi)−aK(xi)max(aK(xi),bK(xi))=6−36=0.5

A positive score means the point is closer on average to its own cluster than to the best alternative.

7.2.2.2 · Silhouette method

Inspect one observation at a time

Change the inspected point. Compare its own-group average, nearest alternative and silhouette. Which points sit near a boundary?

7.2.2.2 · Silhouette method

Which K has the highest average silhouette?

For each tested K, average the silhouette scores of all n observations. For example, if K=2,3,4 give means 0.46, 0.61, and 0.52, choose K=3.

s¯K=1n∑i=1ns(xi),SC=maxKs¯K

s¯K is the average silhouette score for one fitted partition. The silhouette coefficient SC is the highest of these averages. Choose the tested number of clusters K that gives that highest average.

7.2.2.2 · Silhouette method

Choose K by comparing entire partitions

Switch between distortion, mean silhouette and the partition. Does the elbow agree with the largest mean silhouette?

Clustering · Part 1

What to remember

  1. Assign points to centroids and recompute the means.
  2. Explain why distortion falls as more centroids are allowed.
  3. Use an elbow or mean silhouette to compare useful values of K.