Sub topic 6
Initialization: random starts, k-means++, and restarts
This chapter assumes you know Lloyd's algorithm (assign points to the nearest centroid, then move each centroid to the mean of its points) and the inertia objective. It also assumes basic NumPy and scikit-learn. Here you will see why the starting centroids matter and how to choose them well.
Why the starting point matters
Lloyd's algorithm never increases inertia, so it always stops. It stops at a local minimum, though, and which minimum it reaches depends on the initial centroids. Two runs on the same data can produce different clusters and different final inertia.
Bad starts have a typical shape. If two initial centroids land inside the same true cluster, they split it between them. A different true cluster may then get no centroid of its own and be merged with a neighbor. Lloyd's algorithm cannot repair this, because each step only makes small local moves.
Random initialization
The simplest method, used in the NumPy implementation earlier in this tutorial, picks k distinct data points uniformly at random as the starting centroids. It is cheap and easy to explain. Its weakness is that it ignores geometry. Dense regions hold more points, so they are more likely to receive several seeds, while small or distant clusters are easily missed.
k-means++
k-means++ spreads the seeds out while keeping the randomness. It builds the centroid set one point at a time:
- 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, with each point chosen with probability proportional to D(x)².
- Repeat steps 2 and 3 until k centroids are chosen.
Points far from every current centroid have a large D(x)², so they are likely to be picked. Points that sit on an existing centroid have D(x)² = 0 and cannot be picked again. The method is still random, so it does not always take the farthest point. That matters because the farthest point is often an outlier.
Here is the seeding step in NumPy:
import numpy as np
def kmeans_pp_init(X, k, seed=0):
rng = np.random.default_rng(seed)
centroids = [X[rng.integers(len(X))]]
for _ in range(k - 1):
# Squared distance from each point to its nearest chosen centroid
diffs = X[:, None, :] - np.array(centroids)[None, :, :]
d2 = (diffs ** 2).sum(axis=2).min(axis=1)
probs = d2 / d2.sum()
centroids.append(X[rng.choice(len(X), p=probs)])
return np.array(centroids)
rng = np.random.default_rng(1)
X = rng.normal(size=(200, 2))
print(kmeans_pp_init(X, k=4).shape) # (4, 2)The seeding costs about k passes over the data. That is small compared with the many iterations of Lloyd's algorithm that follow. The k-means++ authors also proved that the expected inertia of the seeds is within a factor of O(log k) of the optimum. Random initialization has no such guarantee.
scikit-learn's version adds one refinement. At each step it draws several candidate points and keeps the one that lowers inertia the most.
Restarts
Even good seeding does not remove the randomness. The standard fix is to run the whole algorithm several times from different seeds and keep the run with the lowest inertia. In scikit-learn this is the n_init parameter. Because inertia is the objective being minimized, comparing it across runs is valid for a fixed k.
Comparing the methods
The next script runs single-start k-means ten times with each initialization and prints the best and worst final inertia:
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 gap between the minimum and maximum. A wide gap means single runs are unreliable and restarts are worth the cost. With k-means++ the gap is usually smaller, and the worst run is usually better than the worst random run. The exact numbers depend on your data and library version.
Practical settings
| Setting | Meaning | Advice |
|---|---|---|
| `init="k-means++"` | Spread-out seeding | Default. Keep it unless you have a reason not to. |
| `init="random"` | Uniform random points | Mainly for comparison. Use more restarts with it. |
| `init=array` | Your own starting centroids | Use for reproducible warm starts. Set `n_init=1`. |
| `n_init` | Number of full runs | More runs cost more time and reduce bad outcomes. |
Recent scikit-learn versions default to n_init="auto". This means 1 run with k-means++ and 10 runs with random. Older versions defaulted to 10, so check your version's documentation when comparing results. Set random_state so that results are reproducible.
Common errors
- Comparing inertia across different values of k to pick the best run. Inertia falls as k grows, so only compare runs with the same k.
- Setting
n_init=1and treating the output as the answer. One run is one sample from a distribution of outcomes. - Passing an explicit
initarray while leavingn_initabove 1. The repeated runs would all start from the same seeds, so scikit-learn warns and runs only once. - Forgetting that k-means++ is random too. Without
random_state, results change between runs.
Exercise
You run KMeans with init="random" and ninit=1 on the same data with ten different randomstate values. The final inertia ranges from 410 to 690. What two changes would most reduce this spread, and how does scikit-learn decide which run to return when n_init is greater than 1?
Show answer
Switch to init="k-means++" so seeds are spread across the data, and raise ninit so several full runs are made. With ninit greater than 1, scikit-learn runs the whole algorithm that many times from different seeds and returns the run with the lowest inertia.