Lesson 16 of 227 min
Clustering with k-means
With no labels, k-means finds groups by moving each centre to the middle of its nearest things, and you choose how many.
After this lesson you can group unlabelled points and choose how many groups.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Put a new penguin in a group
Put the Palmer Penguins penguins.csv next to your notebook. Fit the scaler and k-means on the measured bills, then pass the new bill to the same pipeline. The scaler uses the fitted ruler, and k-means picks the nearest center. Group numbers are names assigned by the run. KMeans reference
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
bill = ["bill_length_mm", "bill_depth_mm"]
penguins = pd.read_csv("penguins.csv").dropna(subset=bill)
groups = make_pipeline(StandardScaler(), KMeans(n_clusters=3, random_state=0))
groups.fit(penguins[bill])
print(groups.predict(pd.DataFrame([[48.0, 14.5]], columns=bill)))[1]
Compare each point with its neighbors
The silhouette compares a point’s average distance to its own group with its average distance to the nearest other group. Near one means the groups are well separated. Near zero means a point is near a boundary. The highest mean here is at three groups. Compute the score on the same scaled measurements you clustered. Silhouette reference
from sklearn.metrics import silhouette_score
scaled = groups[0].transform(penguins[bill])
for k in range(2, 6):
labels = KMeans(k, n_init=10, random_state=0).fit_predict(scaled)
print(k, round(silhouette_score(scaled, labels), 3))2 0.476 3 0.525 4 0.437 5 0.4
Add flipper length and body mass
Fit a new scaler when you add measurements. Two groups now have the highest silhouette of the three choices below. One group holds the Gentoos and the other holds both remaining kinds. The four measurements give a different answer to what counts as close.
four = bill + ["flipper_length_mm", "body_mass_g"]
measured = penguins.dropna(subset=four)
scaled_four = StandardScaler().fit_transform(measured[four])
for k in range(2, 5):
fitted = KMeans(k, n_init=10, random_state=0).fit(scaled_four)
print(k, round(fitted.inertia_), round(silhouette_score(scaled_four, fitted.labels_), 3))
labels = KMeans(2, n_init=10, random_state=0).fit_predict(scaled_four)
print(pd.crosstab(labels, measured["species"]).to_numpy().tolist())2 566 0.532 3 379 0.447 4 300 0.4 [[151, 68, 0], [0, 0, 123]]
Give the centers several starts
The default k-means++ start favors points far from the centers already picked. With that start, n_init="auto" gives one run. Set n_init=10 to start ten times and keep the lowest total. Two runs can have almost the same total and still group a point differently. Initialization reference
for starts in ("auto", 10):
fitted = KMeans(3, n_init=starts, random_state=0).fit(scaled)
print(starts, round(fitted.inertia_, 3))auto 186.927 10 186.921
Follow groups that curve
A k-means border between two centers is straight. Try two curved moons with DBSCAN, which joins points through dense neighborhoods and gives isolated points label −1. HDBSCAN searches across density levels. For other shapes, a Gaussian mixture can fit tilted ellipses, and agglomerative clustering builds groups by merging smaller ones. Clustering guide
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
curves, known = make_moons(n_samples=300, noise=0.055, random_state=0)
found = DBSCAN(eps=0.17, min_samples=5).fit_predict(curves)
print(pd.crosstab(found, known).to_numpy().tolist())[[1, 0], [0, 150], [149, 0]]
Read text groups by hand
Each help desk message in the chapter had 768 numbers. The recorded totals for two through five groups are 1.53, 1.28, 1.10, and 0.97. There is no sharp bend at three. Open the groups and see if you can name and use them. A second message about money may belong with refunds even if it uses different words.
text_totals = [1.5284, 1.2771, 1.0985, 0.9728]
drops = [round(a - b, 2) for a, b in zip(text_totals, text_totals[1:])]
print(drops)[0.25, 0.18, 0.13]
Run on Python 3.13.3, pandas 3.1.1 and scikit-learn 1.9.1. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Distance and cosine similarity
Your search compares sentences by their vectors, from a model that gives every vector a length of 1. Which should it rank them by?
2 of 3
The penguins' kinds are hidden, and k-means is asked for three groups. It puts 318 of the 342 with their own kind. What did it group them by?
3 of 3
With ten starts for each k, inertia_, the total squared distance, prints 684, 340, 187, 148, 114, 94 for 1 to 6 groups. How many groups do you keep?
The ideas in this lesson
- Clustering
- Finding groups in things that have no label, by putting near things together; a person then says what each group means.
- k-means
- Drop k centres; each thing joins its nearest centre, each centre moves to its group's middle; repeat until nothing changes.
- How many groups
- Add up each thing's squared distance to its centre: keep the lowest of several starts, and choose k at the bend.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
k-means
Here's a bet. These penguins have their kinds hidden. Nobody tells the computer which kind is which. We only ask it for three groups. Will its three groups be the three kinds?
Keep your guess
Hold on to your guess.
Here are all three hundred and forty-two penguins, by bill length and bill depth. Their three kinds, Adelie, Chinstrap and Gentoo, are hidden.
Groups with no names
Nobody wrote down a kind for these penguins, so there's no label to learn from. Still, look. Your eye already sees three groups of dots.
Finding groups like these, in things with no label, is called clustering.
The groups come with no names. A person reads each group later, and says what it means.
Centers, and the nearest
One way to find groups with no labels is called k-means. First, you choose k: how many groups you want. Here, three. This k is how many groups, not how many neighbors.
Then you drop three centers anywhere on the picture: one middle point for each group.
Now each penguin joins its nearest center: the one at the shortest distance, with both measurements on one ruler.
The regions show which center is nearest. The border between two regions sits halfway between their centers.
The center moves to the middle
Next, each center moves to the middle of its group: the average of its penguins. Will any penguin change groups now?
Yes. Some penguins are now closer to another center, so they join it.
Then the centers move again.
A join and a move make one round. Six rounds move the centers. The seventh changes nothing, and k-means stops.
Groups are not kinds
So, your guess. Here are the kinds. Three hundred and eighteen of the three hundred and forty-two sit with their own kind. About nine in ten. If you said yes, exactly the kinds, that's close, but not quite.
If you said no, it found most of them anyway.
The Adelies and the Gentoos are almost complete. A few Chinstraps sit with each of the others, where their cloud touches.
k-means groups what's close together on these two measurements.
And penguins that are close together are not always the same kind.
The total squared distance
k-means moves the centers until each one sits in the middle of its group. Here, we could check its groups against the kinds. But real data has no names. So how do you judge a grouping? Take each penguin's distance to its center, and square it, so the far penguins count more. Then add them all up. That one number is the total squared distance. Lower means tighter groups.
After the first join, it was four hundred and nineteen. Every round lowered it, down to a hundred and eighty-seven, where k-means stopped.
A start can get stuck
Now start again, from here. Two centers among the short bills, and one among the long ones. Watch it run. What goes wrong?
The Adelies are cut in two, and most Chinstraps and Gentoos share one group. The total is three hundred and four, compared to a hundred and eighty-seven. Every round lowered the total, and it still ended up worse. No round can fix a bad start.
So run k-means from several starts, and keep the one with the lowest total. scikit-learn helps: its start spreads the first centers apart, and you can ask it for several starts.
More groups, lower total
We asked for three groups, because we knew there were three kinds. Without names, how many groups? Which k gives the lowest total?
The most groups. Give every penguin a group of its own. Each center then sits right on its penguin, and the total is zero.
Add a group, and the total falls. Add another, and it falls again. The more groups, the lower the total.
The bend
So the lowest total can't choose for you. Look for the bend instead. Two groups take away half the total. Three take away nearly half of what's left. After three, each new group takes away very little. So choose three.
Read the groups
Then read the groups, because the total can't tell you what a group means.
With four groups, the Adelies are cut in two again, just like the stuck start cut them. That's a cut, not a new kind. Keep the k whose groups you can name and use.
In code
In real code, with scikit-learn.
A pipeline puts the two measurements on one ruler, then runs k-means with three groups.
One call fits it, and gives every penguin a group.
Line the groups up against the kinds.
One group holds fifty-five Chinstraps. Another, a hundred and sixteen Gentoos.
The third, a hundred and forty-seven Adelies.
Now ten starts for each k, from one to eight, keeping each k's lowest total.
scikit-learn calls this total the inertia. Where will the totals bend?
At three.
Does the same code work on text? Here are eighteen messages to a store's help desk. An embedding model turns each one into seven hundred and sixty-eight numbers.
Ask k-means for three groups, and read them: signing in, refunds, and delivery.
"You charged my card twice" sits with the refunds, even without the word refund.
A person reads the groups, and names them.
Three ideas
So: clustering finds groups in things with no labels. k-means moves each center to the middle of its group, until nothing changes.
And you judge a grouping by its total: keep the lowest of several starts, and choose k at the bend.
Move each center to the middle
So k-means moves each center to the middle of its group. Now try it on this lesson's page, and take the quiz. Set two groups, and find out which kinds end up together.
You use this lesson in Lab 6: The penguins' kinds, with the names hidden, after PCA.
Facts last checked on .
