What can we learn when there is no target to predict?
How can we turn similarity into groups?
How do we choose a useful number of clusters?
What if our clusters miss the similarity we care about?
What can we learn without targets?
Organizing an online store
Problem: Help customers browse furniture that has no group labels.
We know how to train a classifier but what would its target be?
Unsupervised learning
Our supervised models learn from features \(X\) and targets \(y\).
Here we have \(X\), without a target column. We can instead look for useful structure:
Clustering: which examples form similar groups? For the furniture store, discover groups without supplied category labels.
Representation learning: can we describe the data using useful new features?
Dimensionality reduction seeks a representation with fewer features.
Representation learning: clicks to interests
Problem: Thousands of article-click features are difficult to interpret; total clicks hide interests.
Instead learn a smaller set of interest dimensions from patterns of articles read together.
Image created by GPT-6.1 Sol Light
How can we group similar examples?
Your turn: group the foods
With a neighbour (2 minutes): Propose two useful groupings. For each, explain its purpose and the features you would use. Would raw pixels capture what you mean by “similar”?
The goal of clustering
Group similar examples without predefined group labels.
Within a cluster: examples should be similar.
Between clusters: examples should differ.
What counts as “similar” depends on the features, distance, and purpose, as in your food groupings.
The algorithm returns memberships; we interpret what the groups mean.
Using the distance tools we already know
Represent each food by numeric features and choose \(k\) groups.
KNN taught us to compare points using Euclidean distance.
Represent each group by a centre; assign points to the nearest one.
Use the group’s mean as its centre.
But we need groups to calculate centres, and centres to assign groups.
The K-Means algorithm
Input: features \(X\) and \(k\). Output:\(k\) centroids and one label per example.
Choose \(k\) initial centres.
Assign: send each point to its nearest centre.
Update: move each centre to the mean of its assigned points.
Repeat assignment and update until the centres change very little, or the iteration limit is reached.
The number of clusters stays fixed during a run.
Your turn: act out K-Means
Pick centres: three volunteers mark the initial centre positions.
Assign: raise your hand when your nearest centre is called.
Update: move each centre to its group’s average row/column position.
Repeat: reassign, then update.
Keep everyone else’s position fixed. A centre can lie between seats.
Discuss: what happened during K-Means?
Did anyone switch clusters in the second round? Why?
When do you think K-Means should stop?
Could we get a different result with different initial centres?
Interactive check: assign, average, repeat
Before Assign: Which centre will the highlighted point join? Before Update: Where will its centre move?
Assign each point to its nearest centre, then move each centre to its cluster’s mean.
K-Means in scikit-learn
from sklearn.cluster import KMeanskm = KMeans(n_clusters=3, random_state=42)labels = km.fit_predict(X) # no target ycentres = km.cluster_centers_new_labels = km.predict(X_new)
predict assigns new examples to their nearest learned centre.
Your turn: predict a new example
Which cluster gets the query point? Explain using distance.
Does predict move either centre? What if we instead refit on the expanded dataset?
iClicker: assignments and prediction
Select all true statements.
A centroid must coincide with an observed example.
A point may change clusters during fitting.
\(k\) increases automatically as fitting proceeds.
predict assigns a new point without moving the learned centres.
Renaming cluster IDs leaves the grouping unchanged.
Initialization: same data, different groups
We have fixed \(X\) and \(k\). Does that determine a single final result? Which initilization is better here?
Getting a better starting point
Problem: one initialization can produce a poor solution.
K-Means++ spreads out the initial centres.
Multiple starts try different initializations and retain the lowest within-cluster sum of squares.
A fixed random_state makes the result reproducible.
If you use n_init=10: try ten starts, then retain the best run.
iClicker: has K-Means found the best solution?
The centres have stopped moving. Which statement follows?
This is the globally smallest possible sum of squared distances.
Every other initialization must produce the same grouping.
Another assignment/update cycle will leave this solution unchanged, using the same tie rules.
The chosen \(k\) must be appropriate for the application.
Scaling: should changing units change the groups?
We cluster customers using age in years and spending in dollars.
Changing spending to thousands of dollars changes its contribution to Euclidean distance even though the customers are unchanged.
Use the preprocessing tools we know: usually scale numeric features before K-Means.
Fit the scaler on the fitting data and apply the same transformation to new examples.
K-Means: strengths and limitations
Strength
Limitation
Simple and usually efficient
We must choose \(k\)
Centres summarize groups compactly
Means are sensitive to outliers
Effective for compact, roughly spherical, similarly sized groups
Curved or elongated groups can be split unnaturally
Assigns every example to a group
No explicit rejection of noise or ambiguous points
Initialization and feature representation affect the result.
How many groups should we create?
How many clusters?
K-Means asks us to choose \(k\)before fitting.
Too few: we may merge groups whose differences matter.
Too many: we may split useful groups into small fragments.
There may not be one correct \(k\); the intended use and domain knowledge matter.
How can we compare candidate values of \(k\)?
Evidence for choosing \(k\)
Quantitative evidence
Elbow plot: how much does another centre reduce inertia?
Silhouette: how cohesive and separated are the groups?
Qualitative evidence
Inspect examples: what do members of each group share?
Are the groups useful for the intended task?
Use numerical diagnostics alongside interpretation.
Measuring fit with inertia
We can fit K-Means for several values of \(k\). How can we compare them?
Inertia is the sum of squared distances to assigned centroids: