Module contents
Lesson 2 of 24Core 100 min

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 kk 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 x1,…,xn∈Rd\vb{x}_1, \dots, \vb{x}_n \in \R^d be the data and k≤nk \le n the number of representatives. An assignment is a function z:{1,…,n}→{1,…,k}z : \{1, \dots, n\} \to \{1, \dots, k\}, meaning a partition C1,…,CkC_1, \dots, C_k with Cj={i:z(i)=j}C_j = \{i : z(i) = j\}.

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 J(μ)J(\vb{\mu}) is not convex (the min⁡\min over jj 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 xi−c=(xi−xˉ)+(xˉ−c)\vb{x}_i - \vb{c} = (\vb{x}_i - \bar{\vb{x}}) + (\bar{\vb{x}} - \vb{c}) and expand the square. The cross term is 2(∑i(xi−xˉ))⊤(xˉ−c)=02\big(\sum_i (\vb{x}_i - \bar{\vb{x}})\big)\T (\bar{\vb{x}} - \vb{c}) = 0, because deviations from the mean sum to zero. This leaves (1). Since m∥xˉ−c∥2≥0m\norm{\bar{\vb{x}} - \vb{c}}^2 \ge 0 and vanishes only at c=xˉ\vb{c} = \bar{\vb{x}}, the mean is the unique minimizer.

For (2), apply (1) with c=xj\vb{c} = \vb{x}_j and sum over jj: ∑j∑i∥xi−xj∥2=∑j(S+m∥xˉ−xj∥2)=mS+mS=2mS.■\sum_j \sum_i \norm{\vb{x}_i - \vb{x}_j}^2 = \sum_j \big(S + m\norm{\bar{\vb{x}} - \vb{x}_j}^2\big) = mS + mS = 2mS. \qquad \blacksquare

∎

Three consequences are used constantly.

  1. For a fixed partition, optimal representatives are means μj=xˉCj\vb{\mu}_j = \bar{\vb{x}}_{C_j}. That is why the algorithm is called k-means.
  2. Inertia is pairwise compactness: by (2), J=∑j12∣Cj∣∑i,l∈Cj∥xi−xl∥2J = \sum_j \frac{1}{2\abs{C_j}} \sum_{i, l \in C_j} \norm{\vb{x}_i - \vb{x}_l}^2. Minimizing JJ asks that, within each group, mean squared pairwise distance be small. This interpretation mentions no centroid.
  3. Within plus between is constant. Applying (1) to each group with c=xˉ\vb{c} = \bar{\vb{x}} (the global mean), total dispersion T=∑i∥xi−xˉ∥2T = \sum_i \norm{\vb{x}_i - \bar{\vb{x}}}^2 decomposes into T=W+BT = W + B, with W=JW = J within-group dispersion and B=∑j∣Cj∣∥μj−xˉ∥2B = \sum_j \abs{C_j}\norm{\vb{\mu}_j - \bar{\vb{x}}}^2 between-group dispersion. Since TT does not depend on the partition, minimizing WW is equivalent to maximizing BB: separating centroids and tightening groups are the same thing. Validity indices in lesson 7 (for example Calinski–Harabasz) are ratios of these quantities.
[ ]Both identities, with numbersBrowser
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 J(z,μ)J(z, \vb{\mu}) depends on two variable blocks, assignment zz and representatives μ\vb{\mu}, and each block is minimized exactly when the other is fixed. This is block coordinate descent (alternating minimization).

  • Block zz with μ\vb{\mu} fixed. The sum separates by data point: each xi\vb{x}_i chooses the jj minimizing ∥xi−μj∥2\norm{\vb{x}_i - \vb{\mu}_j}^2. The set of points in space preferring μj\vb{\mu}_j is the Voronoi cell Vj={x:∥x−μj∥≤∥x−μl∥ ∀l}V_j = \{\vb{x} : \norm{\vb{x} - \vb{\mu}_j} \le \norm{\vb{x} - \vb{\mu}_l}\ \forall l\} (Voronoi diagrams). Since ∥x−μl∥2−∥x−μj∥2=2(μj−μl)⊤x+∥μl∥2−∥μj∥2\norm{\vb{x} - \vb{\mu}_l}^2 - \norm{\vb{x} - \vb{\mu}_j}^2 = 2(\vb{\mu}_j - \vb{\mu}_l)\T\vb{x} + \norm{\vb{\mu}_l}^2 - \norm{\vb{\mu}_j}^2, each cell is an intersection of k−1k - 1 half-spaces: a convex polyhedron bounded by bisectors.
  • Block μ\vb{\mu} with zz fixed. The sum separates by groups and each μj\vb{\mu}_j minimizes ∑i∈Cj∥xi−μj∥2\sum_{i \in C_j}\norm{\vb{x}_i - \vb{\mu}_j}^2: it is the mean, by the previous theorem.

Assignment does not require calculating the full distance: since ∥x−μj∥2=∥x∥2−2x⊤μj+∥μj∥2\norm{\vb{x} - \vb{\mu}_j}^2 = \norm{\vb{x}}^2 - 2\vb{x}\T\vb{\mu}_j + \norm{\vb{\mu}_j}^2 and the first term is the same for all jj, it suffices to minimize ∥μj∥2−2x⊤μj\norm{\vb{\mu}_j}^2 - 2\vb{x}\T\vb{\mu}_j, a matrix product XM⊤\mat{X}\mat{M}\T costing O(nkd)\bigO(nkd). Updating costs O(nd)\bigO(nd). These are per-iteration costs, linear in each quantity.

InteractiveLloyd step by step
Points, centroids and Voronoi cells
start
Inertia JJ after each half-step. Blue shows assignment and green shows update.
mejor conocida
  • after assignment
  • after update
  • best known J⋆J^\star
Initial centroids
Iteration0
Stepinitial state
Inertia JJn/a
J⋆J^\star (best of 30 k-means++ initializations)78.7
Points that change clustern/a
Only the centroids are shown. Each cell contains points closer to its centroid than any other.
Three groups of points (two close together on the left, one on the right) and three centroids. Each colored cell is the region of the plane closest to its centroid. Play the animation: each iteration first colors each point by its containing cell (assign), then each centroid jumps along the dashed line to the mean of its points (update); thick-edged points are no longer in their centroid's cell and will change on the next assignment. Below, inertia after each half-step is drawn as you advance: it never rises. Start with 'Two in one group' and see where the algorithm stops and JJ relative to the best known inertia. Compare with 'Spread out' and 'Random', try 'From a corner', and drag centroids yourself in the initial state. Add points by clicking: does the fixed point reached change?

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 μ(t)\vb{\mu}^{(t)} be the means of groups in z(t)z^{(t)} (an empty group retains its previous centroid and contributes nothing to JJ). There are two inequalities:

J(z(t+1),μ(t+1))  ≤  J(z(t+1),μ(t))  ≤  J(z(t),μ(t)).J(z^{(t+1)}, \vb{\mu}^{(t+1)}) \;\le\; J(z^{(t+1)}, \vb{\mu}^{(t)}) \;\le\; J(z^{(t)}, \vb{\mu}^{(t)}).

The second is assignment: with μ(t)\vb{\mu}^{(t)} fixed, z(t+1)z^{(t+1)} minimizes each term separately, so cannot be worse than z(t)z^{(t)}. 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 z(t+1)z^{(t+1)} fixed, means minimize each group (previous theorem).

If z(t+1)≠z(t)z^{(t+1)} \ne z^{(t)}, inertia strictly decreases, and since J(z(t),μ(t))J(z^{(t)}, \vb{\mu}^{(t)}) depends only on the partition, no partition can repeat. There are only knk^n possible assignments, so after at most knk^n changes the assignment repeats. Then μ(t+1)=μ(t)\vb{\mu}^{(t+1)} = \vb{\mu}^{(t)} (means of the same partition) and the algorithm stops. ■\blacksquare

∎

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 knk^n 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 μ\vb{\mu} and J(μ)J(\vb{\mu}) there equals a sum of strictly convex quadratics, one per group, each minimized at its mean. It is a strict local minimum of J(μ)J(\vb{\mu}) as a function of centroids. (With an empty group, JJ 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 JJ, 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

∥xi−μj∥2=∥xi∥2−2 xi⊤μj+∥μj∥2,\norm{\vb{x}_i - \vb{\mu}_j}^2 = \norm{\vb{x}_i}^2 - 2\,\vb{x}_i\T\vb{\mu}_j + \norm{\vb{\mu}_j}^2,

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).

[ ]Vectorized Lloyd, validated against scikit-learnBrowser
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.

[ ]Cancellation at a glanceBrowser
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 −2-2, 00 and 22: 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 −2-2 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 nn, kk and dd that always solves the exact problem (NP-hardness). Important qualifications:

  • With fixed kk and dd the problem is polynomial: Inaba, Katoh and Imai (1994) solve it in O(nkd+1)\bigO(n^{kd+1}) by enumerating partitions induced by Voronoi cells. This is a clean theoretical result and practically useless. In d=1d = 1 there is even dynamic programming on sorted data.
  • Approximation algorithms with worst-case guarantees exist. Kanungo and coauthors (2004) obtain a factor 9+ε9 + \eps 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 σ2\sigma^2, expected iterations are polynomial in nn and 1/σ1/\sigma. Pathological cases are fragile.

What does an NP-hard problem look like in miniature? With n=10n = 10 points and k=3k = 3 you can enumerate the 310=59 0493^{10} = 59\,049 assignments, know the optimum and see what Lloyd does from each possible seed:

[ ]Local optima landscape of a tiny problemBrowser
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 n=100n = 100 there would be 31003^{100} assignments.

k-means++: seeding with a criterion

If Lloyd depends so heavily on its start, how that start is chosen matters. Choosing kk data points at random (“Forgy” seeding) is simplest and has an explicit, quantifiable failure visible on four points.

[ ]The twelve rectangle seed pairsBrowser
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.

D2D^2 sampling is a middle ground: uniform selection ignores geometry, and always choosing the farthest datum (farthest-first) catches outliers. Squaring DD balances this: distant points are more likely, but dense regions have substantial mass in aggregate.

Proof sketch. Let A1,…,AkA_1, \dots, A_k be groups of an optimal partition and μj\mu_j 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 a\vb{a} is selected uniformly in AA, then E[φ(A;{a})]=2φOPT(A)\E[\varphi(A; \{\vb{a}\})] = 2\varphi_{\mathrm{OPT}}(A), with exact equality. Indeed, by identity (1) with c=a\vb{c} = \vb{a}, 1∣A∣∑a∈A∑x∈A∥x−a∥2=1∣A∣∑a∈A(φOPT(A)+∣A∣ ∥a−μ∥2)=2 φOPT(A),\frac{1}{\abs{A}} \sum_{\vb{a} \in A} \sum_{\vb{x} \in A} \norm{\vb{x} - \vb{a}}^2 = \frac{1}{\abs{A}} \sum_{\vb{a} \in A} \big(\varphi_{\mathrm{OPT}}(A) + \abs{A}\,\norm{\vb{a} - \vb{\mu}}^2\big) = 2\,\varphi_{\mathrm{OPT}}(A), because ∑a∥a−μ∥2=φOPT(A)\sum_{\vb{a}} \norm{\vb{a} - \vb{\mu}}^2 = \varphi_{\mathrm{OPT}}(A). This is the pairwise identity at work: the randomly chosen center is as bad as a typical datum, at φ/∣A∣\sqrt{\varphi/\abs{A}} from the mean.

Step 2: a D2D^2-sampled center costs at most eight times the optimum. If previous centers are CC and a∈A\vb{a} \in A is chosen with probability D(a)2/φ(A;C)D(\vb{a})^2 / \varphi(A; C), then E[φ(A;C∪{a})]≤8 φOPT(A)\E[\varphi(A; C \cup \{\vb{a}\})] \le 8\,\varphi_{\mathrm{OPT}}(A). The expected value is ∑ap(a)∑a′min⁡(D(a′),∥a−a′∥)2\sum_{\vb{a}} p(\vb{a}) \sum_{\vb{a}'} \min\big(D(\vb{a}'), \norm{\vb{a} - \vb{a}'}\big)^2 with p(a)=D(a)2/φ(A;C)p(\vb{a}) = D(\vb{a})^2/\varphi(A; C). The triangle inequality D(a)≤D(a′′)+∥a−a′′∥D(\vb{a}) \le D(\vb{a}'') + \norm{\vb{a} - \vb{a}''} and (u+v)2≤2u2+2v2(u + v)^2 \le 2u^2 + 2v^2, averaged over a′′∈A\vb{a}'' \in A with m=∣A∣m = \abs{A}, give D(a)2≤2m∑a′′(D(a′′)2+∥a−a′′∥2)D(\vb{a})^2 \le \frac{2}{m}\sum_{\vb{a}''}\big(D(\vb{a}'')^2 + \norm{\vb{a} - \vb{a}''}^2\big). Substituting into p(a)p(\vb{a}) produces two sums. In the D(a′′)2D(\vb{a}'')^2 sum, bound the min⁡\min by ∥a−a′∥\norm{\vb{a} - \vb{a}'}, and in the distance sum by D(a′)D(\vb{a}'); in both a sum of D2D^2 is φ(A;C)\varphi(A; C) and cancels the denominator of pp. Each is ≤2m∑a,a′∥a−a′∥2=4φOPT(A)\le \frac{2}{m}\sum_{\vb{a}, \vb{a}'}\norm{\vb{a} - \vb{a}'}^2 = 4\varphi_{\mathrm{OPT}}(A) 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 ≤8φOPT\le 8\varphi_{\mathrm{OPT}} 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 tt of uncovered groups gives harmonic factor 1+Ht1 + H_{t}, and 1+Hk−1≤2+ln⁡k1 + H_{k-1} \le 2 + \ln k. This gives 8(ln⁡k+2)8(\ln k + 2). ■\blacksquare

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 log⁡k\log k in the worst case and no better: the same authors exhibit families of data where k-means++ loses a factor of order log⁡k\log k. And it concerns pure seeding: scikit-learn’s implementation tries 2+⌊ln⁡k⌋2 + \lfloor \ln k \rfloor candidates by D2D^2 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 O(nd)\bigO(nd) per center, O(nkd)\bigO(nkd) 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.

[ ]k-means++ and restarts, validated against scikit-learnBrowser
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 3×33 \times 3 grid with k=9k = 9. Each true group needs exactly one centroid, and it is easy for one to get none.

InteractiveThe initialization lottery
Final inertia of 200 Lloyd runs per method, divided by the best among all 400
good solution: up to 1.03
  • random seeding
  • k-means++
Selected solution. Green centroids uniquely cover a cluster, red centroids share a cluster, and orange centroids fall between clusters and cover neither.
0.50
1
Show a solution from
Run to show
Random seeding success (1 → ninitn_{\text{init}})24.5 % → 24.5 %
k-means++ success (1 → ninitn_{\text{init}})55.5 % → 55.5 %
J/Jmin⁡J/J_{\min} median and worst, random2.48 and 5.64
J/Jmin⁡J/J_{\min} median and worst, k-means++1.00 and 4.03
Mean iterations, random and k-means++7.6 and 5.5
Success means final inertia within 1.03 times the minimum. The arrow goes from one run to the best of ninit=1n_{\text{init}} = 1 runs, with probability 1−(1−p)11 - (1 - p)^{1} that at least one succeeds. The selected result (random, worst) has J/Jmin⁡=5.64J/J_{\min} = 5.64 and covers 3 of 9 clusters. Red circles mark the clusters left without a centroid.
Histogram of final inertia from 200 Lloyd runs per method, divided by the best of all 400. With kk random points (red) most finish far from optimal; with k-means++ (blue), much more mass is near 1. Open each method's worst solution using the selectors: red circles mark groups without a centroid, red centroids share a group, and orange ones are trapped between two groups. Raise ninitn_{\text{init}} and see how probability 1−(1−p)ninit1 - (1 - p)^{n_{\text{init}}} grows. Then raise dispersion σ\sigma: when does the difference between the methods disappear, and why?

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 σ=0.5\sigma = 0.5, 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 σ=1.4\sigma = 1.4 (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:

[ ]Measuring the lotteryBrowser
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 σ=0.5\sigma = 0.5 and 400 runs per method, random seeding succeeds (inertia within 3% of the minimum) with frequency 0.180.18 and k-means++ with 0.590.59; median inertia is 2.772.77 times the minimum for random and 1.001.00 for k-means++, and, as the guarantee being in expectation reminds us, k-means++ also has bad draws: its worst (4.604.60) nearly matches random’s (4.804.80). If one run succeeds with probability pp, then for mm independent runs retaining the best, the probability at least one succeeds is 1−(1−p)m1 - (1 - p)^m (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 pp is not small. With p=0.5p = 0.5, ten restarts leave failure probability 0.510≈0.0010.5^{10} \approx 0.001. With small pp, as for uniform seeding here, many more are needed.

Scale: mini-batches, triangle inequality and parallelism

Each Lloyd iteration scans all data: O(nkd)\bigO(nkd). With n=108n = 10^8 and k=103k = 10^3 each iteration entails 101110^{11} distances in dimension dd. There are three families of remedies.

1. Avoid distances without changing the result (Elkan, Hamerly). If x\vb{x} is assigned to c\vb{c} and another centroid c′\vb{c}' satisfies d(c,c′)≥2 d(x,c)d(\vb{c}, \vb{c}') \ge 2\,d(\vb{x}, \vb{c}), then c′\vb{c}' cannot be closer: by the triangle inequality, d(x,c′)≥d(c,c′)−d(x,c)≥d(x,c)d(\vb{x}, \vb{c}') \ge d(\vb{c}, \vb{c}') - d(\vb{x}, \vb{c}) \ge d(\vb{x}, \vb{c}). 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 O(nk)\bigO(nk) memory. Hamerly (2010) stores only two bounds per datum (an upper bound to its centroid and a lower bound to the second closest), using O(n)\bigO(n) 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 η=1/vj\eta = 1/v_j on 12∥x−cj∥2\frac{1}{2}\norm{\vb{x} - \vb{c}_j}^2, whose gradient is cj−x\vb{c}_j - \vb{x}. With η=1/vj\eta = 1/v_j each centroid is the exact running mean of data absorbed (the first datum replaces it entirely; the second places it halfway, etc.). Rate 1/v1/v satisfies the classical Robbins–Monro conditions (∑η=∞\sum \eta = \infty, ∑η2<∞\sum \eta^2 < \infty), so it converges in the usual stochastic-gradient sense: to a stationary point, with noise fading. Since each step touches bb data rather than nn, work per step does not depend on nn.

3. Parallelize. Assignment maps over data and update reduces sums and counts per group: each machine sends kk pairs (sum, count) of size dd, 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 kk.

[ ]Mini-batches: work, inertia and timeBrowser
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 × n×k\times\, n \times k for Lloyd, steps × b×k\times\, b \times k for mini-batches), independent of machine. Mini-batch work is the same in all three rows because it does not depend on nn; Lloyd work grows with nn and required iterations (11, 63 and 42 here). With n=2000n = 2000 mini-batches cost nearly five times more than full Lloyd (ratio 0.210.21): 100 steps of 1024 points scan more data than 11 iterations over 2000. With n=10 000n = 10\,000 and 50 00050\,000 they cost 6 and 20 times less, at the price of inertia between 0.10.1% and 3.43.4% higher than full Lloyd. The last two lines are scikit-learn and call for caution: MiniBatchKMeans inertia is 1414% 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 nn 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 x∈Rd\vb{x} \in \R^d with a label of log⁡2k\log_2 k bits and the receiver replaces it with its representative.

Two necessary conditions for QQ to be optimal with fixed kk (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 E[X∣X∈Vj]\E[\vb{X} \mid \vb{X} \in V_j]. Applied to a sample, this is literally k-means: inertia divided by nn is empirical distortion, and Lloyd is the LBG codebook-design algorithm. The difference is perspective: in compression kk is not a hypothesis about how many groups exist but a bit budget, and the entire D(R)D(R) curve matters.

How does DD fall with kk? For large kk and a regular density in dimension mm (with mm the data support dimension), Zador’s theorem (1982) says the optimal kk-level quantizer satisfies

Dk  ∼  cm ∥f∥m/(m+2)  k−2/m(k→∞),D_k \;\sim\; c_m \,\norm{f}_{m/(m+2)}\; k^{-2/m} \qquad (k \to \infty),

where cmc_m is a constant depending only on mm (under the usual condition that ff has a finite moment of order 2+δ2 + \delta). The exponent matters: every doubling of kk (one more bit per vector) multiplies distortion by 2−2/m2^{-2/m}, meaning an improvement of 6.02/m6.02/m dB per bit. For m=1m = 1 this is the familiar 6 dB per bit for a scalar quantizer; for RGB color in the full cube (m=3m = 3), 2.0 dB per bit; and for m=100m = 100 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 m<dm < d, the exponent is that of mm, not dd: the same intrinsic dimension idea from lesson 1, now with a direct effect on bits.

Shannon’s theory gives a floor: no rate-RR quantizer can beat the source’s distortion–rate function (rate–distortion function). For a Gaussian source of variance σ2\sigma^2 per component, D(R)=σ22−2RD(R) = \sigma^2 2^{-2R} per component (the same 6.02 dB per bit, without constant cmc_m), and optimal vector quantization of increasing dimension approaches that curve. The operating curve of real kk-means on a real image lies above it: this is what the interactive measures.

InteractiveColor quantization and the distortion–rate curve
Original
k-means, k=16k = 16
Codebook, most to least frequent
Distortion versus rate: PSNR (dB) versus bits per pixel log⁡2k\log_2 k
2.0 dB/bit (m = 3)
  • k-means codebook
  • uniform grid
  • high-resolution slope at m=3m = 3
16
Uniform grids require k=L3k = L^3. Select k=8k = 8, 2727 or 6464 to compare.
Colors and bits per pixel log⁡2k\log_2 k16 and 4.00
Displayed image PSNR32.13 dB
RMS error per channel (0 to 255)6.3
Gain per bit over the previous size6.29 dB/bit
At high resolution with mm degrees of freedom, each bit per pixel should gain 6.02/m6.02/m dB. If colors filled the RGB cube (m=3m = 3), this would be 2.01 dB/bit. A larger measured gain suggests the colors occupy fewer than three dimensions.
A synthetic 120×80120 \times 80-pixel scene (gradient sky, sun, mountains, hills and flowers, with uniform noise of ±5\pm 5) quantized to kk colors, from 2 to 64. Below, the codebook ordered by frequency (the 60 flowers of 3×33 \times 3 pixels make up at most 5.6% of the image: see what happens as kk falls) and PSNR against log⁡2k\log_2 k bits per pixel. The dashed line is the high-resolution slope for m=3m = 3, or 6.02/3≈2.06.02/3 \approx 2.0 dB per bit. Find diminishing returns: between which values of kk does another bit stop being worthwhile? With k=8k = 8, 2727 and 6464 switch to an equal-sized uniform grid and compare. Try your own photograph too: it stays in your browser.
[ ]Distortion–rate for color quantizationBrowser
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 m=3m = 3. At this scale the scene’s colors resemble a curve (m≈1m \approx 1, 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 ±5\pm 5 has variance 25/325/3, so a codebook that does not memorize noise cannot fall below MSE ≈8.3\approx 8.3, 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 k(n−k)k(n-k) swaps and an iteration costs O(k(n−k)2)\bigO(k(n-k)^2), quadratic in nn. 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 L1L^1 or a nonquadratic dissimilarity it is robust to outliers: a very distant datum weighs its distance, not its square.

[ ]PAM with Manhattan distance versus k-means with extreme outliersBrowser
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 ss. With s=15s = 15 both methods succeed. With s=30s = 30 mean k-means ARI falls to 0.330.33: inertia prefers isolating a few distant outliers to separating the groups. PAM with L1L^1 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 s=100s = 100 k-means is at 0.000.00 and PAM still at 0.830.83.

Kernel k-means. Another escape from Euclidean geometry is to apply k-means in a feature space ϕ(x)\phi(\vb{x}) without constructing it, using a kernel K(x,y)=ϕ(x)⊤ϕ(y)K(\vb{x}, \vb{y}) = \phi(\vb{x})\T\phi(\vb{y}) (kernel trick). The mean in feature space is μj=1nj∑l∈Cjϕ(xl)\vb{\mu}_j = \frac{1}{n_j}\sum_{l \in C_j}\phi(\vb{x}_l), and distance from a datum to it is expressed entirely with the kernel: ∥ϕ(xi)−μj∥2=Kii−2nj∑l∈CjKil+1nj2∑l,m∈CjKlm.\norm{\phi(\vb{x}_i) - \vb{\mu}_j}^2 = K_{ii} - \frac{2}{n_j}\sum_{l \in C_j} K_{il} + \frac{1}{n_j^2}\sum_{l, m \in C_j} K_{lm}. Lloyd works the same way (it is Euclidean k-means in ϕ\phi, so the termination proof still holds), at O(n2)\bigO(n^2) 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 σ→0\sigma \to 0 limit of EM for a Gaussian mixture with equal covariances σ2I\sigma^2\mat{I}: 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 kk groups. You must predict.

InteractiveWhich assumption breaks?
Data with true clusters, in the feature space seen by k-means
  • each color is a true cluster
Both axes have the same scale.
Will it recover the clusters?
Preprocessing
3
Colors show the true clusters. Predict whether k-means centroids can recover them, then select Run k-means.
Seven datasets and k-means with 20 k-means++ seeds. Choose one, decide whether you expect k-means to recover the colored groups, and run it. ARI measures agreement with true groups (1 is perfect, near 0 is chance). Always inspect inertia: in every failure in this panel the true partition has more inertia than k-means finds, so the failure is in the objective, not the optimizer: what k-means asks for is not what you see. Then try preprocessing. Standardization fixes 'Different units'. Whitening also fixes 'Anisotropic', which standardization alone did not. Adding ∥x∥2\norm{\vb{x}}^2 fixes rings and no other dataset (in the control it even destroys the result). For moons no preprocessing recovers the groups. Notice 'Unequal sizes' under standardization: ARI worsens. Which assumption does each act on?

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 xx, so total variance of xx (3.393.39) is more than three times that of yy (1.041.04) precisely because groups are separated in that direction. Standardizing divides xx by 1.841.84 and yy by 1.021.02, bringing groups closer without shrinking their dispersion in yy, and ARI falls from 0.640.64 to 0.110.11. 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 ∥x∥2\norm{\vb{x}}^2, one coordinate of the mapping implied by a polynomial kernel), and moons need another method (density in lesson 5, spectral in lesson 6).

Choosing kk: the elbow, cautiously. For fixed kk the minimum J⋆(k)J^\star(k) is nonincreasing in kk (adding a center never worsens it), and J⋆(n)=0J^\star(n) = 0. Therefore inertia cannot compare values of kk: it always prefers the largest. The most popular provisional criterion is the “elbow”: plot J(k)J(k) 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.

[ ]The elbow: with and without groupsBrowser
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, J(k)/J(k−1)J(k)/J(k-1) falls to 0.120.12 exactly at k=4k = 4 and returns to ≈0.9\approx 0.9: a clear elbow. With uniform data, which have no groups, the ratio rises from 0.640.64 to 0.820.82 at k=5k = 5: 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).

[ ]Elkan versus Lloyd in scikit-learnBrowser
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

ProofThe mean minimizes, and inertia is pairwise distance
Prove: For x1,…,xm∈Rd\vb{x}_1, \dots, \vb{x}_m \in \R^d with mean xˉ\bar{\vb{x}} and S=∑i∥xi−xˉ∥2S = \sum_i \norm{\vb{x}_i - \bar{\vb{x}}}^2: (a) ∑i∥xi−c∥2=S+m∥xˉ−c∥2\sum_i \norm{\vb{x}_i - \vb{c}}^2 = S + m\norm{\bar{\vb{x}} - \vb{c}}^2 for every c\vb{c}, so the mean is the unique minimizer; (b) S=12m∑i,j∥xi−xj∥2S = \frac{1}{2m}\sum_{i,j}\norm{\vb{x}_i - \vb{x}_j}^2.
0
Start with (a); (b) follows by applying (a) with a clever choice of c\vb{c}.

Step 1 of 4. How do you prepare the square ∥xi−c∥2\norm{\vb{x}_i - \vb{c}}^2 to compare with the mean?

ProofLloyd does not raise inertia and terminates
Prove: With tie-breaking rule 'a datum changes group only if the new centroid is strictly closer', Lloyd's algorithm never increases JJ, strictly decreases it when assignment changes, and terminates in finitely many iterations.
0
Let z(t)z^{(t)} be assignment and μ(t)\vb{\mu}^{(t)} the group means, and examine one iteration.

Step 1 of 4. Why is J(z(t+1),μ(t))≤J(z(t),μ(t))J(z^{(t+1)}, \vb{\mu}^{(t)}) \le J(z^{(t)}, \vb{\mu}^{(t)})?

NumericOptimal inertia in one dimension
For one-dimensional points {0,1,2,10,11,12}\{0, 1, 2, 10, 11, 12\} and k=2k = 2, calculate minimum inertia J⋆J^\star.
NumericOne Lloyd iteration by hand
The data are (0,0)(0, 0), (2,0)(2, 0), (0,2)(0, 2), (10,10)(10, 10) and (12,10)(12, 10), and initial centroids (0,0)(0, 0) and (2,0)(2, 0). Perform one complete iteration (assign and update). What is inertia JJ with the new centroids and just-calculated assignment?
NumericA move Lloyd would not make
Group AA has nA=10n_A = 10 points and BB has nB=2n_B = 2. A datum x∈A\vb{x} \in A is distance 22 from μA\vb{\mu}_A and 2.52.5 from μB\vb{\mu}_B, so Lloyd leaves it in place. Calculate the change ΔJ\Delta J in total inertia if you move it from AA to BB.
Numerick-means++ on the rectangle
The four corners (±L,±1)(\pm L, \pm 1) with L=3L = 3 and k=2k = 2. With k-means++ seeding, what is the probability that the two initial centers lead Lloyd to the optimum, meaning they fall on opposite sides of the rectangle?
NumericPSNR gain with two more bits
At high resolution, with data filling a space of dimension m=3m = 3 (the RGB cube), distortion of the optimal kk-level quantizer is Dk∝k−2/3D_k \propto k^{-2/3}. How many dB of PSNR are gained moving from k=16k = 16 to k=64k = 64 colors? (PSNR =10log⁡10(2552/MSE)= 10\log_{10}(255^2/\text{MSE}).)
CodeImplement k-means++ seeding
Implement 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 D2D^2 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()
Shift+Enter to run
QuizWhich variant for each scenario?
Choose the most reasonable k-means variant for each scenario: (i) cluster strings with edit distance; (ii) two concentric rings of planar points; (iii) 10710^7 vectors of dimension 50 that do not fit in memory; (iv) customers with purchase amounts containing extreme outliers, where a small group of enormous amounts should not determine the groups.
QuizWhat is guaranteed and what is not
Which of these claims about k-means are true?

More than one answer may be correct.

Summary

Key idea
k-means minimizes within-cluster sum of squares JJ, and Lloyd does so by coordinate descent: assignment to the nearest centroid (Voronoi cells) and the mean as optimal representative. JJ falls at each step and the algorithm terminates, but at a local optimum; the problem is NP-hard and seeding therefore matters: k-means++ provides an O(log⁡k)\bigO(\log k) guarantee in expectation. Viewed as compression it is vector quantization, and its assumptions about data (convex, isotropic groups of similar dispersion and size, and a mean that is a good representative) must be checked before trusting it.
  • Inertia is within-cluster sum of squares; the mean minimizes each group, and JJ is mean squared pairwise distance within groups. Minimizing JJ is equivalent to maximizing between-group dispersion.
  • Lloyd alternates assignment (convex Voronoi cells) and update (means). Cost per iteration O(nkd)\bigO(nkd). It does not increase JJ, strictly decreases it when assignment changes and terminates at a fixed point, a local minimum of J(μ)J(\vb{\mu}), not necessarily global or Hartigan–Wong optimal.
  • The problem is NP-hard (even with k=2k = 2 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++ (D2D^2 sampling) guarantees E[φ]≤8(ln⁡k+2)φOPT\E[\varphi] \le 8(\ln k + 2)\varphi_{\mathrm{OPT}}; in practice, ninitn_{\text{init}} restarts raise success probability to 1−(1−p)ninit1 - (1 - p)^{n_{\text{init}}}.
  • 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 nn, 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 k−2/mk^{-2/m}, 6.02/m6.02/m dB per bit, with mm 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 kk, and the elbow is only a clue.