π«§ Clustering
π΅οΈ Discovering groups without labels
Your camera app automatically puts all the photos of the same person together, without you ever typing in a name. Every Monday, Spotify has a "Discover Weekly" ready for you with songs you have never heard, but that fit your taste suspiciously well. And a web shop sends you exactly the one offer that matches your buying behavior. Behind all these examples sits one and the same idea: an algorithm that discovers groups by itself in a pile of data, without a human explaining beforehand which groups exist. That idea is called clustering, and that is what this chapter is about.
π Labels are expensive
In the previous chapters on naive Bayes, nearest neighbors, decision trees and regression we always worked with labeled data: every example already came with the right answer. Every piece of fruit carried its label (π apple, π pear or π orange), every email was already marked as spam or not, and for every student room we knew the rent. These are all examples of supervised learning: a "supervisor" (a human) looked at every example beforehand and gave it the right answer, and the model learns to imitate those answers.
But in the real world labels are often scarce and expensive. If you want a model that assesses X-rays, a doctor first has to look at thousands of images one by one and label them ("healthy", "pneumonia", ...): weeks of work by an expensive specialist. And sometimes there is not even a good label. How would you label somebody's taste in music? "Likes pop"? Most people listen to a mix, and many songs fit in no box at all.
π§© Learning without examples
People group things all the time without anybody explaining the categories to them. If you get a box with a hundred unknown photos and are asked to sort them, you automatically make little piles: beach with beach, city with city, group photo with group photo. Nobody has to say beforehand which piles there should be; you simply look at what resembles what.
That is exactly what you have a computer do with unsupervised learning: the model only gets the features of the data points, no labels, and has to discover the structure in them by itself.
Unsupervised learning is a form of machine learning in which the model discovers structure, patterns or groups in data without using labels. The model only gets the features of the data points, not the "right answer".
The most widely used form of unsupervised learning is clustering: dividing data points into groups so that things that resemble each other end up together. It is behind a surprising amount of what is called "AI" today:
- πΈ Photos by face: your phone measures how much faces resemble each other (with features that a neural network computes) and puts similar faces together. Afterwards you only give each group a name.
- π΅ Music and recommendations: listeners with similar listening behavior end up in the same group. What your group likes to hear and you do not know yet is a good recommendation. In practice, streaming services combine this with other personalization techniques (external link), but grouping is the intuition behind it.
- π Customer segments: a web shop discovers groups such as "loyal bulk buyers" and "occasional bargain hunters" by itself, without anybody ever labeling a customer.
- πΊ Shards and texts: archaeologists group pottery shards by shape and wall thickness to discover types of pottery, literary scholars group texts by stylistic features (sentence length, word choice) to see which texts belong together, and historians look for recurring themes in thousands of newspaper articles this way.
- 𧬠Genes and patients: biologists discover groups of genes that become active together, and doctors discover subtypes of a disease in patients who got the same diagnosis on paper.
ποΈ What is clustering?
π² Bike sharing in Leuven
To see how a computer discovers groups, we take an example in which you can literally see the groups. A bike-share company wants to put a few stations in Leuven where students can pick up a bike. The company collected the addresses of 150 students who showed interest. Every dot on the simplified map below is one student room (a kot, as students in Leuven call it).
How would you divide these rooms into groups? You probably immediately see three neighborhoods where many students live, and that is where you would put the stations. Nobody told you how many groups there are or where they lie: you simply saw them. Below is the same map, but now an algorithm has divided the rooms into three groups. Every color is a group, and the β sign is the center of that group: the place where the station goes.
The algorithm only got the positions of the rooms, no labels, and still it found the same three neighborhoods you saw. We call such a group a cluster.
Clustering is automatically grouping data points into clusters, so that data points within a cluster resemble each other more than points from other clusters. Unlike with classification, the groups are not fixed beforehand with labels, but discovered by the algorithm itself.
The difference from classification is subtle but important. With classification you know which classes exist (apple, pear, orange) and the model learns to put new points into those classes. With clustering you do not know beforehand which groups there are. The algorithm finds them, and you look afterwards at what each group means ("this is the neighborhood around the campus").
π Measuring similarity
On the map, "resembling each other" simply means "lying close to each other". Just as with nearest neighbors, the algorithm measures similarity with a distance measure, usually the Euclidean distance: the straight-line distance you would measure with a ruler between two dots. The smaller the distance between two points, the more they resemble each other.
The nice thing is that the axes of the chart can be anything. On the map they are kilometers to the east and to the north, but they could just as well be the tempo and the energy of a song, or the sentence length and word choice of a text. As long as you can write every data point as a list of numbers, you can measure distances between them and so look for clusters in them as well. Later in this chapter we do that with the colors of a photo.
π― K-means clustering
π― The goal: everyone close to a station
The best-known clustering algorithm is called k-means, and the idea behind it is exactly the bike-share problem. You decide beforehand how many stations you can afford: that number is . Then you look for places for those stations so that every student lives as close as possible to a station. Every station gets the students for whom it is the nearest station: those are the clusters.
In the jargon such a station is called a centroid: the center of a cluster. So a good clustering is one in which every point lies close to its centroid on average. You can follow that number, the average distance to the centroid, in the demos below.
π Place the stations yourself
Try it yourself first. Click on the map below to place three stations (you can still drag them). Then press the button: every room gets the color of the nearest station, and in the panel next to the map you see how far a student lives from their station on average. Keep pressing and watch what the algorithm does with your stations: it moves every station to the middle of its rooms and then assigns the rooms again. Does the average distance go down? Can you beat the algorithm by placing the stations cleverly? With the button you start over, with the button you let the computer choose the starting positions. Watch how it often ends up at the same solution no matter where the starting positions were, and also try to find a starting position where it does not find the right solution.
π The recipe step by step
What you just did by hand is the complete algorithm. K-means repeats two simple steps until nothing changes anymore:
K-means forms clusters by:
- π Start: placing centroids, usually at the location of randomly chosen data points
- π¨ Assignment: assigning every data point to the nearest centroid
- π Update: moving every centroid to the mean of the points in its cluster
- π repeating steps 2 and 3 until no point switches cluster anymore (convergence)
The name says it already: clusters, and every centroid is the mean of its points.
You compute the mean (the "middle") of a group of points per feature separately: add up all the values and divide by the number of points, and do the same for . For the points , and that is . It is the point where the group "balances": like the center of gravity of a plank on which you put the points as little weights.
In the demo below you follow the recipe step by step with the arrows , or let it run automatically with Play. The panel next to it tells you at every step what happened: how many rooms switched cluster (they briefly get a circle) and the largest distance a station moved. The gray dashed lines are the boundaries between the clusters: everything on one side of such a line lies closer to one station than to the other.
π Convergence
After a few rounds nothing happens anymore: not a single room switches station, and so not a single station moves anymore either. We call that convergence. K-means always converges: every round makes the sum of the squared distances to the stations smaller or keeps it the same (see the math below), and that sum cannot keep going down forever. In practice a handful of rounds is usually enough, even for millions of data points.
π’ How many clusters?
The algorithm asks beforehand how many clusters there should be, and that choice of determines the result. Drag the slider below. With two neighborhoods are lumped together, with you get the three neighborhoods you saw yourself, and with or more a real neighborhood is chopped into pieces.
The chart next to the map helps with that choice. For every it shows how far a student lives from their station on average, each time after the algorithm has run to the end. More stations are always better for the average distance (with a station per room, everyone lives at distance zero), but the gain quickly gets smaller. From one to two and from two to three stations the distance drops sharply; a fourth station only gains a little. The bend in the curve looks like an elbow, and that is usually where a good lies: the elbow method. Click a point in the chart to choose that .
The elbow is an aid, not a law. In data without clear groups there is no bend to see, and then the choice of is a decision you have to make: how many stations can the company afford, how many playlists do you want, how many customer segments can a marketing team handle?
π² A random start
K-means starts with centroids in random places, and that has an annoying consequence: running the same algorithm twice on the same data can give two different clusterings. If two stations happen to start in the same neighborhood, they sometimes split that neighborhood between them and another neighborhood is left without a station, even though that is clearly not the best solution. The algorithm is then stuck in a local optimum: every small shift makes things worse, while a completely different division would be better. You can mimic that on the map from before. Put one station on the remote room at the top left, one in the neighborhood at the bottom left and one in the middle neighborhood, and let the algorithm run: the neighborhood on the right never gets a station of its own.
Try it out: press the button below a few times and play the algorithm again each time. Usually the map ends at an average distance of about 520 meters, but roughly one time in ten it ends at just over 700 meters: then one station claims one or two remote rooms all for itself, and two whole neighborhoods have to share one station. That is why in practice you run k-means several times with different starting positions and keep the result with the smallest average distance.
Starting completely at random is not necessary. Most programs (and the demos on this page) use k-means++: the first centroid is a random data point, and every next centroid is preferably chosen among points that lie far from the centroids already chosen. That way the centroids start well spread out and the algorithm gets stuck much less often.
βοΈ Work it out yourself
To really understand the recipe, do it once with pen and paper. Six rooms lie on a grid: A at , B at , C at , D at , E at and F at . There will be two stations, and both start in the same area: station 1 at the location of room A and station 2 at the location of room C .
- Assign every room to the nearest station (estimate the distances on the grid).
- Move every station to the mean of its rooms.
- Assign the rooms again. Does a room switch station? If so, move the stations once more.
- Where are the stations at the end?
Check your answer in the demo: click on the map to put station 1 on room A and station 2 on room C (a click close to a room snaps to it), and step through the algorithm.
π What k-means minimizes exactly
In this chapter we keep track of the average distance to the centroid as a measure of the quality of a clustering. The algorithm actually minimizes the sum of the squared distances, the WCSS, also called the inertia of the clustering:
where is the set of points in cluster and its centroid. Both steps of the recipe lower or keep it the same. The assignment step chooses for every point the centroid that makes its contribution the smallest. The update step puts every centroid at the mean of its points, and the mean is exactly the point that minimizes the sum of the squared distances to those points. Because cannot go down forever and there are only finitely many assignments, the algorithm has to converge. It does end in a local minimum of , though: finding the best possible clustering is NP-hard (external link), and k-means is a fast heuristic that usually finds a good solution, but not necessarily the best one. In practice the elbow method from above therefore works with instead of the average distance; the shape of the curve is similar.
The objective function of k-means is:
where:
- is the number of clusters
- is the set of points in cluster
- is the centroid (the mean) of cluster
- is the squared Euclidean distance between point and the centroid
K-means tries to make as small as possible: every point should lie as close as possible to the center of its cluster.
π Applications
On the map, distance literally means distance. But the algorithm does not know that it is a map: it only sees numbers. Replace the kilometers with other features, and the same recipe discovers very different groups.
πΌοΈ A photo with eight colors
A photo from your phone easily contains a hundred thousand different colors. Every pixel is a data point with three features: how much red, green and blue it contains. Let k-means look for clusters in them, and every centroid is a color: the mean of all the pixels in its cluster. If you then color every pixel with the centroid of its cluster, you have a photo with only colors.
Press play to watch the algorithm run from the start: it starts with k randomly chosen colors from the photo, and with every round the palette fits the photo better. With eight colors the photo is still easy to recognize; with two or three it becomes a poster. This is exactly how image compression with a palette works (in GIF files, for example): instead of 24 bits per pixel you only store the number of the palette color, and with eight colors that saves a factor of eight. You can also choose a photo of your own; it simply stays on your computer.
β Strengths of clustering
- π·οΈ No labels needed: you save the time and cost of labeling by hand and can get started right away with raw data.
- π Unexpected structure: the algorithm can find groups you had not thought of yourself, which makes clustering ideal for exploring a new dataset.
- π§© A stepping stone to labels: if you have a pile of unlabeled data, you cluster it first, label a few examples per cluster and then train a supervised model on those labels. That way you only have to look at a fraction of the data yourself.
- β‘ Fast and scalable: k-means is simple and converges quickly, even on millions of data points.
π§ Limitations of k-means
π€ k remains a choice
You have to say beforehand how many clusters there are, and in practice you rarely know that. Too few clusters lump real groups together, too many chop them into pieces. The elbow method helps, but gives no answer if the data shows no clear bend. Then you decide.
π΅ Only round clusters
Every centroid claims the area that lies closest to it, and the boundaries between those areas are always straight lines (compare with the decision regions of nearest neighbors). As a result, k-means only finds compact, more or less round clusters, and goes wrong with other shapes. Look at the "Concentric circles" below: there are clearly two groups (an inner and an outer ring), but the algorithm divides the data into two halves, because a ring has no center that its points lie close to.
You see the same problem with the "Two moons": two half-moon shapes that hook into each other. Feel free to choose other datasets in the drop-down list and play with and with the noise. Can you separate the two moons after all? Tip: use more clusters than there are groups and merge clusters yourself afterwards.
For such shapes there are other algorithms, such as DBSCAN (external link), which looks for clusters as areas where the points lie close together. That way it finds clusters of any shape, and you do not even have to choose beforehand.
π‘ Geometric, not meaningful
K-means groups by distance in the feature space, not by meaning. If you cluster customers by age and income, "young with a low income" can contain a student as well as a new entrepreneur, with very different needs. The clusters make sense mathematically (a small distance to the center), but whether they are also useful is something you judge as a human. Interpreting the clusters you found is the real work.
β Other limitations
- π Non-deterministic: because of the random start, two runs can give different results. Run the algorithm several times and keep the best run.
- π Sensitive to scale: a feature with large numbers dominates the distance. Put features on the same scale first, as with scaling variables for nearest neighbors.
- π΄ Sensitive to outliers: one remote room pulls a station toward it, because the mean gives every point the same weight. On the map you can see a few stations pulled slightly away from their neighborhood by the scattered rooms.
- βοΈ Similar sizes: k-means divides the space into areas of similar shape, and has a hard time when a real group is much larger or much more spread out than the others.
π² Hierarchical clustering
K-means wants to know beforehand how many clusters there are. Hierarchical clustering turns that question around: it first builds up all the groupings, from very fine to very coarse, and you choose afterwards.
The recipe is simple. You start with every point as its own cluster: eight rooms are then eight clusters of one. Then you repeatedly look for the two clusters that lie closest to each other and merge them into one cluster. You repeat that until everything is in one big cluster. You can measure how far apart two clusters lie as, for example, the average distance between their points.
You draw the result as a dendrogram, a kind of family tree of your data. At the bottom every data point stands on its own, and every horizontal connection is a merge. The height of such a connection is the distance between the two clusters that come together there: low means they were very similar, high means you are gluing two different groups together.
Eight rooms on the map, colored by cluster, and the dendrogram with all the merges. The dashed line cuts at 2.9 km and leaves three clusters.
So you choose the number of clusters afterwards, by cutting the dendrogram at a height of your choice: every branch you cut through becomes a cluster. If you cut low, you are left with many small clusters; if you cut high, a few large ones remain. A long branch without merges (here between 1.3 and 4.5 km) reveals that the groups below it really lie apart from each other, and is therefore a good place to cut.
Hierarchical clustering is especially interesting when you do not know beforehand or when you want to see the whole structure, for example with a small dataset you are exploring. The price is computation: at every step the algorithm compares all pairs of clusters with each other, and with tens of thousands of points that becomes unaffordable. So for large datasets you reach for k-means after all.
πΉοΈ Demos
Experiment further with the full simulators and demos featured above.


π£οΈ Feedback
Just like machine learning algorithms, we also love learning from your feedback to improve the course.
Let us know how informative and how difficult you found this chapter, and where it could be better.