Okay-means++ is the default option to begin k-means, and on ten well-separated teams of factors it earns that place. Throughout 100 seeds, half of its runs completed inside 1% of one of the best clustering discovered, in opposition to 5% of runs from random begins. On 1,347 handwritten digits, the identical seeding made no measurable distinction: 49% of runs reached that mark both means. Solely restarts mounted the digits.
This text builds k-means from the target up. It really works one instance by hand, implements Lloyd’s algorithm and k-means++ seeding in about 80 strains of NumPy, and checks the end result in opposition to scikit-learn. It then measures the 2 beginning guidelines over 100 seeds on two datasets and chooses okay on the wine knowledge. A C++17 model reads the identical beginning centres and prints the identical report because the Python one. Each program ran on Ubuntu 24.04.5 with Python 3.15.2 and on Home windows 11 with Python 3.14.6, each with NumPy 2.5.5 and scikit-learn 1.9.1, and printed the identical outcomes.
What Is Okay-Means Clustering?
Briefly, k-means clustering is an unsupervised algorithm that locations okay centres in order that the overall squared distance from every row to its nearest centre is as small as potential. Every row belongs to the cluster of its nearest centre. No one provides labels: the algorithm sees solely the characteristic values, and also you select okay.
The amount it minimises is known as the inertia, or the within-cluster sum of squares:
Right here xi is row i, ci is the cluster it belongs to, and μci is that cluster’s centre. Decrease inertia means tighter clusters, and inertia at all times falls as okay grows, so it can’t select okay by itself.
Okay-means fits numeric options on comparable scales, teams which are roughly spherical and related in measurement, and datasets giant sufficient {that a} quick, easy technique issues. Buyer segmentation, color quantisation and compressing a characteristic area earlier than a supervised mannequin are typical makes use of. It matches poorly when clusters are lengthy, curved, nested or very totally different in density, and it forces each row right into a cluster, together with outliers. The kinds of machine studying article locations it among the many different unsupervised strategies.
How Lloyd’s Algorithm Works
The usual process is Lloyd’s algorithm, revealed by Stuart Lloyd in 1982 as a technique for quantising alerts. It alternates two steps that every decrease the inertia:
- Project: give each row to its nearest centre, by squared Euclidean distance.
- Replace: transfer each centre to the imply of the rows assigned to it.
Sj is the set of rows in cluster j and |Sj| is what number of there are. The imply is the purpose that minimises the squared distance to a set set of rows, which is why the replace step can by no means elevate the inertia. The project step can’t elevate it both, as a result of each row strikes solely to a better centre.
Because the inertia by no means rises and there are finitely some ways to assign rows, the loop at all times stops. The place it stops is the catch. Lloyd’s algorithm finds a neighborhood minimal that relies upon solely on the beginning centres, and a foul begin can depart two centres sharing one actual group whereas one other group has none.
Two sensible guidelines full the algorithm. The loop stops when the centres barely transfer: scikit-learn stops when the overall squared shift falls under tol occasions the imply characteristic variance, with tol = 1e-4, and the code right here makes use of the identical rule. A cluster that finally ends up empty wants a brand new centre; each scikit-learn and this code transfer it to the row farthest from its present centre.
A Labored Instance by Hand
Take six factors, A (1, 1), B (2, 1), C (1, 2), D (4, 3), E (5, 4) and F (4, 4), and okay = 2. Begin intentionally badly, with each centres at neighbouring factors A and B.
begin: c1 = A (1, 1), c2 = B (2, 1)
step 1: c1 will get AC, c2 will get BDEF, inertia 40; new c1 (1, 1.5), c2 (3.75, 3)
step 2: c1 will get ABC, c2 will get DEF, inertia 5.4375; new c1 (1.333, 1.333), c2 (4.333, 3.667)
step 3: c1 will get ABC, c2 will get DEF, inertia 2.66667; new c1 (1.333, 1.333), c2 (4.333, 3.667)
lloyd(): 3 iterations, last inertia 2.667
In step 1, A and C are nearer to A, whereas B, D, E and F are nearer to B. The inertia is 0 + 0 + 1 + 8 + 18 + 13 = 40. The brand new centre for the second group is the imply of B, D, E and F, which is (3.75, 3). In step 2, B is now nearer to the primary centre, so the clusters turn into ABC and DEF and the inertia drops to five.4375. Step 3 modifications no project, the centres cease transferring, and the ultimate inertia is 8/3, about 2.667.
The dangerous begin price one additional step right here and nothing extra. With extra clusters and noisier knowledge, it may price the proper reply.
Okay-Means++: Seeding With Squared Distances
David Arthur and Sergei Vassilvitskii proposed k-means++ at SODA 2007 to make dangerous begins unlikely. The primary centre is a row chosen uniformly at random. Every later centre is a row drawn with likelihood proportional to its squared distance to the closest centre chosen to this point:
D(x) is the space from row x to its nearest current centre. Rows removed from each centre are doubtless picks, and a row that already is a centre has likelihood zero. The paper proves that the seeding alone has an anticipated inertia inside an element of 8(ln okay + 2) of the optimum, earlier than Lloyd’s algorithm improves it additional.
On the six factors, with A selected first:
k-means++ after selecting A primary: D(x)^2 and the prospect of changing into c2
A: 0 0.000
B: 1 0.017
C: 1 0.017
D: 13 0.224
E: 25 0.431
F: 18 0.310
probability that c2 lands within the D, E, F group: 0.966
The second centre lands within the D, E, F group with likelihood 56/58, about 0.966. A uniform draw would put it there half the time.
scikit-learn does a bit of extra by default. Its kmeans_plusplus attracts 2 + ln okay candidates, rounded down, for every new centre and retains the one which lowers the inertia most. Its documentation calls this the grasping variant and says that n_local_trials=1 recovers the plain algorithm. Each seem within the measurement under.
Okay-Means in Python From Scratch
The implementation wants NumPy solely. The gap perform compares each row with each centre in a single broadcast, the identical sample the NumPy for machine studying tutorial builds step-by-step:
def squared_distances(X: FloatArray, facilities: FloatArray) -> FloatArray:
"""Squared Euclidean distance from each row of X to each centre: (n, okay)."""
diff = X[:, None, :] - facilities[None, :, :]
out: FloatArray = np.einsum("ijk,ijk->ij", diff, diff)
return out
def random_init(X: FloatArray, okay: int, rng: np.random.Generator) -> FloatArray:
"""Forgy initialisation: okay distinct rows chosen uniformly at random."""
return X[rng.choice(len(X), size=k, replace=False)].copy()
def kmeans_plusplus(X: FloatArray, okay: int, rng: np.random.Generator) -> FloatArray:
"""k-means++: every new centre is a row drawn with likelihood D(x)^2 / sum D^2."""
n = len(X)
facilities = np.empty((okay, X.form[1]))
facilities[0] = X[rng.integers(n)]
d2 = squared_distances(X, facilities[:1])[:, 0]
for j in vary(1, okay):
complete = d2.sum()
# each row already sits on a centre: any alternative prices nothing
idx = rng.integers(n) if complete == 0 else rng.alternative(n, p=d2 / complete)
facilities[j] = X[idx]
d2 = np.minimal(d2, squared_distances(X, facilities[j : j + 1])[:, 0])
return facilities
The replace step and the loop comply with. The replace handles the empty-cluster case, and the loop stops on scikit-learn’s rule:
def update_centers(
X: FloatArray, labels: IntArray, facilities: FloatArray, d2_min: FloatArray
) -> FloatArray:
"""Imply of every cluster. An empty cluster takes the row farthest from its
centre, and that row leaves the cluster it was assigned to."""
okay = len(facilities)
counts = np.bincount(labels, minlength=okay)
sums = np.zeros_like(facilities)
np.add.at(sums, labels, X)
far = np.argsort(-d2_min, form="steady")
for taken, j in enumerate(np.flatnonzero(counts == 0)):
row = far[taken]
sums[labels[row]] -= X[row]
counts[labels[row]] -= 1
sums[j], counts[j] = X[row], 1
return sums / np.most(counts, 1)[:, None]
@dataclass
class LloydResult:
facilities: FloatArray
labels: IntArray
inertia: float
n_iter: int
historical past: listing[float] = discipline(default_factory=listing)
def lloyd(
X: FloatArray, facilities: FloatArray, max_iter: int = 300, tol: float = 1e-4
) -> LloydResult:
"""Alternate the project and replace steps till the centres cease transferring:
the overall squared shift falls to tol occasions the imply characteristic variance, the
stopping rule scikit-learn makes use of. Unchanged labels give a shift of zero."""
tol_abs = tol * float(np.imply(np.var(X, axis=0)))
C = facilities.astype(np.float64, copy=True)
historical past: listing[float] = []
for it in vary(1, max_iter + 1):
d2 = squared_distances(X, C)
labels = d2.argmin(axis=1)
d2_min = d2[np.arange(len(X)), labels]
historical past.append(float(d2_min.sum()))
new = update_centers(X, labels, C, d2_min)
shift = float(((new - C) ** 2).sum())
C = new
if shift <= tol_abs:
break
# the centres moved after the final project, so assign as soon as extra
d2 = squared_distances(X, C)
labels = d2.argmin(axis=1).astype(np.int64)
inertia = float(d2[np.arange(len(X)), labels].sum())
return LloydResult(C, labels, inertia, it, historical past)
The ultimate project after the loop issues. The loop ends simply after an replace, so the final labels belong to the earlier centres; assigning as soon as extra makes the labels, centres and inertia describe the identical state. The KMeans class within the repository wraps this with enter checks, a alternative of init and n_init restarts that maintain the run with the bottom inertia.
Began from an identical centres, this code and scikit-learn’s KMeans produce the identical labels, the identical centres to 1e-10, the identical inertia and the identical iteration rely. The assessments examine this for ten begins on the standardised wine knowledge and ten on artificial blobs.
Okay-Means With scikit-learn
In observe, scale the options and match scikit-learn’s KMeans inside a pipeline, so the scaler learns solely from the coaching rows:
from sklearn.metrics import adjusted_rand_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from knowledge import wine_split
X_train, X_test, _, y_test = wine_split()[:4]
mannequin = make_pipeline(StandardScaler(), KMeans(n_clusters=3, n_init=10, random_state=0))
mannequin.match(X_train)
kmeans = mannequin[-1]
print(f"inertia {kmeans.inertia_:.1f} after {kmeans.n_iter_} iterations")
print(f"cluster sizes {sorted(int((kmeans.labels_ == j).sum()) for j in vary(3))}")
print(f"held-out ARI {adjusted_rand_score(y_test, mannequin.predict(X_test)):.3f}")
inertia 951.5 after 7 iterations
cluster sizes [39, 46, 48]
held-out ARI 0.862
The adjusted Rand index (ARI) compares the clusters of the 45 held-out wines with their true cultivars: 1 is ideal settlement, and 0 is what random labels rating. Since scikit-learn 1.4, n_init defaults to "auto", which implies one run with k-means++ and ten with random begins. The subsequent part reveals when that default is sufficient.
Does Okay-Means++ Beat Random Begins?
The query: does k-means++ seeding slender the unfold of ultimate inertia throughout seeds, and does it enhance the clusters on held-out rows? Every technique ran 100 occasions with one begin per run, utilizing the identical Lloyd code, so solely the beginning centres differ. “Better of 10 random” retains the lowest-inertia run of ten random begins. Inertia is measured on the coaching rows; ARI is measured on held-out rows assigned to the educated centres.
Two datasets had been used. The digits knowledge has 1,797 pictures of 8 × 8 pixels, cut up into 1,347 coaching and 450 take a look at rows, with ten digit lessons that overlap. The blobs are 1,500 artificial factors in ten dimensions round ten well-separated centres, cut up 1,125 and 375.
digits: 1,347 coaching rows, okay=10, 100 seeds per technique
lowest coaching inertia discovered by any run: 865,067.4
technique seed price inertia std worst inside 1% iters take a look at ARI std min
random 1,695,002 882,344 18,153 939,767 49% 17.4 0.591 0.044 0.460
k-means++ 1,663,689 883,265 17,654 939,118 49% 18.1 0.594 0.046 0.461
sklearn plain 1,653,604 884,085 19,108 939,828 43% 18.3 0.586 0.053 0.401
sklearn grasping 1,482,026 876,460 15,296 932,000 63% 16.4 0.611 0.046 0.455
random x10 865,774 1,472 871,508 100% 18.7 0.643 0.023 0.570
blobs: 1,125 coaching rows, okay=10, 100 seeds per technique
lowest coaching inertia discovered by any run: 10,946.2
technique seed price inertia std worst inside 1% iters take a look at ARI std min
random 147,736 43,827 17,985 86,821 5% 9.3 0.764 0.110 0.485
k-means++ 41,460 19,080 9,364 49,888 50% 5.4 0.926 0.080 0.681
sklearn plain 46,704 21,045 9,945 49,121 39% 6.4 0.913 0.074 0.751
sklearn grasping 21,128 11,152 1,448 21,237 98% 2.1 0.997 0.019 0.866
random x10 19,238 7,478 35,200 40% 7.2 0.920 0.066 0.759
“Seed price” is the inertia of the beginning centres earlier than Lloyd’s algorithm runs. “Inside 1%” counts runs whose last inertia got here inside 1% of the bottom inertia any run discovered.
On the blobs, plain k-means++ lower the imply last inertia from 43,827 to 19,080 and raised the held-out ARI from 0.764 to 0.926. A single k-means++ begin did about in addition to one of the best of ten random begins. The grasping variant ended inside 1% of one of the best clustering in 98 of 100 runs, after 2.1 iterations on common.
On the digits, plain k-means++ lowered the seed price by solely 2%. The ultimate outcomes had been indistinguishable from random begins: 49% of runs inside 1% in each circumstances, and a held-out ARI of 0.594 in opposition to 0.591. The grasping variant helped a bit of, at 63% inside 1% and an ARI of 0.611. Solely restarts eliminated the dangerous runs: each best-of-ten run completed inside 1%, with the best ARI at 0.643.
The 2 plain k-means++ rows, from this code and from scikit-learn with one trial, differ solely of their random quantity streams. Their hole, 0.594 in opposition to 0.586 in ARI, reveals the scale of distinction that 100 seeds can’t resolve. Learn the 0.003 hole between random and k-means++ on the digits the identical means: as no distinction.
Why the cut up? When teams are far aside, a random begin typically locations two centres in a single group. Lloyd’s algorithm can’t transfer a centre throughout the empty area between teams, and the blob runs that stopped close to 100% above one of the best are these circumstances. Squared-distance sampling prevents precisely that. When teams overlap, because the digits do in 64 dimensions, the farthest rows are typically uncommon handwriting moderately than unvisited teams, so the weighting buys little. That clarification is a reasoned studying of the 2 outcomes, not a measured trigger.
For observe, the measurement factors a method on this knowledge: use k-means++ and nonetheless run a number of begins. That’s what n_init=10 does.
Methods to Select okay: Elbow and Silhouette
Okay-means can’t inform you what number of clusters exist, so okay wants outdoors proof. The 2 widespread heuristics are the elbow technique and the silhouette rating.
The elbow technique plots inertia in opposition to okay and appears for the purpose the place including a cluster stops paying. The silhouette of a row compares its imply distance to its personal cluster with its imply distance to the closest different cluster, scaled from −1 to 1; the imply silhouette rewards tight, separated clusters. On the wine knowledge, standardised with the coaching rows’ imply and customary deviation, with one of the best of 10 k-means++ begins for every okay:
wine, standardised, better of 10 k-means++ begins per okay
okay inertia drop silhouette held-out
2 1245.3 0.255 0.273
3 951.1 24% 0.288 0.270
4 872.5 8% 0.275 0.251
5 806.9 8% 0.255 0.235
6 772.1 4% 0.193 0.121
7 719.2 7% 0.157 0.113
8 682.6 5% 0.182 0.058
The inertia falls by 24% from okay = 2 to three and by 8% or much less after that, so the elbow factors to three. The coaching silhouette additionally peaks at 3, at 0.288. The held-out silhouette, computed on the 45 take a look at wines assigned to the educated centres, offers 0.273 for okay = 2 and 0.270 for okay = 3, which is a tie, not a verdict.
The info has three cultivars, so 3 is the proper reply right here, however the heuristics solely agree loosely. Silhouette values round 0.27 to 0.29 describe overlapping clusters, not crisp ones. Deal with each strategies as proof to weigh with area data, and like a okay the downstream use can act on.
Okay-Means in C++
The C++ model is a header-only C++17 file with no dependencies. Its project loop is the half that does the work:
// Nearest centre for each row; returns the squared distance to it.
inline void assign(const Matrix& X, const Matrix& C, std::vector<int>& labels,
std::vector<double>& d2min)
{
for (std::size_t i = 0; i < X.rows; ++i) {
double greatest = std::numeric_limits<double>::infinity();
int arg = 0;
for (std::size_t j = 0; j < C.rows; ++j) {
const double d = squared_distance(X.row(i), C.row(j), X.cols);
if (d < greatest) { // strict: the bottom index wins a tie
greatest = d;
arg = static_cast<int>(j);
}
}
labels[i] = arg;
d2min[i] = greatest;
}
}
The strict < retains the decrease index on a tie, as NumPy’s argmin does, and the replace and stopping guidelines mirror the Python file line for line. Random numbers come from splitmix64 moderately than std::discrete_distribution, as a result of the usual distributions could produce totally different values on totally different compilers.
Given the 1,347 digits coaching rows and ten beginning centres written by the Python program, each variations print the identical report:
rows 1347, options 64, okay 10
iterations 21
inertia 873910.3355
cluster sizes 313 173 69 66 139 61 112 134 151 129
first 40 labels 9199821691571106641070274079214440001901
centre 0, first 8 pixels 0.0000 0.3834 7.2907 13.3323 12.7636 6.0096 0.5112 0.0000
CTest compares the C++ output with the identical anticipated file the Python take a look at reads, so the 2 can’t drift aside unnoticed. The identical run was timed on one thread, median of repeated runs, on the Ubuntu machine:
| Implementation | Iterations | Median time | Per iteration |
|---|---|---|---|
| Plain Python lists | 21 | 2,149 ms | 102.3 ms |
NumPy (kmeans.py) |
21 | 69.6 ms | 3.32 ms |
C++17, g++ 13.3 -O2 |
21 | 10.8 ms | 0.51 ms |
| scikit-learn 1.9.1 | 24 | 5.8 ms | 0.24 ms |
The quickest entry just isn’t the compiled loop however the library that modifications the arithmetic. scikit-learn expands the squared distance into ‖x‖² − 2x·μ + ‖μ‖², so many of the work turns into one matrix product, and it runs that product in blocks that keep in cache. The NumPy model builds a full rows × centres × options array as a substitute, which is clearer however slower. The machine studying with C++ article covers when transferring mannequin code to C++ pays off.
Widespread Errors With Okay-Means
Forgetting to scale the options is the most costly mistake. On the uncooked wine knowledge, proline is measured within the lots of and carries 99.7% of the overall variance, so the distances are virtually all proline. Fitted on uncooked options, okay = 3 gave a held-out ARI of 0.332; after standardising, the identical setup gave 0.862.
Trusting one begin is the second. On the digits, single runs ended wherever from one of the best clustering discovered to eight.6% above it, and one of the best of ten random begins by no means ended greater than 0.75% above it. If the library defaults to 1 run, set n_init your self.
Evaluating inertia throughout totally different values of okay is a 3rd. Inertia at all times falls as okay grows, so a decrease quantity at a bigger okay says nothing about which okay is correct.
Studying clusters as lessons is a fourth. Even the best-of-ten digits runs averaged a held-out ARI of 0.643, removed from 1. Okay-means discovered actual construction, however it didn’t uncover the ten digits, and a cluster’s label quantity means nothing till somebody inspects its members.
Quoting in-sample scores as in the event that they generalise is the final. Inertia and the coaching silhouette are each computed on the rows the centres had been fitted to. To evaluate the clustering, assign held-out rows to the educated centres and rating these, as each ARI on this article does.
Okay-means assumes spherical, equally sized clusters and assigns each row someplace. When these assumptions fail, one other algorithm is the higher begin:
| State of affairs | Okay-means does | Better option |
|---|---|---|
| Clusters overlap and also you want membership possibilities | Onerous assignments solely | Gaussian combination fashions |
| Clusters are curved or of very totally different density | Cuts them with straight boundaries | DBSCAN or HDBSCAN |
| Outliers ought to keep unassigned | Forces them right into a cluster and lets them pull the centre | DBSCAN |
| You want the nested construction, or okay is unknown | One flat partition for a set okay | Hierarchical clustering |
| Options are categorical | Means and Euclidean distance are undefined | k-modes, or encode and use one other technique |
| Hundreds of thousands of rows | Full passes over the information per iteration | Mini-batch k-means |
The place k-means does match, it’s the quickest and easiest of those, and its centres are simple to elucidate. That’s the reason it stays the primary clustering technique to attempt on numeric knowledge, the identical function k-nearest neighbors performs among the many distance-based classifiers.
Supply Code and Assessments
The Python code is within the machine-learning/k-means listing of the MYCPLUS Python examples repository, and the C++ model is in the matching listing of the C++ examples repository.
python -m pip set up -r requirements-dev.txt
python worked_example.py
python -m unittest uncover -s assessments -v
sh run_all.sh
The 21 Python assessments cowl the labored instance, settlement with scikit-learn, and inertia that by no means rises. Additionally they examine the mounted level at convergence, a stopping rule that ignores items, empty clusters, the k-means++ odds, restarts and enter validation. A mutation script places 12 believable bugs into a replica of the code, similar to Manhattan distance, sampling by distance as a substitute of squared distance, or an unscaled tolerance, and each one makes a take a look at fail. The C++ suite catches all 11 of its personal planted bugs, and CI builds it with GCC, Clang and MSVC, with sanitizers on Linux.
The methodology behind the splits, seeds and baselines is described in how we take a look at machine studying code.
What I Verified
| Verify | Ubuntu 24.04.5 | Home windows 11 |
|---|---|---|
| Atmosphere | Python 3.15.2, NumPy 2.5.5, scikit-learn 1.9.1; g++ 13.3, clang++ 18.1 | Construct 26300, Python 3.14.6, NumPy 2.5.5, scikit-learn 1.9.1 |
| 21 Python assessments, ruff, mypy strict | Go | Go |
| Three applications print the anticipated output | Byte for byte | Byte for byte |
init_experiment.py, choose_k.py, tie_check.py |
Tables as proven | Equivalent tables |
| Mutation examine, Python | 12 of 12 caught | 12 of 12 caught |
| C++ construct and CTest | g++ and clang++, C++17 and C++20; AddressSanitizer, UBSan and Valgrind clear | MSVC, Launch, in CI |
| C++ report equals Python report | Equivalent | Equivalent, in CI |
| Mutation examine, C++ | 11 of 11 caught | Not run (Linux solely) |
Not lined: macOS, ARM, different library variations, datasets past the three used, and any declare that the digits end result holds for different overlapping knowledge.

