k-means and vector quantization
The k-means objective, Lloyd's algorithm, k-means++ initialization, vector quantization and alternatives.
After this lesson you can
- Derive Lloyd assignment and update steps as block coordinate descent on inertia.
- Prove Lloyd's monotonicity and finite termination.
- Implement vectorized k-means with k-means++ and compare initialization outcomes.
- Identify k-means assumptions and diagnose violations.
- Use k-medoids with non-Euclidean dissimilarity and mini-batch k-means for large data.
Before you start
Motivation: three assignments, one problem
An online store wants to divide customers into five or six segments to decide whom to contact about what. An imaging team wants to store a photograph with only 16 colors without noticeable degradation. A vector search system wants to represent each of its hundred million vectors by a single number between 0 and 255, the index of a representative. These assignments look different but share a structure: choose representatives in data space and assign each datum to its nearest representative, minimizing what is lost by replacing each datum with its representative.
That structure has two names. Viewed as a way to discover groups, it is k-means, probably the most widely used clustering method. Viewed as compression, it is vector quantization. They are the same optimization problem, and each tradition contributes something: clustering asks whether the groups exist; compression offers a precise theory of the cost of each bit.
This lesson does four things. First it specifies what is minimized (inertia) and proves two identities that explain almost everything about it. It then derives Lloyd’s algorithm as coordinate descent, proves it terminates and explains why it is nevertheless a heuristic: the problem is NP-hard and Lloyd can end arbitrarily far from optimal. This motivates k-means++, replacing blind seeding with a guarantee, and variants that scale. Finally it examines k-means as a compressor (codebooks, distortion–rate curve) and critically: the geometric assumptions that sometimes make it fail and alternatives (k-medoids, kernel k-means) when the mean is no longer the right representative.
Inertia: what is minimized
Let be the data and the number of representatives. An assignment is a function , meaning a partition with .
Note two things. Distance is squared: a point far from its representative costs much more than several nearby points, making k-means sensitive to outliers. And is not convex (the over breaks convexity), so a local method is not guaranteed to find the global minimum.
The first result identifies the best representative of a group and provides a second interpretation of inertia without representatives.
Proof
Write and expand the square. The cross term is , because deviations from the mean sum to zero. This leaves (1). Since and vanishes only at , the mean is the unique minimizer.
For (2), apply (1) with and sum over :
∎Three consequences are used constantly.
- For a fixed partition, optimal representatives are means . That is why the algorithm is called k-means.
- Inertia is pairwise compactness: by (2), . Minimizing asks that, within each group, mean squared pairwise distance be small. This interpretation mentions no centroid.
- Within plus between is constant. Applying (1) to each group with (the global mean), total dispersion decomposes into , with within-group dispersion and between-group dispersion. Since does not depend on the partition, minimizing is equivalent to maximizing : separating centroids and tightening groups are the same thing. Validity indices in lesson 7 (for example Calinski–Harabasz) are ratios of these quantities.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3)) * [1.0, 2.0, 3.0] + 5.0
lab = rng.integers(0, 4, size=200) # una partición cualquiera en 4 grupos
mu = X.mean(0)
T = ((X - mu) ** 2).sum() # dispersión total
W = B = 0.0
for j in range(4):
Xj = X[lab == j]
mj = Xj.mean(0)
W += ((Xj - mj) ** 2).sum() # dentro de los grupos: la inercia
B += len(Xj) * ((mj - mu) ** 2).sum() # entre grupos
D2 = ((Xj[:, None, :] - Xj[None, :, :]) ** 2).sum(2)
assert np.isclose(((Xj - mj) ** 2).sum(), D2.sum() / (2 * len(Xj))) # identidad de pares
print(f"T = {T:.3f} W + B = {W + B:.3f} (W = {W:.3f}, B = {B:.3f})")Lloyd’s algorithm
With identity (1), the algorithm follows directly. Inertia depends on two variable blocks, assignment and representatives , and each block is minimized exactly when the other is fixed. This is block coordinate descent (alternating minimization).
- Block with fixed. The sum separates by data point: each chooses the minimizing . The set of points in space preferring is the Voronoi cell (Voronoi diagrams). Since , each cell is an intersection of half-spaces: a convex polyhedron bounded by bisectors.
- Block with fixed. The sum separates by groups and each minimizes : it is the mean, by the previous theorem.
Assignment does not require calculating the full distance: since and the first term is the same for all , it suffices to minimize , a matrix product costing . Updating costs . These are per-iteration costs, linear in each quantity.
The figure has two lessons. First, descent is clean: inertia falls at each half-step and the graph is a staircase. Second, where it ends depends on where it starts. With two centroids in one group, the third is trapped between two groups that do not belong to it, and no Lloyd step gets it out: each point is in its nearest centroid’s cell and each centroid is its cell’s mean. This state is a fixed point and need not be the best.
Convergence: monotonicity, termination and local optima
Proof
Let be the means of groups in (an empty group retains its previous centroid and contributes nothing to ). There are two inequalities:
The second is assignment: with fixed, minimizes each term separately, so cannot be worse than . It is strict if any datum changes group, because the tie-breaking rule permits a change only to a strictly closer centroid. The first is the update: with fixed, means minimize each group (previous theorem).
If , inertia strictly decreases, and since depends only on the partition, no partition can repeat. There are only possible assignments, so after at most changes the assignment repeats. Then (means of the same partition) and the algorithm stops.
∎Read carefully what the theorem does not say. Monotone is not convergent to the minimum: the inertia sequence converges to a value that may be far from optimal. And is a ridiculous iteration bound; in practice tens suffice (below, in what sense and with what caveats).
What is a fixed point mathematically? If no datum is equidistant from two centroids and no group is empty, assignment is constant in a neighborhood of and there equals a sum of strictly convex quadratics, one per group, each minimized at its mean. It is a strict local minimum of as a function of centroids. (With an empty group, does not locally depend on that centroid and the minimum is no longer strict: the centroid is redundant.) But Lloyd does not explore perturbations that change assignment all at once.
Empty groups. No datum may choose a centroid. Its mean does not exist. Common solutions are to leave it where it is (with a useless representative) or relocate it to the worst-represented datum, the one farthest from its centroid: the next step then safely reduces , as in the implementation below.
Implementation from scratch
With Lloyd’s theory in hand, here is its vectorized NumPy implementation with empty-group handling. The performance key is calculating all distances at once using the expansion
which turns the work into a matrix product. The expansion, however, costs precision, and sqdist clips the negatives produced by cancellation (below, with an example visible to the eye).
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
def sqdist(X, C):
"""||x - c||^2 para todos los pares con ||x||^2 - 2 x.c + ||c||^2; el recorte quita los negativos de la cancelación."""
d2 = (X * X).sum(1)[:, None] - 2.0 * (X @ C.T) + (C * C).sum(1)[None, :]
return np.maximum(d2, 0.0)
def lloyd(X, C0, max_iter=300):
"""Lloyd: asignar al centroide más cercano y llevar cada centroide a la media de su grupo."""
C = C0.astype(float).copy()
k = len(C)
labels = None
for it in range(1, max_iter + 1):
D = sqdist(X, C)
new = D.argmin(1)
if labels is not None and np.array_equal(new, labels):
break # la asignación no cambia: punto fijo
labels = new
cnt = np.bincount(labels, minlength=k)
S = np.stack([np.bincount(labels, weights=X[:, j], minlength=k) for j in range(X.shape[1])], axis=1)
for j in np.flatnonzero(cnt == 0): # grupo vacío: se recoloca en el punto peor representado
far = D[np.arange(len(X)), labels].argmax()
C[j] = X[far]
D[far, labels[far]] = 0.0
full = cnt > 0
C[full] = S[full] / cnt[full, None]
inertia = sqdist(X, C)[np.arange(len(X)), labels].sum()
return C, labels, inertia, it
# validación: con los mismos centroides iniciales y tol=0, sklearn recorre exactamente los mismos pasos
X, _ = make_blobs(n_samples=600, centers=5, cluster_std=1.2, random_state=3)
C0 = X[np.random.default_rng(0).choice(len(X), 5, replace=False)] # cinco datos al azar
C, lab, J, it = lloyd(X, C0)
sk = KMeans(n_clusters=5, init=C0, n_init=1, algorithm="lloyd", tol=0.0, max_iter=300).fit(X)
print(f"propia: inercia {J:.6f} en {it} iteraciones | sklearn: {sk.inertia_:.6f} en {sk.n_iter_}")
print("diferencia relativa de inercias:", abs(J - sk.inertia_) / sk.inertia_)
print("particiones distintas salvo permutación:", len(set(zip(lab, sk.labels_))) - 5)Validation is strict, not merely “similar”: with the same initial centroids and tol=0 (no early stop before assignment stabilizes), scikit-learn follows exactly the same steps, so inertias agree up to rounding and partitions are identical up to label permutation.
rng = np.random.default_rng(0)
X32 = (3000.0 + 0.05 * rng.standard_normal((6, 2))).astype(np.float32) # puntos casi iguales y lejos del origen
c = X32[:1]
exacta = ((X32.astype(np.float64) - c.astype(np.float64)) ** 2).sum(1)
expandida = (X32 ** 2).sum(1) - 2 * (X32 @ c.T)[:, 0] + (c ** 2).sum(1) # la expansión, en float32
print("distancia² exacta ", np.round(exacta, 4))
print("expansión en float32 ", np.round(expandida, 4))
Xc = X32 - X32.mean(0) # centrar primero
centrada = (Xc ** 2).sum(1) - 2 * (Xc @ Xc[:1].T)[:, 0] + (Xc[:1] ** 2).sum(1)
print("tras centrar, float32 ", np.round(centrada, 4))True distances are on the order of thousandths and the expansion returns , and : neither order nor sign is reliable. After centering, the same formula with the same numbers and precision reproduces true distances. Also note that clipping alone fixes nothing: it turns into 0, but 2 remains 2. Centering is the remedy.
How hard is it?
If Lloyd misses the global minimum, is there a better algorithm that finds it? Generally there is no efficient one, and this is a limitation of the problem, not Lloyd.
That is, unless P = NP there is no algorithm polynomial simultaneously in , and that always solves the exact problem (NP-hardness). Important qualifications:
- With fixed and the problem is polynomial: Inaba, Katoh and Imai (1994) solve it in by enumerating partitions induced by Voronoi cells. This is a clean theoretical result and practically useless. In there is even dynamic programming on sorted data.
- Approximation algorithms with worst-case guarantees exist. Kanungo and coauthors (2004) obtain a factor with local swap search (local search with guarantees); conversely, approximating better than a certain constant greater than 1 is also NP-hard (Awasthi and coauthors, 2015). Lloyd alone has no guarantee.
- Lloyd’s iteration count can also be bad: Arthur and Vassilvitskii (2006) constructed examples requiring a superpolynomial number of steps, and Vattani (2011) showed exponential cases already in the plane. Yet in practice it converges in tens of steps. The formal explanation is smoothed analysis: Arthur, Manthey and Röglin (2009) proved that if data are perturbed with Gaussian noise of variance , expected iterations are polynomial in and . Pathological cases are fragile.
What does an NP-hard problem look like in miniature? With points and you can enumerate the assignments, know the optimum and see what Lloyd does from each possible seed:
import itertools
def todas_las_particiones(X, k):
"""Inercia de las k^n asignaciones posibles (solo para n diminuto)."""
n = len(X)
digitos = (np.arange(k ** n)[:, None] // k ** np.arange(n)) % k
sq = (X ** 2).sum(1)
J = np.zeros(len(digitos))
for c in range(k):
m = (digitos == c).astype(float)
cnt = m.sum(1)
S = m @ X
J += m @ sq - np.where(cnt > 0, (S ** 2).sum(1) / np.maximum(cnt, 1), 0.0)
return J
r = np.random.default_rng(0)
X = np.vstack([r.normal(c, 0.9, size=(3, 2)) for c in ([0, 0], [5, 1], [2.5, 4.5])] + [r.normal([2.5, 1.5], 0.9, size=(1, 2))])
Jopt = todas_las_particiones(X, 3).min()
puntos_fijos = {}
for ini in itertools.combinations(range(len(X)), 3): # Lloyd desde cada terna de puntos de datos
_, lab, J, _ = lloyd(X, X[list(ini)])
primero = {}
clave = tuple(primero.setdefault(l, len(primero)) for l in lab) # partición salvo permutación
puntos_fijos.setdefault(clave, [J, 0])[1] += 1
total = sum(v[1] for v in puntos_fijos.values())
llegan = sum(v[1] for v in puntos_fijos.values() if v[0] <= Jopt * (1 + 1e-9))
print(f"n = {len(X)}, k = 3: {3 ** len(X)} asignaciones; inercia óptima {Jopt:.3f}")
print(f"Lloyd desde las {total} ternas de puntos: {len(puntos_fijos)} puntos fijos distintos")
print(f" llegan al óptimo: {llegan / total:.0%} de las siembras")
print(" J / J_óptima de los puntos fijos:", sorted(round(float(v[0] / Jopt), 2) for v in puntos_fijos.values()))With only ten points, Lloyd has ten different fixed points: starting from each of 120 triples of data points, only 59% of seeds reach the optimum, and the worst fixed points cost up to 4.5 times optimal inertia. A problem of this size is solved by enumeration; with there would be assignments.
k-means++: seeding with a criterion
If Lloyd depends so heavily on its start, how that start is chosen matters. Choosing data points at random (“Forgy” seeding) is simplest and has an explicit, quantifiable failure visible on four points.
import itertools
L = 10.0
R = np.array([[L, 1.0], [L, -1.0], [-L, 1.0], [-L, -1.0]]) # las cuatro esquinas de un rectángulo ancho
J_de = {}
for a, b in itertools.permutations(range(4), 2): # (primer centro, segundo centro)
J_de[(a, b)] = lloyd(R, R[[a, b]])[2]
Jopt, Jmal = min(J_de.values()), max(J_de.values())
print(f"J óptima = {Jopt}, J del mal punto fijo = {Jmal}, cociente = {Jmal / Jopt} (L² = {L ** 2})")
p_unif = np.mean([J == Jopt for J in J_de.values()]) # el segundo, uniforme entre los otros tres
p_pp = 0.0
for a in range(4):
d2 = ((R - R[a]) ** 2).sum(1)
p_pp += 0.25 * sum(d2[b] / d2.sum() for b in range(4) if b != a and J_de[(a, b)] == Jopt)
print(f"P(óptimo): siembra uniforme {p_unif:.4f}, k-means++ {p_pp:.5f}, fórmula 1 - 1/(2(L²+1)) = {1 - 1 / (2 * (L ** 2 + 1)):.5f}")The remedy is therefore to make the second center favor what the first represents poorly.
sampling is a middle ground: uniform selection ignores geometry, and always choosing the farthest datum (farthest-first) catches outliers. Squaring balances this: distant points are more likely, but dense regions have substantial mass in aggregate.
Proof sketch. Let be groups of an optimal partition and their means. The argument examines what happens to each optimal group when it receives its first center.
Step 1: a uniform center in a group costs twice the optimum. If is selected uniformly in , then , with exact equality. Indeed, by identity (1) with , because . This is the pairwise identity at work: the randomly chosen center is as bad as a typical datum, at from the mean.
Step 2: a -sampled center costs at most eight times the optimum. If previous centers are and is chosen with probability , then . The expected value is with . The triangle inequality and , averaged over with , give . Substituting into produces two sums. In the sum, bound the by , and in the distance sum by ; in both a sum of is and cancels the denominator of . Each is by identity (2), totaling 8.
Step 3: induction over uncovered groups. Each new center falls in an uncovered optimal group (then, by step 2, that group has expected cost from then on) or an already covered group (a “wasted” center). A center falls in an already covered group with probability proportional to the covered groups’ remaining cost, which is what is being bounded; induction over the number of uncovered groups gives harmonic factor , and . This gives .
Three qualifications. The guarantee is in expectation: it says nothing about one run (the figure below shows one k-means++ seed can give a bad result). It is of order in the worst case and no better: the same authors exhibit families of data where k-means++ loses a factor of order . And it concerns pure seeding: scikit-learn’s implementation tries candidates by sampling at each step and keeps the one lowering inertia most. It works better in practice and does not have the same proof.
Seeding in code
Seeding maintains a vector d2 with each datum’s squared distance to the nearest center and updates it with np.minimum when adding a center: it costs per center, total, the same as one Lloyd iteration, so good seeding hardly adds cost. The kmeans function wraps several restarts and keeps the lowest inertia. First, the same validation as before, now with k-means++ seeding; then the complete result of 10 restarts versus scikit-learn.
def kmeanspp_init(X, k, rng):
"""Siembra D²: el primer centro, uniforme; cada uno de los siguientes, con probabilidad proporcional a D(x)²."""
n = len(X)
C = np.empty((k, X.shape[1]))
C[0] = X[rng.integers(n)]
d2 = sqdist(X, C[:1])[:, 0]
for j in range(1, k):
total = d2.sum()
i = rng.choice(n, p=d2 / total) if total > 0 else rng.integers(n)
C[j] = X[i]
d2 = np.minimum(d2, sqdist(X, C[j:j + 1])[:, 0])
return C
def kmeans(X, k, n_init=10, seed=0):
"""k-means con k-means++ y n_init reinicios: se queda con la solución de menor inercia."""
rng = np.random.default_rng(seed)
best = None
for _ in range(n_init):
res = lloyd(X, kmeanspp_init(X, k, rng))
if best is None or res[2] < best[2]:
best = res
return best
# validación: con la misma siembra, Lloyd propio y el de scikit-learn coinciden; y con 10 reinicios llegan al mismo mínimo
X, _ = make_blobs(n_samples=600, centers=5, cluster_std=1.2, random_state=3)
C0 = kmeanspp_init(X, 5, np.random.default_rng(0))
_, lab, J, it = lloyd(X, C0)
sk = KMeans(n_clusters=5, init=C0, n_init=1, algorithm="lloyd", tol=0.0, max_iter=300).fit(X)
print(f"misma siembra k-means++: propia {J:.6f} ({it} it.), sklearn {sk.inertia_:.6f} ({sk.n_iter_} it.), particiones distintas: {len(set(zip(lab, sk.labels_))) - 5}")
mine = kmeans(X, 5, n_init=10, seed=1)
ref = KMeans(n_clusters=5, init="k-means++", n_init=10, random_state=1).fit(X)
print(f"mejor de 10 siembras: propia {mine[2]:.3f}, sklearn {ref.inertia_:.3f}")The initialization lottery
The interactive runs Lloyd 200 times from random seeds and another 200 from k-means++ on nine Gaussians in a grid with . Each true group needs exactly one centroid, and it is easy for one to get none.
The pattern is robust: uniform seeding often lands in a bad local optimum; k-means++ avoids this much more often, but not always, and its worst case remains bad. With heavily overlapping groups initialization stops mattering because all fixed points are worth nearly the same. In the interactive, with , 24.5% of random seeds and 55.5% of k-means++ seeds succeed, and the worst runs are 5.64 and 4.03 times the best; with (groups separated by less than three standard deviations), success is 34.5% and 35.5%, and each method’s worst is within 17% of the best: when groups touch, bad partitions cost barely more than good ones. The same experiment in code, using the implementation above:
g = np.random.default_rng(3)
cent = np.array([(a, b) for b in (-4, 0, 4) for a in (-4, 0, 4)], float) # rejilla 3x3 de gaussianas
X = np.repeat(cent, 40, axis=0) + 0.5 * g.standard_normal((360, 2))
def final_inertia(metodo, semilla):
r = np.random.default_rng(semilla)
C0 = kmeanspp_init(X, 9, r) if metodo == "pp" else X[r.choice(len(X), 9, replace=False)]
return lloyd(X, C0)[2]
R = 400
J = {m: np.array([final_inertia(m, 1000 * (m == "pp") + s) for s in range(R)]) for m in ("azar", "pp")}
Jmin = min(J["azar"].min(), J["pp"].min())
print(f"inercia mínima observada: {Jmin:.1f}")
for m, nombre in (("azar", "k puntos al azar"), ("pp", "k-means++")):
p = np.mean(J[m] <= 1.03 * Jmin)
print(f"{nombre:17s} óptimo bueno (J <= 1.03 Jmin): {p:.3f} | mediana J/Jmin {np.median(J[m]) / Jmin:.2f} | peor {J[m].max() / Jmin:.2f}")
for mm in (2, 5, 10):
mejor = J[m][: R // mm * mm].reshape(-1, mm).min(1) # mejor de mm ejecuciones independientes
print(f" n_init={mm:2d}: éxito observado {np.mean(mejor <= 1.03 * Jmin):.3f} 1 - (1 - p)^m = {1 - (1 - p) ** mm:.3f}")With and 400 runs per method, random seeding succeeds (inertia within 3% of the minimum) with frequency and k-means++ with ; median inertia is times the minimum for random and for k-means++, and, as the guarantee being in expectation reminds us, k-means++ also has bad draws: its worst () nearly matches random’s (). If one run succeeds with probability , then for independent runs retaining the best, the probability at least one succeeds is (the column compared with observation). This is the argument behind n_init: each restart is a lottery ticket, final inertia objectively measures the winner, and the best of several falls quickly when is not small. With , ten restarts leave failure probability . With small , as for uniform seeding here, many more are needed.
Scale: mini-batches, triangle inequality and parallelism
Each Lloyd iteration scans all data: . With and each iteration entails distances in dimension . There are three families of remedies.
1. Avoid distances without changing the result (Elkan, Hamerly). If is assigned to and another centroid satisfies , then cannot be closer: by the triangle inequality, . Elkan (2003) maintains lower and upper bounds on each datum’s distances to centroids, updating them by centroid movement to skip most distances. The result is exactly Lloyd’s: same assignments each iteration, fewer operations, at the cost of memory. Hamerly (2010) stores only two bounds per datum (an upper bound to its centroid and a lower bound to the second closest), using memory, which works better in low dimensions. The benefit depends on the data: it is greatest with well-separated groups. This is what algorithm='elkan' implements in scikit-learn, and the lesson’s last cell verifies it gives exactly Lloyd’s result.
2. Look at only a mini-batch per step. Sculley (2010) treats this as stochastic gradient descent: each step takes a mini-batch, assigns its data to current centroids and moves each centroid toward its data at a rate decaying with the number already absorbed.
The update is a gradient-descent step with per-centroid rate on , whose gradient is . With each centroid is the exact running mean of data absorbed (the first datum replaces it entirely; the second places it halfway, etc.). Rate satisfies the classical Robbins–Monro conditions (, ), so it converges in the usual stochastic-gradient sense: to a stationary point, with noise fading. Since each step touches data rather than , work per step does not depend on .
3. Parallelize. Assignment maps over data and update reduces sums and counts per group: each machine sends pairs (sum, count) of size , not its data. k-means++ seeding is sequential (each center depends on the previous one), and k-means (Bahmani and coauthors, 2012) replaces it with a logarithmic number of rounds sampling many centers at once and then reducing them to .
import time
from sklearn.cluster import MiniBatchKMeans
def minibatch_kmeans(X, C0, batch=1024, steps=100, seed=0):
"""Sculley (2010): en cada paso, un minilote; cada centro absorbe sus puntos con tasa 1/v (media móvil)."""
rng = np.random.default_rng(seed)
C = C0.astype(float).copy()
k = len(C)
v = np.zeros(k) # cuántos puntos ha absorbido cada centro hasta ahora
for _ in range(steps):
B = X[rng.integers(len(X), size=batch)]
lab = sqdist(B, C).argmin(1)
cnt = np.bincount(lab, minlength=k)
S = np.stack([np.bincount(lab, weights=B[:, j], minlength=k) for j in range(X.shape[1])], axis=1)
m = cnt > 0
v[m] += cnt[m]
C[m] += (S[m] - cnt[m, None] * C[m]) / v[m, None] # equivale a aplicar c <- c + (x - c)/v a cada punto
return C
k, batch, steps = 16, 1024, 100
print(f"{'n':>6} {'iter. Lloyd':>11} {'trabajo Lloyd':>14} {'trabajo minilotes':>18} {'cociente':>8} {'J_mini / J_Lloyd':>16}")
for n in (2000, 10000, 50000):
X, _ = make_blobs(n_samples=n, n_features=10, centers=k, cluster_std=1.5, random_state=0)
C0 = X[np.random.default_rng(1).choice(n, k, replace=False)]
_, _, J, it = lloyd(X, C0)
Jm = sqdist(X, minibatch_kmeans(X, C0, batch, steps)).min(1).sum()
wl, wm = it * n * k, steps * batch * k # evaluaciones de distancia al cuadrado
print(f"{n:6d} {it:11d} {wl:14.2e} {wm:18.2e} {wl / wm:8.2f} {Jm / J:16.3f}")
X, _ = make_blobs(n_samples=50000, n_features=10, centers=k, cluster_std=1.5, random_state=0)
for nombre, est in (("KMeans", KMeans(k, init="random", n_init=1, random_state=0)), ("MiniBatchKMeans", MiniBatchKMeans(k, init="random", n_init=1, batch_size=batch, random_state=0))):
t0 = time.perf_counter(); est.fit(X); t = time.perf_counter() - t0
print(f"sklearn {nombre:16s} n = 50000: {t:6.3f} s, inercia {est.inertia_:.0f}")The table counts squared-distance evaluations (iterations for Lloyd, steps for mini-batches), independent of machine. Mini-batch work is the same in all three rows because it does not depend on ; Lloyd work grows with and required iterations (11, 63 and 42 here). With mini-batches cost nearly five times more than full Lloyd (ratio ): 100 steps of 1024 points scan more data than 11 iterations over 2000. With and they cost 6 and 20 times less, at the price of inertia between % and % higher than full Lloyd. The last two lines are scikit-learn and call for caution: MiniBatchKMeans inertia is % higher here than KMeans, but each starts from its own random seed, so the difference combines mini-batch noise with the initialization lottery; wall-clock times depend on implementation, available threads and machine (in your browser with one thread they need not rank the same as on a multicore laptop). Mini-batches pay off when data do not fit in memory or arrive as a stream, or when is so large a full pass is already expensive; not because they are faster “in general.”
Vector quantization
Everything above reads the same from compression. A quantizer sends each vector with a label of bits and the receiver replaces it with its representative.
Two necessary conditions for to be optimal with fixed (Lloyd, 1957; Max, 1960; Linde, Buzo and Gray, 1980) are exactly the two Lloyd steps: the optimal encoder for a codebook assigns to the nearest neighbor (encoding regions are Voronoi cells), and a cell’s optimal representative is its centroid . Applied to a sample, this is literally k-means: inertia divided by is empirical distortion, and Lloyd is the LBG codebook-design algorithm. The difference is perspective: in compression is not a hypothesis about how many groups exist but a bit budget, and the entire curve matters.
How does fall with ? For large and a regular density in dimension (with the data support dimension), Zador’s theorem (1982) says the optimal -level quantizer satisfies
where is a constant depending only on (under the usual condition that has a finite moment of order ). The exponent matters: every doubling of (one more bit per vector) multiplies distortion by , meaning an improvement of dB per bit. For this is the familiar 6 dB per bit for a scalar quantizer; for RGB color in the full cube (), 2.0 dB per bit; and for almost nothing: high-dimensional quantization with few bits per vector is inefficient, hence decomposition into small blocks (product quantization in vector search, residual in residual vector quantization). If data live near a manifold of dimension , the exponent is that of , not : the same intrinsic dimension idea from lesson 1, now with a direct effect on bits.
Shannon’s theory gives a floor: no rate- quantizer can beat the source’s distortion–rate function (rate–distortion function). For a Gaussian source of variance per component, per component (the same 6.02 dB per bit, without constant ), and optimal vector quantization of increasing dimension approaches that curve. The operating curve of real -means on a real image lies above it: this is what the interactive measures.
def escena(rng, w=120, h=80):
"""Cielo con degradado, sol con halo, montañas, colinas y flores (60 de 3x3 píxeles: como mucho el 5.6 % de los píxeles) con ruido uniforme de ±5."""
y, x = np.mgrid[0:h, 0:w].astype(float)
t = np.clip(y / (0.58 * h), 0, 1)[..., None]
azul, claro, ocaso = np.array([60, 120, 205.]), np.array([140, 185, 235.]), np.array([255, 205, 150.])
img = np.where(t < 0.55, azul + (claro - azul) * (t / 0.55), claro + (ocaso - claro) * ((t - 0.55) / 0.45))
sol = np.hypot(x - 0.72 * w, y - 0.4 * h)
halo = (0.55 * np.exp(-(((sol - 9) / 14) ** 2)))[..., None]
img = np.where((sol < 9)[..., None], [255, 244, 190.], img + (np.array([255, 215, 140.]) - img) * halo)
ym = 0.5 * h + 5 * np.sin(x * 0.09) + 3 * np.sin(x * 0.23 + 1)
u = np.clip((y - ym) / (0.3 * h), 0, 1)[..., None]
img = np.where((y > ym)[..., None], np.array([120, 108, 155.]) + (np.array([88, 84, 128.]) - [120, 108, 155.]) * u, img)
yh = 0.66 * h + 4 * np.sin(x * 0.06 + 2) + 2 * np.sin(x * 0.17)
u = np.clip((y - yh) / (h - yh), 0, 1)[..., None]
img = np.where((y > yh)[..., None], np.array([100, 170, 72.]) + (np.array([28, 92, 50.]) - [100, 170, 72.]) * u, img)
flores = np.array([[215, 45, 55], [245, 215, 60], [240, 240, 240]], float)
for i in range(60):
fx, fy = int(rng.integers(2, w - 2)), int(rng.integers(int(0.74 * h), int(0.98 * h)))
img[fy - 1:fy + 2, fx - 1:fx + 2] = flores[i % 3]
return np.clip(np.round(img + rng.uniform(-5, 5, img.shape)), 0, 255)
P = escena(np.random.default_rng(0)).reshape(-1, 3) # 9600 píxeles, d = 3
def psnr(Q): return 10 * np.log10(255 ** 2 / np.mean((P - Q) ** 2))
print(f"techo por el ruido: PSNR = {10 * np.log10(255 ** 2 / (10 ** 2 / 12)):.2f} dB (MSE = 25/3)")
print(f"{'k':>3} {'bits':>5} {'PSNR':>7} {'dB por bit':>10}")
previo = None
for k in (2, 4, 8, 16, 32, 64):
km = KMeans(k, n_init=1, random_state=0).fit(P[::3]) # se ajusta con un píxel de cada tres
s = psnr(np.round(km.cluster_centers_)[km.predict(P)])
print(f"{k:3d} {np.log2(k):5.1f} {s:7.2f} {'' if previo is None else f'{(s - previo[0]) / (np.log2(k) - previo[1]):10.2f}'}")
previo = (s, np.log2(k))
for L in (2, 3, 4): # rejilla uniforme con L niveles por canal
niveles = (np.arange(L) + 0.5) * 256 / L
Q = niveles[np.argmin(np.abs(P[:, :, None] - niveles), axis=2)]
print(f"rejilla uniforme, {L ** 3:2d} colores: PSNR {psnr(Q):.2f} dB")The output (another scene from the same recipe with different noise than the interactive; figures change somewhat, not the three interpretations) has three readings, none predicted by the naive formula. First, bits do not have equal value. Going from 2 to 4 colors gains 4.0 dB; the next three bits, from 4 to 32 colors, gain between 5.0 and 5.8 dB each: over 5 dB per bit, well above 2 dB for . At this scale the scene’s colors resemble a curve (, giving 6 dB per bit) more than a volume, by construction: sky, mountains and hills are gradients, polygonal curves in the RGB cube; only the sun halo, mixing sky with a fixed color, occupies a small surface, and the rest are a few isolated colors (sun disk and flowers). Second, there is a floor, known because we put it there: uniform noise of has variance , so a codebook that does not memorize noise cannot fall below MSE , or 38.9 dB. At 64 colors it is within 0.4 dB of the ceiling, and the last bit gives only 2.2 dB, less than half the previous one: that is diminishing returns. In a real photo grain sets the floor. Third, the uniform grid is very poor: with 64 levels equally distributed in the cube, the scene is 16 dB below k-means with the same 64 colors, because the grid spends most levels on colors the image never uses. A data-adapted codebook makes vector quantization effective.
The same mechanism appears in model compression: compressing network weights by clustering their values into a per-layer codebook is one-dimensional vector quantization (nonuniform codebook quantization), and a VQ-VAE codebook is k-means trained by gradient, with the problem that some centroids receive no data (VQ-VAE and codebook collapse), Lloyd’s empty group under another name.
Beyond the mean: k-medoids and kernel k-means
The entire structure rests on the mean being the best representative, and that is a theorem of squared Euclidean distance, not distance in general.
The most general way out is to require representatives to be data points.
The reference algorithm is PAM (Partitioning Around Medoids; Kaufman and Rousseeuw, 1987). The BUILD phase greedily chooses medoids one at a time: the first minimizes total dissimilarity to all points, each next is the datum whose inclusion reduces cost most. The SWAP phase tries all (medoid, non-medoid) swaps and applies the best while cost falls: each step evaluates swaps and an iteration costs , quadratic in . CLARA runs PAM on samples to scale. Three reasons to pay for it: (i) it works for non-vector data (strings with edit distance, sets with Jaccard, graphs) or mixed-data dissimilarities such as in lesson 1; (ii) the medoid is a real, interpretable datum (“the segment’s typical customer”); (iii) with or a nonquadratic dissimilarity it is robust to outliers: a very distant datum weighs its distance, not its square.
from sklearn.metrics import adjusted_rand_score
def manhattan(X):
return np.abs(X[:, None, :] - X[None, :, :]).sum(2)
def pam(D, k, max_iter=50):
"""PAM simplificado sobre una matriz de disimilitudes D (n, n): BUILD voraz y SWAP completo."""
n = len(D)
med = [int(D.sum(1).argmin())] # BUILD: el primer medoide minimiza la suma de distancias
while len(med) < k:
cerca = D[:, med].min(1)
ahorro = np.maximum(cerca[:, None] - D, 0).sum(0) # lo que ahorraría añadir cada candidato
ahorro[med] = -1
med.append(int(ahorro.argmax()))
coste = D[:, med].min(1).sum()
for _ in range(max_iter):
mejor = (coste, None)
for i in range(k): # SWAP: cambiar el medoide i por el mejor candidato
resto = [m for j, m in enumerate(med) if j != i]
base = D[:, resto].min(1)
costes = np.minimum(base[:, None], D).sum(0)
costes[med] = np.inf
h = int(costes.argmin())
if costes[h] < mejor[0] - 1e-12:
mejor = (costes[h], (i, h))
if mejor[1] is None:
break
med[mejor[1][0]] = mejor[1][1]
coste = mejor[0]
return np.array(med), D[:, med].argmin(1), coste
print(f"{'dispersión de los atípicos':>26} {'ARI k-means':>12} {'ARI PAM (L1)':>13}")
for s in (15, 30, 100):
ak, ap = [], []
for semilla in range(6):
r = np.random.default_rng(semilla)
A, B = r.normal([0, 0], 1.0, size=(80, 2)), r.normal([8, 0], 1.0, size=(80, 2))
X = np.vstack([A, B, r.normal(0, s, size=(8, 2))]) # 8 atípicos de desviación s
y = np.r_[np.zeros(80), np.ones(80)]
ak.append(adjusted_rand_score(y, kmeans(X, 2, n_init=10, seed=semilla)[1][:160]))
ap.append(adjusted_rand_score(y, pam(manhattan(X), 2)[1][:160]))
print(f"{s:26d} {np.mean(ak):12.2f} {np.mean(ap):13.2f}")Two Gaussian groups separated by 8 and eight outliers with standard deviation . With both methods succeed. With mean k-means ARI falls to : inertia prefers isolating a few distant outliers to separating the groups. PAM with holds up because an outlier’s cost grows with distance, not its square, and gives way only when outliers are so far away that even linear distance cannot ignore them: with k-means is at and PAM still at .
Kernel k-means. Another escape from Euclidean geometry is to apply k-means in a feature space without constructing it, using a kernel (kernel trick). The mean in feature space is , and distance from a datum to it is expressed entirely with the kernel: Lloyd works the same way (it is Euclidean k-means in , so the termination proof still holds), at cost per iteration with the Gram matrix in memory. This opens the door to spectral clustering in lesson 6: Dhillon, Guan and Kulis (2004) proved that the weighted kernel k-means objective equals a normalized graph cut with appropriate weights and kernel. It works for nonconvex groups with the right kernel, but not by magic: the kernel and its scale must be chosen well.
Implicit assumptions and failure modes
k-means is not assumption-free; its assumptions are merely hidden. Voronoi cells are convex and equidistant from their centroids; Euclidean distance treats all directions equally; and the objective sums all data distances without weighting by group. This implies four assumptions:
- Convex groups (the cells are convex).
- Isotropy: within-group dispersion is equal in every direction.
- Similar dispersion between groups: the boundary is equidistant from two centroids.
- Similar sizes: the objective does not weight small groups.
There is an exact way to state this. k-means is the limit of EM for a Gaussian mixture with equal covariances : responsibilities become hard assignments and mean updates are Lloyd’s (Gaussian mixture, lesson 8; Bishop, 2006, section 9.3.2). The first three assumptions are the model’s assumptions (spherical groups of equal radius, separated); the fourth follows because the objective sums distances without weighting by group.
No assumption is checked by looking at k-means output: the algorithm always returns groups. You must predict.
Two lessons emerge from the controls. First, preprocessing changes the problem, not the solution: standardization and whitening are linear transformations and can fix only linear failures (variables on different scales; a common linear shape). Whitening with total covariance is not the same as normalizing within-group covariance, which matters but is not known in advance: here it works because the three groups share shape. The other side appears in ‘Unequal sizes’: groups align along , so total variance of () is more than three times that of () precisely because groups are separated in that direction. Standardizing divides by and by , bringing groups closer without shrinking their dispersion in , and ARI falls from to . Scaling by total variance shrinks exactly the directions separating groups; it is therefore justified only when variables have different units. Second, a convexity failure has no linear fix: rings need a new feature (here , one coordinate of the mapping implied by a polynomial kernel), and moons need another method (density in lesson 5, spectral in lesson 6).
Choosing : the elbow, cautiously. For fixed the minimum is nonincreasing in (adding a center never worsens it), and . Therefore inertia cannot compare values of : it always prefers the largest. The most popular provisional criterion is the “elbow”: plot and look where it stops falling quickly. It is heuristic and sometimes ambiguous; more serious criteria (stability, gap statistic, silhouette) are the subject of lesson 7.
Xb, _ = make_blobs(n_samples=400, centers=[[-6, -3], [6, -3], [0, 6], [0, -12]], cluster_std=1.0, random_state=0)
Xu = np.random.default_rng(0).uniform(-8, 8, size=(400, 2))
Jb = [kmeans(Xb, k, n_init=5, seed=0)[2] for k in range(1, 9)]
Ju = [kmeans(Xu, k, n_init=5, seed=0)[2] for k in range(1, 9)]
print(f"{'k':>2} {'J (4 grupos)':>13} {'J (uniforme)':>13} {'J_k/J_(k-1) 4 grupos':>21} {'uniforme':>9}")
for k in range(1, 9):
r1 = '' if k == 1 else f"{Jb[k - 1] / Jb[k - 2]:.2f}"
r2 = '' if k == 1 else f"{Ju[k - 1] / Ju[k - 2]:.2f}"
print(f"{k:2d} {Jb[k - 1]:13.1f} {Ju[k - 1]:13.1f} {r1:>21} {r2:>9}")With four groups, falls to exactly at and returns to : a clear elbow. With uniform data, which have no groups, the ratio rises from to at : there is also a certain “elbow” there that means nothing. The elbow offers a clue when the signal is strong and does not resolve weak signals.
The professional version
In practice use sklearn.cluster.KMeans. Important parameters: init ('k-means++' by default), n_init (in recent versions, 'auto': 1 seed with k-means++, 10 with 'random'), algorithm ('lloyd' or 'elkan') and tol. Attributes: cluster_centers_, labels_, inertia_, n_iter_. For mini-batches use MiniBatchKMeans with batch_size. k-medoids is not in scikit-learn: use sklearn_extra.cluster.KMedoids or your own implementation (such as PAM above).
X, _ = make_blobs(n_samples=3000, n_features=8, centers=12, cluster_std=2.0, random_state=0)
C0 = kmeanspp_init(X, 12, np.random.default_rng(0))
res = {}
for alg in ("lloyd", "elkan"): # Elkan: mismas iteraciones, menos distancias evaluadas
res[alg] = KMeans(12, init=C0, n_init=1, algorithm=alg, tol=0.0, max_iter=500).fit(X)
print(f"{alg:6s} inercia {res[alg].inertia_:.6f}, {res[alg].n_iter_} iteraciones")
print("mismas etiquetas:", np.array_equal(res["lloyd"].labels_, res["elkan"].labels_))
km = KMeans(12, n_init=10, random_state=0).fit(X)
print("transform(X[:2]).shape =", km.transform(X[:2]).shape, "| score(X) = -inertia_:", bool(np.isclose(km.score(X), -km.inertia_)))
print("tamaños de los 12 grupos:", np.sort(np.bincount(km.labels_)).tolist())Elkan produces the same labels and inertia as Lloyd, as it should: it is the same algorithm with fewer distances.
Common mistakes
Exercises
Step 1 of 4. How do you prepare the square to compare with the mean?
Step 1 of 4. Why is ?
kmeans_pp_init(X, k, rng), taking data X of shape (n, d), number of centers k and a NumPy generator rng (np.random.default_rng), and returning a (k, d) matrix of centers chosen by sampling: the first is a uniformly selected row of X (use rng.integers), and each subsequent center is row i with probability proportional to squared distance to the nearest center already selected. If all points coincide with centers (sum 0), choose a row uniformly. The first center must be C[0].import numpy as np
def kmeans_pp_init(X, k, rng):
"""Siembra k-means++ con muestreo D^2."""
X = np.asarray(X, dtype=float)
# tu código: primer centro uniforme; después, k - 1 veces, elegir con prob. D^2 y actualizar D^2
return X[:k].copy()More than one answer may be correct.
Summary
- Inertia is within-cluster sum of squares; the mean minimizes each group, and is mean squared pairwise distance within groups. Minimizing is equivalent to maximizing between-group dispersion.
- Lloyd alternates assignment (convex Voronoi cells) and update (means). Cost per iteration . It does not increase , strictly decreases it when assignment changes and terminates at a fixed point, a local minimum of , not necessarily global or Hartigan–Wong optimal.
- The problem is NP-hard (even with in high dimension, or in the plane), Lloyd can finish an arbitrary factor from optimum, and in the worst case needs exponentially many iterations; in practice, not.
- k-means++ ( sampling) guarantees ; in practice, restarts raise success probability to .
- At scale: Elkan accelerates without changing the result using the triangle inequality; mini-batches give a running mean per centroid at per-step cost independent of , for some extra inertia; updates parallelize with sums and counts.
- Vector quantization: Lloyd’s steps are a quantizer’s two optimality conditions; distortion falls as , dB per bit, with data dimension; a data-adapted codebook greatly outperforms a uniform grid.
- The mean is optimal only for squared Euclidean distance. With other dissimilarities or outliers, use k-medoids (PAM) or k-medians; with nonconvex groups, kernel k-means or density or spectral methods; inertia cannot compare , and the elbow is only a clue.