K-means clustering explained described the loop: assign every point to its nearest centroid, move every centroid to the average of its points, repeat. K-means from scratch in Python takes about 30 lines of NumPy, and building it shows the three details that separate a toy version from a reliable one: how to choose the starting centroids, what to do when a cluster ends up empty, and why you run the whole thing several times.
At the end, the home-made version is checked against scikit-learn's KMeans on the same data.
What you need first: K-means clustering explained, distance between vectors and NumPy arrays from the NumPy array tutorial and NumPy reshape; broadcasting is explained below where it's used.
Key terms
- Broadcasting: NumPy's way of combining arrays of different shapes, used here to measure every point against every centroid at once.
- Random initialisation: starting from k data points picked at random.
- k-means++: starting from spread-out points, each chosen with a probability that grows with its squared distance from the centroids already picked.
- Empty cluster: a centroid that no point is nearest to, so its average is undefined.
- Local minimum: an arrangement where no single step improves the inertia, though a better arrangement exists.
Step 1: distances from every point to every centroid
For n points and k centroids, the distances form an n × k table. Broadcasting builds it without a loop:
import numpy as np
def squared_distances(X, centroids):
diff = X[:, None, :] - centroids[None, :, :]
return (diff ** 2).sum(axis=2)
X_tiny = np.array([[0.0, 0.0], [1.0, 0.0], [10.0, 10.0]])
centroids_tiny = np.array([[0.0, 0.0], [10.0, 9.0]])
print(squared_distances(X_tiny, centroids_tiny))
[[ 0. 181.]
[ 1. 162.]
[200. 1.]]
X[:, None, :] has shape (n, 1, 2) and centroids[None, :, :] has shape (1, k, 2); NumPy stretches both to (n, k, 2), subtracts, and sum(axis=2) adds up the x and y parts. Squared distances are enough for finding the nearest centroid, and save a square root.
Row 3 is the point (10, 10): it's 200 away (squared) from the first centroid and 1 away from the second.
Step 2: the loop
def kmeans(X, k, init="k-means++", max_iter=100, seed=0):
rng = np.random.default_rng(seed)
centroids = choose_start(X, k, init, rng)
labels = np.full(len(X), -1)
for iteration in range(1, max_iter + 1):
new_labels = squared_distances(X, centroids).argmin(axis=1) # assign
if np.array_equal(new_labels, labels):
break # nothing changed
labels = new_labels
for j in range(k): # update
members = X[labels == j]
if len(members) == 0: # empty cluster
farthest = squared_distances(X, centroids).min(axis=1).argmax()
centroids[j] = X[farthest]
else:
centroids[j] = members.mean(axis=0)
inertia = squared_distances(X, centroids).min(axis=1).sum()
return centroids, labels, inertia, iteration
labels starts as all −1, so the first assignment always counts as a change. np.array_equal checks whether any point switched cluster; if none did, the centroids won't move either, so the loop stops. members.mean(axis=0) averages each column, giving the new centroid.
If a cluster loses all its points, there's nothing to average. This version moves its centroid to the point that is currently farthest from any centroid, which is usually where a cluster is most needed. Scikit-learn does something similar.
Step 3: two ways to start
def choose_start(X, k, init, rng):
if init == "random":
return X[rng.choice(len(X), size=k, replace=False)].copy()
centroids = [X[rng.integers(len(X))]] # k-means++
for _ in range(1, k):
d2 = squared_distances(X, np.array(centroids)).min(axis=1)
centroids.append(X[rng.choice(len(X), p=d2 / d2.sum())])
return np.array(centroids, dtype=float)
rng.choice(len(X), size=k, replace=False) picks k different row numbers. For k-means++, d2 holds each point's squared distance to its nearest chosen centroid, and p=d2 / d2.sum() makes points far from every chosen centroid more likely to be picked next. A point already chosen has distance 0, so it can't be picked twice.
Check against scikit-learn
Eight groups this time, close enough together that starting points matter. One start is a gamble, as the experiment below shows, so compare the best of 10 starts from each version:
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=800, centers=8, cluster_std=1.2, random_state=7)
def kmeans_best_of(X, k, n_init=10, init="k-means++"):
runs = [kmeans(X, k, init=init, seed=s) for s in range(n_init)]
return min(runs, key=lambda run: run[2])
centroids, labels, inertia, rounds = kmeans_best_of(X, 8)
sk = KMeans(n_clusters=8, n_init=10, random_state=0).fit(X)
print(f"mine, best of 10: inertia {inertia:.1f}")
print(f"scikit-learn, n_init=10: inertia {sk.inertia_:.1f}")
mine, best of 10: inertia 2101.7
scikit-learn, n_init=10: inertia 2101.8
min(runs, key=...) picks the run with the smallest inertia; lambda run: run[2] is a one-line function that returns a run's inertia, the third value kmeans returns.
The same answer to within 0.1: 2,101.7 against 2,101.8. Thirty lines of NumPy do what scikit-learn's KMeans does; scikit-learn is faster and handles more special cases, but the result is the same.
Watch it converge
Run the loop one round at a time and draw the centroids after rounds 1, 2, 5 and the end, starting from random points:
import matplotlib.pyplot as plt
rng = np.random.default_rng(3)
start = choose_start(X, 8, "random", rng)
fig, axes = plt.subplots(1, 4, figsize=(16, 4), sharex=True, sharey=True)
for ax, rounds in zip(axes, [1, 2, 5, 100]):
c = start.copy()
for _ in range(rounds):
lab = squared_distances(X, c).argmin(axis=1)
c = np.array([X[lab == j].mean(axis=0) if np.any(lab == j) else c[j] for j in range(8)])
lab = squared_distances(X, c).argmin(axis=1)
label = "settled" if rounds == 100 else f"after {rounds} round" + ("s" if rounds > 1 else "")
print(f"{label}: inertia {squared_distances(X, c).min(axis=1).sum():.1f}")
ax.scatter(X[:, 0], X[:, 1], c=lab, s=6, cmap="tab10")
ax.scatter(c[:, 0], c[:, 1], marker="X", s=160, c="black")
ax.set_title(label)
plt.tight_layout()
plt.show()
after 1 round: inertia 3281.3
after 2 rounds: inertia 3150.6
after 5 rounds: inertia 3049.3
settled: inertia 2102.3
np.any(lab == j) checks whether cluster j has any points; if not, its centroid stays where it was. sharex=True, sharey=True gives all four panels the same axes, so the movement is easy to compare.
The wide cloud at the bottom is really two overlapping groups of 100 points, so two centroids belong there. Early on, the centroids in the crowded top-left area are badly placed, and the inertia falls only slowly: 3,281 after one round, 3,049 after five. Then, over later rounds, the centroids sort themselves out, one per group, and the inertia drops to 2,102.3. This start was a lucky one. The next two sections show how often a start isn't.
Experiment: random starts against k-means++
Experiment: run both starting methods 50 times each with different seeds, and count how often each finds the best arrangement. Predict first: will k-means++ find it every time?
results = {}
for init in ["random", "k-means++"]:
results[init] = np.array([kmeans(X, 8, init=init, seed=s)[2] for s in range(50)])
best = min(r.min() for r in results.values())
for init, inertias in results.items():
print(f"{init:10}: best {inertias.min():.1f}, worst {inertias.max():.1f}, "
f"within 1% of the best in {np.mean(inertias <= best * 1.01):.0%} of 50 runs")
random : best 2101.7, worst 7658.7, within 1% of the best in 26% of 50 runs
k-means++ : best 2101.7, worst 3157.4, within 1% of the best in 46% of 50 runs
[2] takes the third value kmeans returns, the inertia. "Within 1%" counts runs that found essentially the best arrangement: two runs can split a few border points differently and differ slightly.
No. k-means++ gets within 1% of the best arrangement in 46% of runs, against 26% for random starts, and its worst run (3,157) is far better than the worst random run (7,659). But more than half its runs still settle somewhere worse. Spreading the starts out helps a lot; it doesn't guarantee anything.
See it fail: one start isn't enough
A single unlucky start can leave K-means stuck, and nothing in the output warns you. Take the worst random start from the experiment and look at its clusters' sizes:
worst_seed = int(results["random"].argmax())
_, bad_labels, bad_inertia, _ = kmeans(X, 8, init="random", seed=worst_seed)
_, good_labels, good_inertia, _ = kmeans(X, 8, init="k-means++", seed=int(results["k-means++"].argmin()))
print(f"stuck run: inertia {bad_inertia:.1f}, cluster sizes {np.sort(np.bincount(bad_labels))}")
print(f"best run: inertia {good_inertia:.1f}, cluster sizes {np.sort(np.bincount(good_labels))}")
stuck run: inertia 7658.7, cluster sizes [ 27 38 38 45 52 198 199 203]
best run: inertia 2101.7, cluster sizes [ 80 97 97 100 100 103 103 120]
np.bincount counts how many points carry each label, and np.sort orders the counts from smallest to largest.
The data has eight groups of 100 points each, and the best run finds them: cluster sizes between 80 and 120. The stuck run has three clusters of about 200, each covering two real groups, while two real groups are cut into five small pieces of 27 to 52 points. Its inertia is more than three times the best. A single run reports "inertia 7,658.7" just as calmly as "2,101.7"; only comparing several runs shows that something went wrong.
The fix is cheap: run K-means several times and keep the run with the lowest inertia, as kmeans_best_of does and scikit-learn's n_init does. Even with plain random starts, the best of 10 does well:
print(f"best of 10 random starts: inertia {kmeans_best_of(X, 8, init='random')[2]:.1f}")
best of 10 random starts: inertia 2102.3
2,102.3, within 0.03% of the best. Each single random start finds the best only about a quarter of the time, but the chance that all ten miss is small. With k-means++ starts, scikit-learn's default, even fewer starts are needed.
Your version or scikit-learn's?
| Situation | Use |
|---|---|
| Understanding what K-means does | Your own version |
| Real work, up to about a million rows | KMeans |
| Millions of rows | MiniBatchKMeans, which updates centroids from small random batches |
| Distances other than straight-line | Not K-means: try K-medoids or DBSCAN |
Practice
- Without running code: three points at 0, 4 and 10, and two centroids at 1 and 9. What are the labels and the new centroids after one round?
Show the answer
0 and 4 are nearer to 1, and 10 is nearer to 9, so the labels are [0, 0, 1]. The new centroids are the averages: 2 and 10.
One round in code, starting from the given centroids:
pts = np.array([[0.0], [4.0], [10.0]])
start_c = np.array([[1.0], [9.0]])
lab = squared_distances(pts, start_c).argmin(axis=1)
print(lab, [float(pts[lab == j].mean()) for j in range(2)])
[0 0 1] [2.0, 10.0]
- Change
kmeansso it also returns the inertia after every round. Is the list always decreasing?
Show the answer
Add history = [] before the loop and history.append(squared_distances(X, centroids).min(axis=1).sum()) after the update step, and return it. The list never increases: each assign step and each update step can only lower the inertia or leave it the same. (The empty-cluster fix is the exception: moving a centroid to the farthest point can briefly raise it.)
- Why does k-means++ use squared distance as the chance of being picked, rather than plain distance?
Show the answer
Squaring makes far points much more likely than moderately far ones, so the starting centroids spread out more. It also matches what K-means minimises, squared distance, and it's what the k-means++ guarantee of being close to the best result is proved for.
- Time both versions on the 800 points. Which is faster, and why?
Show the answer
import time
t = time.perf_counter(); kmeans_best_of(X, 8); mine = time.perf_counter() - t
t = time.perf_counter(); KMeans(n_clusters=8, n_init=10, random_state=0).fit(X); theirs = time.perf_counter() - t
print("scikit-learn faster" if theirs < mine else "mine faster")
scikit-learn faster
scikit-learn is faster. Its loop is written in compiled code rather than Python, it runs the starts in parallel, and it uses bounds that let it skip distance calculations it can prove won't change any assignment. The home-made version does the same maths, just less cleverly.
- What happens to
kmeansif two starting centroids are the same point?
Show the answer
Every point that is nearest to that spot gets the first of the two labels (argmin picks the first of equal values), so the second centroid gets no points: an empty cluster. The empty-cluster step then moves it to the farthest point, and the loop carries on. Random starts with replace=False avoid picking the same row twice, but duplicate rows in the data can still cause it.
Interview questions
Implement K-means. What are the key steps?
Initialise k centroids (randomly or with k-means++). Repeat: compute the distance from every point to every centroid, assign each point to the nearest, recompute each centroid as the mean of its points, handle empty clusters, and stop when assignments stop changing or after a maximum number of rounds. Return the centroids, labels and inertia.
How does k-means++ initialisation work, and why is it better than random?
The first centroid is a random point; each next one is sampled with probability proportional to the squared distance to the nearest chosen centroid. This spreads the starting centroids across the data, which reduces the chance of two starting in one cluster and leads to lower inertia and faster convergence.
What is the time complexity of K-means?
Each round computes n × k distances in d dimensions, so O(n · k · d) per round, times the number of rounds. In practice it converges in a few dozen rounds, so it scales roughly linearly with the number of points.
Key takeaways
- K-means is a short loop: broadcast distances,
argminto assign,meanto update, stop when nothing changes. - Starting points matter: random starts often get stuck; k-means++ spreads them out and does far better.
- Even k-means++ isn't perfect, so run several starts and keep the lowest inertia (
n_init). - An empty cluster needs a rule; moving it to the farthest point is a common one.
- The home-made version reaches the same inertia as scikit-learn on the same data.
Frequently asked questions
Why use squared distances in the code?
They give the same nearest centroid as plain distances, because squaring keeps the order of positive numbers, and they skip a square root per pair. K-means also minimises squared distances, so the inertia uses them directly.
Does K-means always converge?
Yes: there are finitely many ways to assign points to clusters, and each round lowers the inertia or ends the loop, so it can't cycle forever. It converges to a local minimum, not necessarily the best one.
What does scikit-learn's KMeans do differently?
The same loop, written in fast compiled code, using an accelerated method (Elkan's or Lloyd's with clever bounds) that skips distance calculations it can prove are unnecessary, and running several starts in parallel.
What to learn next
- Use K-means on real customers in the customer segmentation project, the next lesson.
- Revisit the ideas behind the loop in K-means clustering explained.
- Compare with another algorithm built from scratch in KNN from scratch.