Sub topic 6
Initialization: Random Starts, k-means++, and Restarts
What this chapter assumes
You should already know Lloyd's algorithm (the assign and update loop) and the inertia objective from the earlier chapters. You should be comfortable with NumPy broadcasting and with fitting a scikit-learn estimator. This chapter covers the part of k-means that runs before the loop starts: choosing the first k centroids.
Why the starting point matters
Lloyd's algorithm never increases inertia, so it always converges. It converges to a local minimum, though, and which one depends on where the centroids began. Two runs on the same data with different starting centroids can end with different clusters and different inertia values.
The usual failure is a bad split of the data. One starting centroid lands in the middle of two true groups, and two others land inside a single group. The loop then settles into a state where one centroid covers two groups and two centroids share one. No assignment or update step can fix this, because each step only improves things locally.
Three techniques deal with this. They are listed here in the order the rest of the chapter covers them:
- Random initialization, the simple baseline.
- k-means++ seeding, which spreads the starting centroids out.
- Restarts, which run the whole algorithm several times and keep the best result.
Random initialization
The simplest method, often called Forgy initialization, picks k distinct data points uniformly at random and uses them as the starting centroids. This is the line used in the NumPy implementation from the previous chapter:
centroids = X[rng.choice(len(X), size=k, replace=False)]It is cheap and easy to reason about, and it always starts the centroids inside the data. Its weakness is that nothing prevents two chosen points from sitting in the same dense group. When the groups have different sizes, a large group is likely to receive several seeds. A small, distant group is likely to receive none.
k-means++ seeding
k-means++ keeps the idea of using data points as seeds but chooses them so they tend to be far apart. The procedure is:
- Pick the first centroid uniformly at random from the data.
- For every point, compute D(x)², the squared distance to the nearest centroid chosen so far.
- Pick the next centroid from the data, where each point's probability is proportional to its D(x)².
- Repeat steps 2 and 3 until k centroids are chosen.
Points close to an existing centroid have a small D(x)² and are unlikely to be chosen. Points far from every centroid have a large D(x)² and are likely to be chosen. The method is still random, so it can occasionally make a poor choice. It is not a deterministic farthest-point rule, and that matters because a farthest-point rule would pick outliers.
The squared distance in step 3 matches the squared distance in the inertia objective. Arthur and Vassilvitskii showed in 2007 that this seeding gives an expected inertia within a factor of O(log k) of the optimal clustering, even before any Lloyd iterations run. Plain random seeding has no such guarantee.
A NumPy implementation
The function below follows the steps exactly. It keeps a running array d2 and updates it with a minimum after each new centroid, so each pass costs one distance computation per point rather than one per existing centroid.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
def kmeans_plus_plus(X, k, seed=0):
rng = np.random.default_rng(seed)
first = rng.integers(len(X))
centers = [X[first]]
d2 = ((X - X[first]) ** 2).sum(axis=1)
for _ in range(1, k):
probs = d2 / d2.sum()
idx = rng.choice(len(X), p=probs)
centers.append(X[idx])
d2 = np.minimum(d2, ((X - X[idx]) ** 2).sum(axis=1))
return np.array(centers)
X, _ = make_blobs(n_samples=500, centers=5, cluster_std=1.5, random_state=0)
init = kmeans_plus_plus(X, k=5, seed=1)
km = KMeans(n_clusters=5, init=init, n_init=1).fit(X)
print(init.shape, km.inertia_)Passing an array as init tells scikit-learn to start from exactly those centroids. In that case it uses n_init=1, since every run would be identical, and it warns if you ask for more.
The sampling step fails when d2.sum() is zero. That happens when fewer than k distinct points exist, for example in a dataset full of duplicate rows. Every remaining point then already sits on a centroid, and the probabilities become 0/0. scikit-learn's own implementation handles this case. A hand-written version like the one above does not, so check the number of distinct rows first if your data may contain many duplicates.
Restarts
Even with k-means++, the result varies from run to run, because both the seeding and the cluster structure involve chance. The standard remedy is to run the complete algorithm several times from different seeds and keep the run with the lowest inertia. In scikit-learn this is the n_init parameter.
The experiment below measures the spread in final inertia for single-start runs. It uses ten different seeds for each initialization method.
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=500, centers=5, cluster_std=1.5, random_state=0)
for init in ("random", "k-means++"):
inertias = [
KMeans(n_clusters=5, init=init, n_init=1, random_state=seed).fit(X).inertia_
for seed in range(10)
]
print(init, min(inertias), max(inertias))Read the output as a range per method. The exact values depend on your scikit-learn version, so do not expect to match any particular number. What you should compare is the gap between the minimum and the maximum. A wide gap means single runs are unreliable. A narrow gap, or a maximum that equals the minimum, means most starts reach the same solution. Both methods can show a wide gap on data with overlapping clusters. Use this experiment on your own data before you decide how many restarts you need.
Restarts and good seeding do different jobs:
| Technique | What it improves | Cost |
|---|---|---|
| k-means++ | Quality of each individual start | One extra pass over the data per centroid |
| Restarts (`n_init`) | Chance that at least one start is good | Multiplies the whole running time by `n_init` |
They combine well. Better starts mean fewer restarts are needed, and restarts protect against the occasional bad seeding.
The relevant scikit-learn parameters
| Parameter | Values | Meaning |
|---|---|---|
| `init` | `"k-means++"` (default), `"random"`, array, callable | How the starting centroids are chosen |
| `n_init` | `"auto"` (default in recent versions), or an integer | Number of complete runs from different seeds |
| `random_state` | integer or `None` | Seed that makes the initialization reproducible |
A few details are worth knowing:
- With
n_init="auto", scikit-learn runs one start forinit="k-means++"and ten forinit="random". Older versions defaulted ton_init=10for both. If you rely on the default, check your installed version, because the amount of restarting changed. - scikit-learn's k-means++ is a "greedy" variant. At each step it draws several candidate points, roughly 2 + log(k), and keeps the one that lowers the current inertia the most. This reduces variance compared with the textbook version above, so your NumPy implementation is a teaching model of the idea and not an exact copy of the library.
- The fitted attributes
inertia_,labels_, andcluster_centers_come from the best of then_initruns. The other runs are discarded and cannot be inspected.
Common errors
Trusting a single run
Setting n_init=1 with init="random" and treating the result as the answer is the most frequent mistake. The result may be a poor local minimum. Increase n_init, or use k-means++, and check that the best inertia stops improving as you add restarts.
Comparing cluster IDs between runs
Cluster numbers are arbitrary. In one run a group may be labeled 0, and in the next run the same group may be labeled 2. Comparing labels_ from two runs with == tells you nothing. Compare inertia values instead. To check whether two runs found the same partition regardless of numbering, use sklearn.metrics.adjusted_rand_score. A score of 1.0 means identical partitions.
Forgetting to fix the seed when you need reproducibility
With random_state=None, every call to fit can give a different result. Set random_state while developing, in tests, and in any report that quotes numbers. Remember that a fixed seed makes a result repeatable, not good. A single lucky or unlucky seed does not tell you how stable the clustering is.
Initializing before scaling
Initialization measures distances, so it is affected by feature scale in the same way as the main loop. If you compute seeds on raw data and then fit on scaled data, the seeds are meaningless. Put the scaler and KMeans in one pipeline so the seeding happens in the scaled space.
Empty clusters
If a starting centroid ends up with no points assigned, the update step has no mean to compute. The NumPy implementation from the earlier chapter keeps the old centroid in that case. scikit-learn instead relocates the empty centroid to a point far from its current centroid. Empty clusters are more likely with random initialization, and they are a sign that k may be too large for the data.
Choosing a restart budget in practice
Start with the defaults and measure. Fit the model with several different random_state values and look at the spread of inertia_. If every value is the same to within rounding, the clustering is stable and more restarts add cost without benefit. If values differ noticeably, raise n_init and repeat the measurement. Keep raising it until the best inertia stops changing between repeated experiments.
Running time grows linearly with n_init. For a large dataset, ten restarts can mean waiting ten times as long, which is one reason the mini-batch variant in the last chapter exists.
Exercise
A colleague fits KMeans(nclusters=4, init="random", ninit=1) on the same data with randomstate=0 and randomstate=1. The two models report different inertia values and different labels for the first ten rows. Does this show a bug? What two things would you check or change?
Show answer
It does not show a bug. Different seeds give different starting centroids, and Lloyd's algorithm can end in different local minima. The differing labels on their own mean little, because cluster numbers are arbitrary. To check the result, compare inertia values or use adjustedrandscore on the two label arrays. To get a more reliable model, increase ninit or switch to init="k-means++", and keep the run with the lowest inertia.
Exercise
In k-means++, why is the next centroid sampled with probability proportional to D(x)² and not simply set to the point with the largest D(x)?
Show answer
Choosing the single farthest point is deterministic and tends to select outliers, which would waste a centroid on one isolated point. Sampling in proportion to D(x)² still favors distant points but gives every point some chance, so dense regions far from existing centroids are likely to receive a seed. The squared distance also matches the squared distance in the inertia objective, which is what gives the O(log k) expected guarantee.
Exercise
You fit KMeans on a dataset with ninit=10 and find that the printed inertia is lower than the inertia from any single run you remember seeing. Is that surprising? What does scikit-learn do with the other nine runs?
Show answer
It is not surprising. With ninit=10, scikit-learn runs the whole algorithm ten times from different starts and keeps only the run with the lowest inertia, so inertia is the minimum of ten outcomes. The other nine runs are discarded, and their labels and centroids cannot be inspected afterward.