A pizza chain wants to open three kitchens in a new city so that every customer is as close as possible to one of them. Put the three kitchens down anywhere. Each customer orders from the nearest kitchen. Now move each kitchen to the middle of the customers who order from it. Some customers now find a different kitchen closer, so they switch. Move the kitchens again. After a few rounds, nothing changes: the kitchens sit in the middle of three natural groups of customers.
That's K-means clustering, the most widely used way to find groups in data that has no labels. K-means clustering takes a number k, places k centres, and repeats two steps until it settles: assign every point to its nearest centre, then move every centre to the average of its points. Everything before this module was supervised learning, with a correct answer to learn from. Clustering is unsupervised: nobody says what the groups are; the algorithm finds them.
What you need first: distance between vectors, feature scaling and types of machine learning for what "unsupervised" means.
Key terms
- Cluster: a group of points that are closer to each other than to points in other groups.
- Centroid: the centre of a cluster, the average of its points.
- Inertia: the sum of squared distances from every point to its centroid; smaller means tighter clusters.
- k: the number of clusters, which you choose before running K-means.
- Silhouette score: a number from −1 to 1 measuring how well each point fits its own cluster compared with the nearest other cluster.
The k-means clustering algorithm in two steps
- Start: choose k points as the first centroids.
- Assign: give every point to its nearest centroid.
- Update: move each centroid to the average of the points assigned to it.
- Repeat steps 2 and 3 until no point changes cluster.
Each round can only lower the inertia or keep it the same: assigning a point to a nearer centroid shortens its distance, and the average is the spot with the smallest total squared distance to a group of points. So the loop always stops.
One round by hand
Six points on a line, and k = 2, with the two centroids starting at 1 and 2:
import numpy as np
points = np.array([1, 2, 3, 10, 11, 12])
centroids = np.array([1.0, 2.0])
for round_number in range(1, 4):
distances = np.abs(points[:, None] - centroids[None, :])
labels = distances.argmin(axis=1)
centroids = np.array([points[labels == k].mean() for k in range(2)])
inertia = ((points - centroids[labels]) ** 2).sum()
print(f"round {round_number}: labels {labels}, centroids {centroids}, inertia {inertia:.2f}")
round 1: labels [0 1 1 1 1 1], centroids [1. 7.6], inertia 89.20
round 2: labels [0 0 0 1 1 1], centroids [ 2. 11.], inertia 4.00
round 3: labels [0 0 0 1 1 1], centroids [ 2. 11.], inertia 4.00
points[:, None] - centroids[None, :] makes a table of differences, one row per point and one column per centroid. argmin(axis=1) picks the column with the smallest distance for each row: the nearest centroid. centroids[labels] looks up each point's own centroid.
Predict first: before reading the output, which points will join the centroid at 1 in the first round?
Only the point at 1. Every other point, even 12, is at least as close to the centroid at 2, so in round 1 the second cluster takes five points and its centroid jumps to their average, 7.6. That leaves 2 and 3 closer to the first centroid, so in round 2 they switch, and the centroids move to 2 and 11. In round 3 nobody switches: K-means has settled, and the inertia has fallen from 89.2 to 4.0.
K-means in scikit-learn
Three groups of points, made with make_blobs, so the right answer is known:
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, true_group = make_blobs(n_samples=300, centers=3, cluster_std=1.0, random_state=42)
kmeans = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
print("centroids:\n", kmeans.cluster_centers_.round(2))
print("inertia:", round(kmeans.inertia_, 1))
print("rounds until it settled:", kmeans.n_iter_)
fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, s=15, cmap="viridis")
ax.scatter(*kmeans.cluster_centers_.T, marker="X", s=250, c="red", edgecolor="black")
ax.set_title("K-means with k = 3")
plt.show()
centroids:
[[-2.63 9.04]
[-6.88 -6.98]
[ 4.75 2.01]]
inertia: 566.9
rounds until it settled: 2
make_blobs makes round clouds of points around random centres. n_init=10 runs K-means 10 times from different starting centroids and keeps the run with the lowest inertia. kmeans.labels_ holds each point's cluster number, and *kmeans.cluster_centers_.T splits the centroids into their x and y coordinates for plotting.
Each centroid lands in the middle of one cloud, and with clouds this clear K-means settles after just 2 rounds. Note that the cluster numbers 0, 1 and 2 are arbitrary names: K-means doesn't know which group is "first", and another run could number them differently.
Choosing k
K-means always returns exactly k clusters, even if the data has none. So how do you pick k?
Experiment: run K-means for k from 1 to 8 and record two numbers: the inertia, and the silhouette score. Predict first: will inertia ever go up as k grows?
from sklearn.metrics import silhouette_score
ks = range(1, 9)
inertias, silhouettes = [], []
for k in ks:
model = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
inertias.append(model.inertia_)
silhouettes.append(silhouette_score(X, model.labels_) if k > 1 else np.nan)
print(f"k = {k}: inertia {model.inertia_:8.1f} silhouette {silhouettes[-1]:.3f}")
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].plot(ks, inertias, marker="o")
axes[0].set_title("Inertia (look for the elbow)")
axes[1].plot(ks, silhouettes, marker="o", color="tab:orange")
axes[1].set_title("Silhouette score (higher is better)")
for ax in axes:
ax.set_xlabel("k")
plt.tight_layout()
plt.show()
k = 1: inertia 20402.3 silhouette nan
k = 2: inertia 5763.5 silhouette 0.705
k = 3: inertia 566.9 silhouette 0.848
k = 4: inertia 496.8 silhouette 0.660
k = 5: inertia 426.3 silhouette 0.492
k = 6: inertia 361.1 silhouette 0.331
k = 7: inertia 320.0 silhouette 0.336
k = 8: inertia 272.7 silhouette 0.362
The silhouette score needs at least two clusters, so k = 1 gets np.nan, "not a number", which matplotlib leaves out of the chart.
No: inertia only ever falls, because more centroids always means each point can be at least as close to one. It drops steeply from k = 1 to k = 3 (20,402 to 567) and then barely moves. That bend is the elbow: beyond it, extra clusters only split real groups into pieces. The silhouette score agrees, and more sharply: it peaks at k = 3 (0.848) and falls away on both sides. On real data the elbow is often much softer and the two methods can disagree; then the deciding question is which k gives groups you can use.
See it fail: unscaled features
K-means measures straight-line distance, so a feature measured in big numbers drowns out one measured in small numbers. Imagine customers described by yearly income in rupees and age in years:
rng = np.random.default_rng(0)
young = np.column_stack([rng.normal(500_000, 150_000, 100), rng.normal(25, 3, 100)])
old = np.column_stack([rng.normal(500_000, 150_000, 100), rng.normal(60, 3, 100)])
customers = np.vstack([young, old])
is_old = np.array([0] * 100 + [1] * 100)
raw = KMeans(n_clusters=2, n_init=10, random_state=0).fit(customers)
from sklearn.preprocessing import StandardScaler
scaled = KMeans(n_clusters=2, n_init=10, random_state=0).fit(StandardScaler().fit_transform(customers))
def agreement(labels):
same = np.mean(labels == is_old)
return max(same, 1 - same)
print(f"raw features: clusters match the age groups for {agreement(raw.labels_):.0%} of customers")
print(f"scaled features: clusters match the age groups for {agreement(scaled.labels_):.0%} of customers")
raw features: clusters match the age groups for 56% of customers
scaled features: clusters match the age groups for 100% of customers
np.column_stack puts the two columns side by side. Cluster numbers are arbitrary (cluster 0 could be either group), so agreement counts the match both ways round and keeps the better one.
Unscaled, the clusters match the two age groups for only 56% of customers, barely better than a coin toss. Income varies by hundreds of thousands of rupees and age by a few decades, so to K-means the distance between two customers is almost entirely their income gap, and it splits them into richer and poorer instead of younger and older. After StandardScaler puts both columns on the same scale, the match is 100%. Scale your features before K-means, every time.
See it fail: groups that aren't round
K-means assumes each cluster is a round blob around its centroid. Two interlocking half-moons break that assumption:
from sklearn.datasets import make_moons
X_moons, moon = make_moons(n_samples=300, noise=0.06, random_state=0)
moon_labels = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X_moons)
print(f"clusters match the moons for {max(np.mean(moon_labels == moon), np.mean(moon_labels != moon)):.0%} of points")
fig, ax = plt.subplots(figsize=(6, 4))
ax.scatter(X_moons[:, 0], X_moons[:, 1], c=moon_labels, s=15, cmap="viridis")
ax.set_title("K-means cuts the moons in half")
plt.show()
clusters match the moons for 74% of points
fit_predict fits the model and returns the labels in one step.
K-means matches the moons for only 74% of points. It cuts the picture with a straight boundary roughly down the middle, because every point simply joins its nearest centroid, and two centroids always split the plane with a straight line. Clusters that wind around each other need a method that follows chains of nearby points, such as DBSCAN, later in this course.
When to use K-means
| Situation | K-means? | Better choice |
|---|---|---|
| Round, similar-sized groups, numeric features | Yes | |
| Large data (millions of rows) | Yes, it's fast (MiniBatchKMeans for the largest) | |
| Groups of odd shapes, such as rings or moons | No | DBSCAN, later in this course |
| Many outliers | Risky: outliers drag centroids | DBSCAN, or remove outliers first |
| You don't know how many groups there are | Possible, with the elbow and silhouette | Hierarchical clustering shows every k at once |
| Text categories or mixed data types | No: averages need numbers | K-prototypes, or encode carefully first |
Practice
- Without running code: K-means with k = 3 on the points 0, 1, 2, 20, 21, 22, 40, 41, 42, starting from centroids 0, 1 and 2. Where do the centroids end up?
Show the answer
km = KMeans(n_clusters=3, init=np.array([[0.0], [1.0], [2.0]]), n_init=1)
print(km.fit(np.array([0, 1, 2, 20, 21, 22, 40, 41, 42]).reshape(-1, 1)).cluster_centers_.ravel())
[ 0. 1.5 31. ]
They get stuck at 0, 1.5 and 31, not at 1, 21 and 41. The centroids at 1 and 2 both start inside the first group, and the one at 2 grabs everything else; once the third centroid sits between the second and third groups at 31, no point is closer to another centroid, so nothing moves again. K-means only ever finds a local minimum, which is why scikit-learn chooses spread-out starting points (k-means++) and runs several starts with n_init.
- Why must you choose k before running K-means, and why can't you simply choose the k with the lowest inertia?
Show the answer
The algorithm needs k centroids to start. Inertia always falls as k grows, reaching 0 when every point is its own cluster, so "lowest inertia" always picks the largest k. Look for the elbow, or use the silhouette score, which does penalise too many clusters.
- Run K-means on the blobs with
n_init=1and five differentrandom_statevalues. Does the inertia change?
Show the answer
for seed in range(5):
print(seed, round(KMeans(n_clusters=3, n_init=1, random_state=seed).fit(X).inertia_, 1))
0 566.9
1 566.9
2 566.9
3 566.9
4 566.9
No: all five give 566.9. With k-means++ starting points and three well-separated blobs, every start finds the same answer. On messier data, different starts do give different results, which K-means from scratch shows with purely random starts.
- Why does a centroid move to the average of its points, and not to, say, the middle point?
Show the answer
K-means minimises squared distances, and the point with the smallest total squared distance to a group is exactly their average. (The middle value, the median, minimises total plain distance instead; using it gives a different algorithm, K-medians.)
- A colleague clusters customers on income and age without scaling and finds two clusters: "high income" and "low income". What would you check first?
Show the answer
Whether the features were scaled. Income in rupees varies over hundreds of thousands, age over decades, so unscaled K-means sees only income. Standardise both, then cluster again.
Interview questions
How does K-means work?
Choose k starting centroids, often with k-means++. Then alternate two steps: assign each point to its nearest centroid, and move each centroid to the mean of its assigned points. Stop when assignments no longer change. It minimises the within-cluster sum of squared distances (inertia).
How do you choose k in K-means?
Plot inertia against k and look for the elbow where improvement slows, compute the silhouette score for each k, and, above all, check which k gives clusters that are useful and interpretable for the purpose.
What are the limitations of K-means?
It needs k in advance, assumes roughly spherical clusters of similar size, is sensitive to feature scales, outliers and starting centroids, finds only a local minimum, and works only with numeric features where averages make sense.
Key takeaways
- K-means repeats two steps: assign each point to its nearest centroid, then move each centroid to the average of its points.
- Every round lowers or keeps the inertia, so it always settles, but possibly in a poor arrangement;
n_initruns it several times. - Inertia always falls as k grows; use the elbow and the silhouette score to choose k.
- Scale the features first, or the feature with the biggest numbers decides everything.
- K-means finds round blobs; groups of other shapes need other methods.
Frequently asked questions
Is K-means supervised or unsupervised?
Unsupervised: it uses only the features, with no labels. Its clusters have no names until you look at them and decide what they mean.
What is k-means++?
A smarter way to choose the starting centroids: the first is a random point, and each next one is chosen with a probability that grows with its distance from the centroids already chosen. Spread-out starts lead to better results, and scikit-learn uses it by default.
Can K-means predict the cluster of a new point?
Yes: kmeans.predict(new_points) assigns each new point to its nearest centroid, without moving the centroids.
What to learn next
- Build K-means yourself, including k-means++, in K-means from scratch in Python, the next lesson.
- Revisit how distance works in distance between vectors.
- Revisit feature scaling, which K-means depends on.