ML K-means
K-means is the most popular clustering algorithm. Like hierarchical clustering it needs no labels, but it works differently: you choose the number of clusters k in advance, and the algorithm finds k centres (centroids) so that every point is close to its own centre.
How it works
- Place k centroids somewhere (scikit-learn uses a smart random start called k-means++).
- Assign every point to its nearest centroid.
- Move each centroid to the mean of the points assigned to it.
- Repeat steps 2–3 until the centroids stop moving.
Let's watch the core of the algorithm on a tiny one-dimensional example — ages of 8 people, k = 2 — written in plain NumPy:
import numpy as np
ages = np.array([18, 21, 22, 25, 51, 54, 58, 61], dtype=float)
centroids = np.array([18.0, 25.0]) # a deliberately poor start
for step in range(1, 5):
distances = np.abs(ages[:, None] - centroids[None, :])
labels = distances.argmin(axis=1) # assign
centroids = np.array([ages[labels == k].mean() for k in range(2)]) # move
print(f"step {step}: labels={labels.tolist()} centroids={centroids.round(2).tolist()}")step 1: labels=[0, 0, 1, 1, 1, 1, 1, 1] centroids=[19.5, 45.17]
step 2: labels=[0, 0, 0, 0, 1, 1, 1, 1] centroids=[21.5, 56.0]
step 3: labels=[0, 0, 0, 0, 1, 1, 1, 1] centroids=[21.5, 56.0]
step 4: labels=[0, 0, 0, 0, 1, 1, 1, 1] centroids=[21.5, 56.0]
After a few steps the centroids settle on the two age groups and stop changing — the algorithm has converged.
K-means in scikit-learn
make_blobs generates points around a few random centres — handy for experiments. We create 300 points around 4 centres and let KMeans find them:
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.9, random_state=7)
kmeans = KMeans(n_clusters=4, n_init=10, random_state=0)
labels = kmeans.fit_predict(X)
plt.scatter(X[:, 0], X[:, 1], c=labels, s=15, cmap="viridis")
plt.scatter(*kmeans.cluster_centers_.T, c="red", marker="X", s=200)
plt.show()
print("centroids:")
print(kmeans.cluster_centers_.round(2))
print("points per cluster:", [int((labels == k).sum()) for k in range(4)])centroids:
[[ 9.52 0.53]
[-1.31 4.54]
[ 0.09 -8.71]
[-8.44 5.49]]
points per cluster: [75, 75, 75, 75]
n_init=10 runs the algorithm ten times from different starting points and keeps the best result, which protects against an unlucky start. random_state makes it reproducible.
Choosing k: the elbow method
In real data you rarely know the right k. A common heuristic is the elbow method. K-means' inertia is the sum of squared distances from each point to its centroid. Inertia always falls as k grows (with k = number of points it is zero!), but after the "right" k it falls much more slowly. Plot inertia against k and look for the bend:
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.9, random_state=7)
ks = range(1, 9)
inertias = [KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_ for k in ks]
plt.plot(ks, inertias, marker="o")
plt.xlabel("Number of clusters k")
plt.ylabel("Inertia")
plt.title("Elbow method")
plt.show()
for k, inertia in zip(ks, inertias):
print(f"k={k}: inertia={inertia:8.1f}")k=1: inertia= 22193.5
k=2: inertia= 8941.6
k=3: inertia= 2402.8
k=4: inertia= 462.8
k=5: inertia= 414.0
k=6: inertia= 370.8
k=7: inertia= 326.5
k=8: inertia= 282.6
The drop from k = 3 to k = 4 is still large, but from 4 to 5 it is small: the elbow is at k = 4, matching how the data was generated.
Clustering new points
A fitted KMeans can assign new points to the nearest centroid with predict:
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.9, random_state=7)
kmeans = KMeans(n_clusters=4, n_init=10, random_state=0).fit(X)
new_points = [[-8, -5], [0, 0], [-4, 7]]
print("clusters:", kmeans.predict(new_points))
print("distance to each centroid for the first point:")
print(kmeans.transform(new_points[:1]).round(2))clusters: [2 1 1]
distance to each centroid for the first point:
[[18.37 11.65 8.9 10.5 ]]
Limitations
- You must choose k (use the elbow method, or the silhouette score from the DBSCAN & Choosing Clusters lesson).
- K-means assumes roughly round clusters of similar size. Long, curved or nested shapes confuse it.
- It uses distances, so scale your features first when they have different units.
- Outliers pull centroids toward them.
Go further: k-Means Clustering writes the algorithm and k-means++ from scratch and compares ways of choosing k.
Test yourself
What are the two steps k-means repeats until it converges?
- Split and prune
- Assign points to the nearest centroid, then move centroids to the mean
- Merge the closest clusters
- Sort and count
What is inertia in k-means?
- The number of iterations
- The sum of squared distances from points to their centroids
- The number of clusters
- The accuracy of the clustering
In the elbow method, which k do you pick?
- The k with the lowest inertia
- The largest k you can afford
- The k where inertia stops dropping sharply
- Always k = 2