Module contents
Lesson 7 of 24Core 75 min

Evaluating a clustering

Internal and external clustering validation, selecting cluster count, stability and Kleinberg's impossibility theorem.

After this lesson you can

  • Compute internal indices and explain their geometric biases.
  • Compute chance-corrected external indices from contingency tables.
  • Implement gap statistic and resampling stability to choose k.
  • State Kleinberg's impossibility theorem and discuss its consequences.
  • Design evaluation without leaking labels into tuning.

Before you start

Motivation: three algorithms, three partitions—which is better?

You have seen several ways to cluster: k-means, hierarchical clustering, DBSCAN and spectral clustering. Each returns a partition, and partitions rarely agree. In supervised learning, comparing models is simple: measure error on data not used to fit them. In clustering there is no single correct answer to measure against, the source of almost everything difficult in this lesson.

A first experiment: the familiar two moons, three algorithms and four measures you will learn to use—silhouette, Davies–Bouldin and Calinski–Harabasz (using only data and partition), and ARI (comparing with the partition generating the data).

[ ]Three algorithms on the same moons, four measuresBrowser
import numpy as np, warnings
from sklearn.datasets import make_moons
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from sklearn.metrics import silhouette_score, davies_bouldin_score, calinski_harabasz_score, adjusted_rand_score
warnings.filterwarnings("ignore")

X, y = make_moons(n_samples=300, noise=0.07, random_state=0)
particiones = {
    "k-means (k=2)": KMeans(2, n_init=10, random_state=0).fit_predict(X),
    "Ward (k=2)": AgglomerativeClustering(2, linkage="ward").fit_predict(X),
    "DBSCAN (eps=0.2)": DBSCAN(eps=0.2, min_samples=5).fit_predict(X),
    "verdad": y,
}
print(f"{'partición':18s} clusters ruido  silhouette    DB      CH     ARI")
for nombre, l in particiones.items():
    k = len(set(l) - {-1}); ruido = int((l == -1).sum())
    print(f"{nombre:18s} {k:5d} {ruido:6d}  {silhouette_score(X, l):9.3f} {davies_bouldin_score(X, l):7.2f} {calinski_harabasz_score(X, l):7.1f} {adjusted_rand_score(y, l):7.3f}")

Read the table carefully. DBSCAN recovers both moons exactly (ARI 1.000), yet scores worst on all three internal measures: silhouette 0.326 (lowest), Davies–Bouldin 1.17 (highest, and lower is better), and Calinski–Harabasz 192.5 (lowest). k-means, which cuts each moon in half, gets 0.487, 0.78 and 438.9, and Ward, which also cuts them badly, 0.443, 0.77 and 326.3: indices prefer these partitions to the correct one (Ward beats k-means by one hundredth on Davies–Bouldin), and their ARI against truth is 0.234 and 0.399. The calculation has no error. Internal indices measure one thing (compactness and separation of centers) while a human viewing moons wants another (continuity). Understanding what each index measures and which geometry it rewards is the lesson’s first part.

Evaluation methods fall into three families, all covered here:

  • Internal indices: score a partition using only data (silhouette, Davies–Bouldin, Calinski–Harabasz). They need no labels but embed a notion of a good cluster.
  • External indices: compare a partition with a reference (ARI, NMI, AMI). They validate methods on labeled data and measure agreement between partitions, but “truth” is not always what you want to find.
  • Criteria for choosing kk: elbow, information criteria, gap statistic and resampling stability. They compare solutions from one method at different kk.

Finally Kleinberg’s theorem explains why this area is fundamentally uncomfortable, and a practical protocol shows how to evaluate without fooling yourself.

Internal indices

Silhouette

Let nn points be partitioned into k≥2k \ge 2 clusters C1,…,CkC_1, \dots, C_k with dissimilarity dd. For point ii in cluster CIC_I with ∣CI∣≥2\abs{C_I} \ge 2, measure two mean distances: to other points in its cluster and to points in its nearest other cluster.

Since a,b≥0a, b \ge 0, ∣b−a∣≤max⁡{a,b}\abs{b - a} \le \max\{a, b\} and hence s(i)∈[−1,1]s(i) \in [-1, 1]. An s(i)s(i) near 1 means the point is much closer to its cluster than the neighboring one; s(i)≈0s(i) \approx 0 means it lies on a boundary; s(i)<0s(i) < 0 means it is on average closer to another cluster. As a distance ratio, ss is unchanged by multiplying all distances by a positive constant. Rousseeuw plotted s(i)s(i) sorted by cluster in the silhouette plot shown interactively: one bar per point, grouped by cluster and sorted descending, so block height is cluster size and shape reveals misassigned points.

Before reading further, inspect the moons. Initially k-means with k=2k = 2 cuts each moon in half, and silhouette rewards it; the true partition scores much lower. One point is fixed to show where a(i)a(i) and b(i)b(i) come from; hover over others.

InteractiveThe silhouette plot
k-means with k=2k = 2 (moons)
s = 0.55
Silhouette plot: one bar per point, grouped by cluster
s̄ = 0.48212
Mean k-means silhouette versus kk
truth 0.32
  • distances to own cluster (aa)
  • distances to neighboring cluster (bb)
  • ground-truth partition silhouette (below)
Data
Partition
2
Mean silhouette sˉ\bar s0.482
sˉ\bar s of ground truth0.317
ARI against ground truth0.246
Davies-Bouldin (lower is better)0.78
Calinski-Harabasz (higher is better)287
point 1: aa, bb, ss0.65, 1.45, 0.55
k-means with k=2k = 2 scores 0.482 and its ARI against ground truth is 0.25; la partición verdadera scores 0.317. The index prefers the wrong partition because it rewards compact convex clusters.
Data (left) and silhouette plot (right) for your chosen partition, with mean k-means silhouette for kk from 2 to 8 below. Gray solid lines join the point to its cluster, magenta dashed lines to the neighboring cluster: a(i)a(i) and b(i)b(i) are mean lengths. Initially (moons, k-means with k=2k = 2), mean silhouette is 0.482 and the true partition's 0.317: the index prefers the wrong partition. The fixed point is the upper moon's tip: with k-means a=0.65a = 0.65, b=1.45b = 1.45 and s=0.55s = 0.55. Switch to 'truth': the same point now has a=1.31a = 1.31 (its moon extends far away) and b=0.74b = 0.74 (the other moon passes nearby), so s=−0.43s = -0.43; 33 of 200 points have s<0s < 0 in the correct partition. Concentric rings are worse (truth 0.131 versus k-means k=2k = 2 at 0.340), and on both rings and moons the k-means curve peaks at the endpoint k=8k = 8 (0.402 and 0.508): chopping shapes into many compact pieces scores higher than preserving them. For three clouds the maximum is at correct kk (0.616 with k=3k = 3).

These numbers come from an explicit model: 180 to 200 points per dataset, k-means with k-means++ and 6 starts, and the definitions above (code verified against scikit-learn). The observation is not an algorithmic accident. Silhouette is a function of mean distances: it rewards clusters that, like compact clouds, have small internal mean distances relative to their separation from others. An elongated or curved cluster has large a(i)a(i) even when perfectly coherent.

Davies–Bouldin and Calinski–Harabasz

The other two classical indices use cluster centroids μj\boldsymbol\mu_j instead of point-to-point distances, so are defined only for data with a mean (typically vectors in Rd\R^d with Euclidean distance).

WW is exactly k-means inertia. Its connection to BB is a variance decomposition.

Proof

For x∈Cj\vb{x} \in C_j, write x−μ=(x−μj)+(μj−μ)\vb{x} - \boldsymbol\mu = (\vb{x} - \boldsymbol\mu_j) + (\boldsymbol\mu_j - \boldsymbol\mu) and expand the square. Summing over x∈Cj\vb{x} \in C_j, the cross term is 2(μj−μ)⊤∑x∈Cj(x−μj)=02 (\boldsymbol\mu_j - \boldsymbol\mu)\T \sum_{\vb{x} \in C_j} (\vb{x} - \boldsymbol\mu_j) = 0, since μj\boldsymbol\mu_j is the mean of CjC_j. This leaves ∑x∈Cj∥x−μj∥2+∣Cj∣ ∥μj−μ∥2\sum_{\vb{x} \in C_j} \norm{\vb{x} - \boldsymbol\mu_j}^2 + \abs{C_j}\,\norm{\boldsymbol\mu_j - \boldsymbol\mu}^2, and summing over jj gives W+BW + B.

∎

Since TT does not depend on the partition, minimizing WW (k-means) maximizes BB, and CH\mathrm{CH} is the ratio of two mean squares forming the one-way ANOVA FF statistic. One important caveat: clusters here were chosen by looking at data, so the statistic does not follow an FF distribution and has no honest p-value. It only compares partitions. Moreover, CH\mathrm{CH} is undefined for k=1k = 1, as are DB\mathrm{DB} and silhouette: none can say there are no groups.

What geometry they reward

The motivating table already contains the lesson. All three measures depend on two quantities: how compact each cluster is relative to a center or neighbors, and how separated clusters are. This makes them excellent for choosing among k-means solutions (which optimize compactness) and poor judges of methods not seeking compactness. In summary:

  • They favor convex clusters of similar size and dispersion. An elongated, curved cluster or one surrounding another scores poorly even if it is the desired structure.
  • They compare the partition only with an idea of a “good cluster”; they do not compare with absence of structure. A uniform cloud also scores, as the cell below shows.
  • They depend on the chosen distance. In high dimension distances concentrate and hubs appear, shrinking the relative difference between a(i)a(i) and b(i)b(i).
  • With noise marked as another cluster (as DBSCAN does with label −1-1), the result depends on its treatment: this is not an innocuous convention.

For density methods, indices designed around another cluster notion exist (DBCV, Moulavi and colleagues, 2014, is best known), but deserve the same caution: each index carries its own definition of a good cluster.

The next lab implements all three indices from scratch (vectorized silhouette, without loops over points), compares them with scikit-learn and checks decomposition T=B+WT = B + W.

[ ]Silhouette, Davies–Bouldin and Calinski–Harabasz from scratchBrowser
import numpy as np, warnings
from scipy.spatial.distance import cdist
from sklearn.datasets import make_moons, make_blobs
from sklearn.cluster import KMeans
from sklearn import metrics as M
warnings.filterwarnings("ignore")

def silhouette(X, l):
    D = cdist(X, X)                                  # n x n distancias
    ks = np.unique(l)
    S = np.stack([D[:, l == c].sum(1) for c in ks], axis=1)   # suma de distancias de cada punto a cada cluster
    size = np.array([(l == c).sum() for c in ks])
    own = np.searchsorted(ks, l)
    a = S[np.arange(len(X)), own] / np.maximum(size[own] - 1, 1)
    media = S / size
    media[np.arange(len(X)), own] = np.inf           # b(i): el mejor de los OTROS clusters
    b = media.min(1)
    s = (b - a) / np.maximum(a, b)
    s[size[own] == 1] = 0                            # convenio de Rousseeuw: cluster unitario
    return s.mean()

def davies_bouldin(X, l):
    ks = np.unique(l)
    C = np.array([X[l == c].mean(0) for c in ks])
    S = np.array([np.linalg.norm(X[l == c] - C[i], axis=1).mean() for i, c in enumerate(ks)])
    Mij = cdist(C, C); np.fill_diagonal(Mij, np.inf)
    return ((S[:, None] + S[None, :]) / Mij).max(1).mean()

def calinski_harabasz(X, l):
    ks = np.unique(l); n = len(X); mu = X.mean(0)
    C = np.array([X[l == c].mean(0) for c in ks]); nj = np.array([(l == c).sum() for c in ks])
    B = (nj * ((C - mu) ** 2).sum(1)).sum()
    W = sum(((X[l == c] - C[i]) ** 2).sum() for i, c in enumerate(ks))
    return (B / (len(ks) - 1)) / (W / (n - len(ks))), B, W

for nombre, (X, y), k in [("nubes", make_blobs(300, centers=4, cluster_std=1.2, random_state=3), 4),
                          ("lunas", make_moons(300, noise=0.07, random_state=0), 2)]:
    l = KMeans(k, n_init=10, random_state=0).fit_predict(X)
    ch, B, W = calinski_harabasz(X, l)
    T = ((X - X.mean(0)) ** 2).sum()
    print(f"{nombre}: silhouette {silhouette(X, l):.6f} (sklearn {M.silhouette_score(X, l):.6f})")
    print(f"       DB {davies_bouldin(X, l):.6f} (sklearn {M.davies_bouldin_score(X, l):.6f})   CH {ch:.4f} (sklearn {M.calinski_harabasz_score(X, l):.4f})")
    print(f"       T = {T:.4f}, B + W = {B + W:.4f}")

Implementations match scikit-learn to six digits, and T=B+WT = B + W holds to the cent. Now the promised warning: what silhouette does k-means obtain on entirely structureless data?

[ ]A uniform cloud also scoresBrowser
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X = np.random.default_rng(0).uniform(size=(300, 2))
for k in range(2, 7):
    l = KMeans(k, n_init=5, random_state=0).fit_predict(X)
    print(f"k = {k}: silhouette = {silhouette_score(X, l):.3f}")

Between 0.36 and 0.40 for uniform points in a square. On the scale Kaufman and Rousseeuw (1990) propose in their reference book, 0.26 to 0.50 indicates weak structure that might be artificial: that is what appears here, and a good reason not to treat a “reasonable” silhouette as proof of groups. To know whether groups exist, compare with a structureless reference, exactly what the gap statistic below does.

External indices

If you have a reference partition VV (class labels, expert annotations, synthetic-data truth), compare yours, UU, with it. Cluster names are arbitrary, so comparison can depend only on which points are together and which are not. The contingency table summarizes everything.

The second equality follows from N00=(n2)−A−B+N11N_{00} = \binom n2 - A - B + N_{11} (inclusion–exclusion over pairs together in UU or VV). RI\mathrm{RI} is 1 if and only if partitions agree. The problem appears when comparing with chance: independent partitions with many clusters leave almost all pairs separated in both, which counts as agreement. Thus RI\mathrm{RI} rises with cluster count even without a relationship. Hubert and Arabie’s correction subtracts chance expectation and rescales.

What “by chance” means

The chance model is permutation or hypergeometric: fix each partition’s cluster sizes (marginals aia_i and bjb_j) and distribute the rest randomly, uniformly permuting VV labels while keeping UU fixed. Under that model expected N11N_{11} is simple.

Proof

N11N_{11} counts pairs {p,q}\{p, q\} together in UU that are also together in VV after permutation: N11=∑{p,q} junto en U1[{p,q} junto en Vπ]N_{11} = \sum_{\{p, q\} \text{ junto en } U} \ind[\{p, q\} \text{ junto en } V_\pi]. There are AA terms. For a fixed one, {p,q}\{p, q\} corresponds under uniform permutation to a uniform pair of distinct VV elements, together with probability B/(n2)B / \binom n2 (there are BB together pairs among (n2)\binom n2 possible pairs). Linearity of expectation gives A⋅B/(n2)A \cdot B / \binom n2.

∎

The denominator uses the possible maximum of N11N_{11} under Hubert and Arabie’s convention: N11≤min⁡{A,B}≤(A+B)/2N_{11} \le \min\{A, B\} \le (A + B)/2, using the mean as a bound. ARI 0 means UU resembles VV as much as a random partition with the same marginals; it can be negative (less agreement than chance); and it is unchanged by renaming clusters or swapping UU and VV.

Mutual information, NMI, V-measure and AMI

The other family measures how much knowing the UU cluster reduces uncertainty about the VV cluster. With Shannon entropies H(U)=−∑iainlog⁡ainH(U) = -\sum_i \frac{a_i}{n} \log \frac{a_i}{n} (and analogously H(V)H(V)), and mutual information

I(U;V)=∑i,jnijnlog⁡n nijaibj=H(U)+H(V)−H(U,V),I(U; V) = \sum_{i, j} \frac{n_{ij}}{n} \log \frac{n \, n_{ij}}{a_i b_j} = H(U) + H(V) - H(U, V),

normalize II to [0,1][0, 1]. Since I≤min⁡{H(U),H(V)}I \le \min\{H(U), H(V)\}, any mean of the entropies can normalize; the arithmetic choice gives

NMI(U,V)=I(U;V)12(H(U)+H(V)),\mathrm{NMI}(U, V) = \frac{I(U; V)}{\tfrac12 \bigl(H(U) + H(V)\bigr)},

scikit-learn’s default (other variants use geometric mean, maximum or minimum). Rosenberg and Hirschberg’s V-measure is the harmonic mean of homogeneity h=1−H(V∣U)/H(V)h = 1 - H(V \mid U)/H(V) (each cluster contains elements of one class only) and completeness c=1−H(U∣V)/H(U)c = 1 - H(U \mid V)/H(U) (each class lies in one cluster). Since H(V∣U)=H(V)−IH(V \mid U) = H(V) - I, we obtain h=I/H(V)h = I/H(V), c=I/H(U)c = I/H(U) and

V-measure=2hch+c=2IH(U)+H(V)=NMIaritmeˊtica.\text{V-measure} = \frac{2 h c}{h + c} = \frac{2 I}{H(U) + H(V)} = \mathrm{NMI}_{\text{aritmética}}.

They are the same number: V-measure is NMI with arithmetic normalization.

NMI has the same problem as Rand, with an exact explanation. Empirical mutual information of an r×sr \times s table with nn elements is positive even when UU and VV are independent: the independence likelihood-ratio statistic G=2nIG = 2 n I follows, for nn large relative to cell count, a χ2\chi^2 with (r−1)(s−1)(r-1)(s-1) degrees of freedom, so E[I]≈(r−1)(s−1)/(2n)\E[I] \approx (r-1)(s-1)/(2n) nats, growing with cluster count. NMI rises with kk because its numerator rises with kk. Vinh, Epps and Bailey (2010) correct this with the same trick as ARI.

The right-hand factor is the hypergeometric probability that cell (i,j)(i, j) contains nijn_{ij} elements: select bjb_j elements of VjV_j among nn and require nijn_{ij} to fall in UiU_i. Computing E[I]\E[I] takes O(r s min⁡(ai,bj))\bigO(r \, s \, \min(a_i, b_j)) evaluations and uses log factorials (gammaln) to avoid overflow: AMI is therefore substantially more expensive than NMI with many clusters, and the interactive computes it at every step.

Here is the whole phenomenon. The interactive takes fixed truth with KK balanced classes and compares random partitions of kk clusters. Start with ρ=0\rho = 0 (no shared information) and see which index remains near 0 as kk grows.

InteractiveIndices that rise without information
Mean (line) and ± 1 standard deviation (band) of 30 partitions per kk
Mutual information II and its expected value E[I]\E[I] (nats)
  • Rand
  • NMI
  • ARI
  • AMI
  • mutual information II (right)
  • expected value E[I]\E[I] (right)
100
4
40
0.00
12
Rand, NMI with k=12k = 120.715, 0.103
ARI, AMI with k=12k = 120.002, 0.000
Largest mean ∣AMI∣|\mathrm{AMI}| across all kk0.012
Partitions are independent of ground truth, so shared information is zero. Yet with k=12k = 12 the Rand index is 0.71 and NMI is 0.10; ARI and AMI are 0.002 and 0.000. NMI rises because empirical mutual information in a 4 × 12 table with 100 points is positive even without a relationship (0.20 nats, versus an expected value of 0.20).
With ρ=0\rho = 0 partitions are independent of truth (n = 100, K = 4). Rand rises from 0.50 (with k=2k = 2) to 0.74 (with k=40k = 40) and NMI from 0.01 to 0.25 without shared information; ARI and AMI stay near 0 with narrow bands. Right, mutual information II and its expectation E[I]\E[I] under the hypergeometric model grow together with kk (0.61 and 0.62 nats at k=40k = 40): AMI is their normalized difference, hence 0. Raise ρ\rho to 0.3: a fraction of points respects truth (each class splits into random subclusters when k>Kk > K), and Rand and NMI still maximize at k=40k = 40, the scale's end, whereas ARI and AMI maximize at k=4k = 4 and k=6k = 6. At ρ=0.6\rho = 0.6 all four agree on k=K=4k = K = 4. Raise kmax⁡k_{\max} and lower nn: the band widens because index variance is large with few points.

The model is explicit: truth has KK classes of n/Kn/K points, and a partition into kk clusters gives each point, with probability ρ\rho, a cluster compatible with its class (if k≤Kk \le K, class modulo kk; if k>Kk > K, a randomly chosen subcluster of its class) and otherwise a uniform one in {1,…,k}\{1, \dots, k\}. Thirty partitions are averaged for each kk.

Now the lab: contingency table, Rand, ARI, NMI and AMI from scratch (with E[I]\E[I] by the hypergeometric formula), compared with scikit-learn; the identity V-measure == NMI; and a simulation check of the expectation theorem.

[ ]Contingency, Rand, ARI, NMI and AMI from scratchBrowser
import numpy as np, warnings
from scipy.special import gammaln, comb
from sklearn import metrics as M
warnings.filterwarnings("ignore")

def contingencia(u, v):
    _, iu = np.unique(u, return_inverse=True); _, iv = np.unique(v, return_inverse=True)
    T = np.zeros((iu.max() + 1, iv.max() + 1), dtype=int)
    np.add.at(T, (iu, iv), 1)
    return T

def rand_ari(T):
    n = T.sum()
    sij = comb(T, 2).sum(); sa = comb(T.sum(1), 2).sum(); sb = comb(T.sum(0), 2).sum()
    tot = comb(n, 2)
    rand = (tot + 2 * sij - sa - sb) / tot
    esperado = sa * sb / tot
    ari = (sij - esperado) / ((sa + sb) / 2 - esperado)
    return rand, ari

def entropia(c):
    p = c[c > 0] / c.sum()
    return -(p * np.log(p)).sum()

def info_mutua(T):
    n = T.sum(); a = T.sum(1, keepdims=True); b = T.sum(0, keepdims=True)
    nz = T > 0
    return ((T[nz] / n) * np.log(n * T[nz] / (a @ b)[nz])).sum()

def mi_esperada(T):
    """E[I] bajo el modelo hipergeométrico (marginales fijas): Vinh, Epps y Bailey (2010)."""
    n = T.sum(); a = T.sum(1); b = T.sum(0)
    lf = lambda x: gammaln(np.asarray(x, dtype=float) + 1)
    e = 0.0
    for ai in a:
        for bj in b:
            nij = np.arange(max(1, ai + bj - n), min(ai, bj) + 1)
            logp = (lf(ai) + lf(n - ai) + lf(bj) + lf(n - bj) - lf(n) - lf(nij)
                    - lf(ai - nij) - lf(bj - nij) - lf(n - ai - bj + nij))
            e += ((nij / n) * np.log(n * nij / (ai * bj)) * np.exp(logp)).sum()
    return e

def nmi_ami(T):
    ha, hb = entropia(T.sum(1)), entropia(T.sum(0))
    I, E = info_mutua(T), mi_esperada(T)
    media = (ha + hb) / 2
    return I / media, (I - E) / (media - E)

rng = np.random.default_rng(1)
u = rng.integers(0, 4, 60); v = rng.integers(0, 7, 60)       # dos particiones independientes
T = contingencia(u, v)
rand, ari = rand_ari(T); nmi, ami = nmi_ami(T)
print("tabla", T.shape, " Rand", round(rand, 6), round(M.rand_score(u, v), 6))
print("ARI", round(ari, 6), round(M.adjusted_rand_score(u, v), 6), " NMI", round(nmi, 6), round(M.normalized_mutual_info_score(u, v), 6),
      " AMI", round(ami, 6), round(M.adjusted_mutual_info_score(u, v), 6))

h, c, vm = M.homogeneity_completeness_v_measure(u, v)
print(f"homogeneidad {h:.4f}, completitud {c:.4f}, V-measure {vm:.6f}  =  NMI {nmi:.6f}")

sa = comb(T.sum(1), 2).sum(); sb = comb(T.sum(0), 2).sum()
sims = [comb(contingencia(u, rng.permutation(v)), 2).sum() for _ in range(4000)]
print(f"E[N11]: fórmula {sa * sb / comb(60, 2):.3f}, simulación con 4000 permutaciones {np.mean(sims):.3f}")

Everything matches scikit-learn. For independent partitions ARI is 0.0001 and AMI 0.013, while NMI reports 0.122: even with 60 points and a 4×74 \times 7 table there is “noise” mutual information. Now the interactive’s experiment in numbers: random partitions of n=100n = 100 points against truth with 4 classes of 25.

[ ]Random partitions against fixed truthBrowser
rng = np.random.default_rng(7)
n, K, R = 100, 4, 40
verdad = np.repeat(np.arange(K), n // K)
print(f"verdad: {K} clases de {n // K}; partición uniforme al azar con k clusters; media de {R} réplicas")
print("  k    Rand    NMI     ARI     AMI   E[I] exacta  (K-1)(k-1)/2n")
for k in (2, 5, 10, 20, 50):
    vals = []
    for _ in range(R):
        T = contingencia(verdad, rng.integers(0, k, n))
        vals.append((*rand_ari(T), *nmi_ami(T), mi_esperada(T)))
    m = np.mean(vals, 0)                       # columnas: Rand, ARI, NMI, AMI, E[I]
    print(f"{k:3d}  {m[0]:6.3f}  {m[2]:6.3f}  {m[1]:6.3f}  {m[3]:6.3f}   {m[4]:9.3f}   {(K - 1) * (k - 1) / (2 * n):9.3f}")

NMI rises from 0.013 to 0.287 and Rand from 0.500 to 0.747 solely by using more clusters, while ARI and AMI stay at zero (between −0.005 and 0.000). The last columns compare exact expected mutual information with asymptotic approximation (K−1)(k−1)/2n(K-1)(k-1)/2n: they agree at small kk (0.015 and 0.015 with k=2k = 2) and diverge when there are few points per cell (0.347 versus 0.285 at k=20k = 20). Do not be fooled by k=50k = 50, where they look similar again (0.724 versus 0.735): the curves cross. The approximation grows linearly without bound with kk, while exact expectation is bounded because I(U;V)≤H(V)=log⁡4≈1.386I(U; V) \le H(V) = \log 4 \approx 1.386 nats for 4 balanced classes; at k=100k = 100 the approximation would give 1.4851.485, impossible. Approximation needs many points per cell (here with k=50k = 50 there is half a point per cell); with large tables and little data use the exact formula.

Two nuances for proper use. First, chance correction does not make indices universal: Romano, Vinh, Bailey and Verspoor (2016) study when each is appropriate and recommend ARI when the reference has large similarly sized clusters, and AMI when imbalanced with small clusters. Second, the chance model is a convention: correction is exact for fixed-marginal permutations, which may not be your desired null model.

Choosing the number of clusters

Most algorithms in this module ask for kk (or a substitute: ε\varepsilon, bandwidth, cut height). This section’s criteria compare solutions from one method with different kk and select the best by some criterion.

The elbow. WkW_k, minimum inertia with kk clusters, does not increase with kk (a cluster in a kk-partition can always be split without increasing WW), so it cannot simply be minimized. Convention plots WkW_k and seeks an “elbow” where improvement stops being large. It helps when present, but “where the elbow begins” is subjective and an elbow also appears in structureless data: with regular density in dimension mm, Zador’s theorem (lesson 2) says for large kk, Wk≈C k−2/mW_k \approx C\, k^{-2/m}, a smooth convex curve with no privileged point, yet the eye finds an “elbow.”

Information criteria. If a Gaussian mixture is fitted, BIC =−2log⁡L^+plog⁡n= -2 \log \hat L + p \log n penalizes likelihood by parameter count pp and has a minimum at finite kk. It is a complete probabilistic model, studied in detail in mixture model selection; here it is one more candidate.

Maximum silhouette or Calinski–Harabasz. Calculate the index for each kk and take the maximum (minimum for Davies–Bouldin). They inherit all previous geometric biases, and all require k≥2k \ge 2.

The gap statistic

Gap supplies the missing idea: compare log⁡Wk\log W_k not with other kk values but with what log⁡Wk\log W_k would be if data had no structure. First, write WkW_k using pairwise distances.

Each piece has a purpose. The logarithm turns data units into an additive constant canceling in gap, and compares relative dispersion drops. The reference gives gap meaning: it must be a groupless distribution on the same support. Tibshirani and colleagues propose two: uniform points in the data’s bounding box (each variable’s range), and uniform points in a box aligned to principal components, accounting for global data shape. Factor 1+1/B\sqrt{1 + 1/B} adds error from approximating the reference mean with BB samples to reference deviation. The rule seeks the first kk such that increasing to k+1k+1 improves gap by no more than one standard error: improvement is attributed to reference-sample noise.

A direct consequence: gap can say k^=1\hat k = 1, while silhouette, DB and CH cannot. With a uniform cloud, log⁡Wk\log W_k and its reference fall alike, gap fluctuates around 0 and the rule stops at the first kk.

The interactive calculates everything live for four datasets. Initially, the one-standard-deviation rule fails even though groups are obvious: three clouds in an equilateral triangle.

InteractiveThe gap statistic
Data (color: k-means with k=1k = 1)
log⁡Wk\log W_k observed and expected under the reference (band: ±sk\pm s_k)
Gap(k)\mathrm{Gap}(k) with error bars sks_k; the rule stops at the first marked kk
Gap(1) = 0.39 versus Gap(2) − s = 0.27
  • log⁡Wk\log W_k of your data
  • mean log⁡Wk\log W_k in the reference
  • kk chosen by the one-standard-error rule
  • global gap maximum
Data
1.00
10
k^\hat k (one-standard-error rule)1
kk at the global gap maximum3
kk true3
The rule selects k^=1\hat k = 1, not the 3 grupos verdaderos. El máximo global del gap sí está at k=3k = 3 (1.07), but earlier the condition already holds Gap(1)=0.39≥Gap(2)−s2=0.27\mathrm{Gap}(1) = 0.39 \ge \mathrm{Gap}(2) - s_{2} = 0.27 and the rule stops at the first candidate.
Left: data (150 points, clouds of standard deviation 1) colored by k-means with chosen kk; 'reference sample' shows uniform bounding-box points used for comparison. Upper right, data log⁡Wk\log W_k (blue) and reference mean with band (gray). Below, Gap(k)\mathrm{Gap}(k) with error bars sks_k. For the equilateral triangle the global gap maximum is at k=3k = 3 (1.07), but Gap(2)=0.32\mathrm{Gap}(2) = 0.32 does not exceed Gap(1)=0.39\mathrm{Gap}(1) = 0.39 and the rule stops at k=1k = 1. At k=2k = 2, k-means isolates one cloud and merges two, and data log⁡W\log W falls 0.53, slightly less than the uniform reference's 0.60: at that step data are indistinguishable from noise. The large drop comes from 2 to 3 (1.15 versus 0.41), after the rule has stopped. Move separation: throughout the slider range the rule says k=1k = 1 for the triangle, while on the row it succeeds from 0.45. 'In a row' and 'two pairs' show the other behaviors: in a row Gap(3)=1.00\mathrm{Gap}(3) = 1.00 dominates and the rule succeeds; with two cloud pairs it stops at k=2k = 2 (coarse resolution) despite four clouds and a global maximum at k=4k = 4. Without structure, gap is compatible with 0 (maximum 0.07, error sk≈0.06s_k \approx 0.06) and the rule says k=1k = 1.

The interactive shows an honest limitation of gap, not an implementation defect. It compares against a unimodal uniform reference and can have multiple local maxima: with hierarchical structure (cloud pairs) or symmetry, the one-standard-deviation rule stops at the first. Other selection rules therefore exist (implementations such as clusGap in R’s cluster package offer Tibshirani’s and global maximum among them), and sensible practice plots all of Gap(k)\mathrm{Gap}(k) before reading one number.

Stability

Another way to choose kk examines not partition geometry but reproducibility: if data sample a population with kk groups, two different samples should yield similar partitions at the correct kk. With excessive kk, the algorithm splits groups by arbitrary cuts changing across samples; with too few clusters, it must merge groups, sometimes in several equally good ways.

In the interactive, groups are KK clouds of standard deviation 1 with centers at vertices of a regular polygon of side ss (in standard deviations). For each kk from 2 to 8, stability is calculated with RR replications and mean plotted with a one-standard-deviation band.

InteractiveStability curve
Stability (mean ARI between two bootstrap resamples) versus kk
K = 3
Replicate A: k-means with k=2k = 2 on a resample
Replicate B: k-means with k=2k = 2 on a resample
  • mean stability and ±1\pm 1 standard deviation band
  • kk with highest stability
  • true KK
True groups KK
4.0
20
2
kk with highest stability3
Stability at k=K=3k = K = 30.979
ARI of shown pair (k=2k = 2)0.118
Stability peaks at k=3k = 3 (0.98), the true number of groups. With kk smaller, k-means must merge groups and several merges are nearly as good, so it varies across replicates; with kk larger, it splits groups using arbitrary cuts.
Stability (mean ARI between two k-means models fitted to two bootstrap resamples) versus kk, with 50 points per cloud. Initially three groups form a triangle of side 4. The curve reaches 0.98 at k=3k = 3 and plunges at k=2k = 2 (0.25): going from 3 to 2 clusters forces two clouds to merge, and since all three are equivalent, each resample chooses a different pair. The two replications at right (k=2k = 2) are reasonable distinct partitions with ARI 0.12. Move 'Mark kk' to 3 and they are nearly identical (0.94). With four groups in a square of side 4 the maximum is at k=4k = 4 (0.97), with k=3k = 3 at 0.68 and k=2k = 2 at 0.56. Lower side ss: separation disappears and the peak flattens. With three groups and s=2s = 2, k=4k = 4 (0.66) already exceeds k=3k = 3 (0.64) and the curve no longer identifies the true count.

von Luxburg’s (2010) review explains this: with k-means and lots of data, stability mainly reflects whether the objective has a unique minimizer. With three symmetric clouds, k=2k = 2 has three equivalent solutions and is unstable; with four clouds in a square, k=2k = 2 has two (horizontal or vertical cut), and k=3k = 3 also leaves an arbitrary choice. Stability therefore measures fit between model and data: it signals correct kk when that kk gives a unique objective solution well separated from alternatives and other kk values do not, as with clear groups but not guaranteed (cloud symmetry, for example, depresses k=2k = 2 in the triangle). Know its limits:

  • It cannot say k=1k = 1: with one cluster the partition is trivially identical. Sometimes without structure a large kk is stable (seen in the benchmark).
  • It measures algorithm stability, not truth: a method biased toward grid partitions can be stable and wrong.
  • It requires extending partitions to new points (nearest center for k-means; other methods need a classifier trained on clusters or comparison on sample intersection).
  • It is costly: R×2R \times 2 fits per kk.

Consensus. The same idea pairwise yields Monti, Tamayo, Mesirov and Golub’s (2003) consensus clustering, common in genomics. Repeat clustering on HH subsamples (without replacement, e.g. 80%) and for each point pair (i,j)(i, j) calculate consensus index CijC_{ij}: the fraction of subsamples containing both in which they land in the same cluster. If the partition is reproducible, almost all CijC_{ij} are 0 or 1 and matrix CC reordered by clusters is block-diagonal. Şenbabaoğlu, Michailidis and Li (2014) propose summarizing it with proportion of ambiguous pairs, PAC(k)=#{i<j:u1<Cij<u2}/(n2)\mathrm{PAC}(k) = \#\{i < j : u_1 < C_{ij} < u_2\} / \binom n2 for an intermediate interval such as (0.1,0.9)(0.1, 0.9), choosing kk with lowest PAC. Their key warning: unimodal, groupless data yield apparently stable consensus partitions for several kk. The cell checks this with the benchmark’s three separated clouds and 150 uniform points.

[ ]Consensus matrix and proportion of ambiguous pairs (PAC)Browser
import numpy as np, warnings
from sklearn.cluster import KMeans
warnings.filterwarnings("ignore")

def consenso(X, k, H=20, frac=0.8, seed=0):
    """Índices de consenso C_ij (triángulo superior) de k-means sobre H submuestras sin reemplazo."""
    rng = np.random.default_rng(seed); n = len(X)
    juntos = np.zeros((n, n)); ambos = np.zeros((n, n))
    for h in range(H):
        idx = rng.choice(n, int(frac * n), replace=False)
        l = KMeans(k, n_init=1, random_state=h).fit_predict(X[idx])
        ambos[np.ix_(idx, idx)] += 1                              # submuestras que contienen a i y a j
        juntos[np.ix_(idx, idx)] += l[:, None] == l[None, :]      # ... y en las que caen juntos
    return (juntos / np.maximum(ambos, 1))[np.triu_indices(n, 1)]

def pac(c, u1=0.1, u2=0.9):
    return np.mean((c > u1) & (c < u2))

r = np.random.default_rng(1)
tres = np.vstack([r.normal(c, 1, (50, 2)) for c in [(0, 0), (6, 0), (13, 0)]])
unif = np.random.default_rng(5).uniform(size=(150, 2))
for nombre, X in [("3 nubes separadas", tres), ("uniforme", unif)]:
    print(f"{nombre:18s}", "  ".join(f"k={k}: PAC {pac(consenso(X, k)):.3f}" for k in range(2, 7)))

With three clouds, PAC is exactly 0 at k=3k = 3 (every pair always together or always apart) and rises to 0.155 as soon as a cloud splits. With uniform points, PAC for k=3k = 3 is 0.093: over 90% of pairs have clear consensus on data without groups, and the criterion would choose k=3k = 3 with the same apparent confidence the benchmark below finds when stability selects k=3k = 3 on that dataset. This is Şenbabaoğlu and colleagues’ phenomenon: k-means cuts a uniform square reproducibly, and reproducibility cannot distinguish a reproducible cut from a real group. Consensus inherits stability’s limits, so its matrix CC (often drawn as a heatmap) is an excellent visualization tool, not proof of groups.

Lab: a benchmark of criteria

Implement gap and stability and compare them with elbow, silhouette and Gaussian-mixture BIC on five datasets with known kk, including one without structure. Automate “elbow” with the commonest rule: kk maximizing the ratio of WW‘s drop on reaching kk to its drop moving to k+1k+1.

[ ]Gap and stability from scratch, and the criteria benchmarkBrowser
import numpy as np, warnings
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score, adjusted_rand_score as ARI
warnings.filterwarnings("ignore")

def inercia(X, k, seed=0):
    return KMeans(k, n_init=2, random_state=seed).fit(X).inertia_

def gap_statistic(X, k_max=8, B=8, seed=0):
    """Tibshirani, Walther y Hastie (2001): referencia uniforme en la caja envolvente, regla de una desviación típica."""
    rng = np.random.default_rng(seed)
    lo, hi = X.min(0), X.max(0)
    logW = np.array([np.log(inercia(X, k, seed)) for k in range(1, k_max + 1)])
    ref = np.array([[np.log(inercia(rng.uniform(lo, hi, X.shape), k, seed)) for k in range(1, k_max + 1)] for _ in range(B)])
    gap = ref.mean(0) - logW
    s = ref.std(0) * np.sqrt(1 + 1 / B)
    for k in range(1, k_max):
        if gap[k - 1] >= gap[k] - s[k]:           # gap[k-1] es Gap(k)
            return k, gap, s
    return k_max, gap, s

def estabilidad(X, k, R=6, seed=0):
    """ARI medio entre pares de k-means ajustados a remuestreos bootstrap, comparados sobre todos los puntos."""
    rng = np.random.default_rng(seed); n = len(X); aris = []
    for _ in range(R):
        etiquetas = []
        for _ in range(2):
            idx = rng.integers(0, n, n)
            etiquetas.append(KMeans(k, n_init=2, random_state=int(rng.integers(1 << 30))).fit(X[idx]).predict(X))
        aris.append(ARI(*etiquetas))
    return np.mean(aris)

def nubes(centros, n_por, seed):
    r = np.random.default_rng(seed)
    return np.vstack([r.normal(c, 1, (m, 2)) for c, m in zip(centros, n_por)])

conjuntos = {
    "3 nubes separadas": (nubes([(0, 0), (6, 0), (13, 0)], [50] * 3, 1), 3),
    "4 nubes en cuadrado": (nubes([(0, 0), (6, 0), (0, 6), (6, 6)], [40] * 4, 2), 4),
    "3 nubes solapadas": (nubes([(0, 0), (3, 0), (1.5, 2.6)], [50] * 3, 3), 3),
    "2 nubes, 135 y 15": (nubes([(0, 0), (5, 0)], [135, 15], 4), 2),
    "uniforme": (np.random.default_rng(5).uniform(size=(150, 2)), 1),
}
KM = 8
tabla = {}

def evaluar(nombre):
    X, kt = conjuntos[nombre]
    W = np.array([inercia(X, k) for k in range(1, KM + 1)])
    caidas = W[:-1] - W[1:]
    codo = 2 + int(np.argmax(caidas[:-1] / caidas[1:]))
    sil = 2 + int(np.argmax([silhouette_score(X, KMeans(k, n_init=2, random_state=0).fit_predict(X)) for k in range(2, KM + 1)]))
    bic = 1 + int(np.argmin([GaussianMixture(k, random_state=0).fit(X).bic(X) for k in range(1, KM + 1)]))
    gk, g, s = gap_statistic(X, KM)
    st = [estabilidad(X, k) for k in range(2, KM + 1)]
    tabla[nombre] = (kt, codo, sil, bic, gk, 2 + int(np.argmax(st)), g, st)

Each dataset calculation takes a few seconds in the browser (dozens of k-means and mixture fits), so it is split across cells.

[ ]Criteria benchmark: three separated clouds and four in a squareBrowser
evaluar("3 nubes separadas")
evaluar("4 nubes en cuadrado")
print({k: v[:6] for k, v in tabla.items()})
[ ]Criteria benchmark: overlapping clouds and unequal sizesBrowser
evaluar("3 nubes solapadas")
evaluar("2 nubes, 135 y 15")
print({k: v[:6] for k, v in tabla.items() if k in ("3 nubes solapadas", "2 nubes, 135 y 15")})
[ ]Criteria benchmark: no structure and the tableBrowser
evaluar("uniforme")
print(f"{'conjunto':22s} k real  codo  silh.  BIC   gap  estab.")
for nombre, (kt, codo, sil, bic, gk, est, g, st) in tabla.items():
    print(f"{nombre:22s} {kt:5d} {codo:5d} {sil:5d} {bic:5d} {gk:5d} {est:6d}")
print("estabilidad del conjunto uniforme para k = 2..8:", np.round(tabla["uniforme"][7], 2))
print("Gap(k) del conjunto uniforme para k = 1..8:", np.round(tabla["uniforme"][6], 2))
print("Gap(k) de las tres nubes solapadas para k = 1..8:", np.round(tabla["3 nubes solapadas"][6], 2))

Five datasets and five criteria give 25 decisions; the pattern matters, not a scoreboard:

  • When structure is clear, all five criteria agree: on three separated clouds and four clouds in a square, all return true kk (3 and 4). Choosing kk is not the hard problem when groups are compact and far apart.
  • Overlapping or very unequal groups reveal differences. On three overlapping clouds, elbow, silhouette and stability give 3, but BIC and gap give 1; on two clouds of 135 and 15 points, gap again gives 1 and others 2. Gap’s failure on overlapping clouds is familiar: centers form an equilateral triangle of side 3, the interactive configuration, and the cell’s last line repeats what you saw there, Gap(1)=0.72\mathrm{Gap}(1) = 0.72 above Gap(2)=0.63\mathrm{Gap}(2) = 0.63 (the rule stops at k=1k = 1 without looking at error bars) and a global maximum at k=3k = 3 of only 0.74. With the small 15-point cloud (10% of data), gap is conservative: the rule gives 1 because improvement from Gap(1)\mathrm{Gap}(1) to Gap(2)\mathrm{Gap}(2) does not exceed one reference standard error.
  • Without structure, only gap says k=1k = 1. Elbow, silhouette, BIC and stability return 3 for 150 uniform points in a square. Stability of k=3k = 3 is 0.88, and BIC accepts a three-Gaussian mixture because a square is not a Gaussian: BIC compares against one Gaussian model, not absence of structure. Gap instead has Gap(k)\mathrm{Gap}(k) between −0.16-0.16 and 0.080.08 for every kk.

Two cautions. Each row comes from one sample per dataset, with 8 gap references and 6 resample pairs for stability, so this illustrates rather than reliably compares criteria; that would require many samples and configurations. And all criteria use k-means (BIC uses Gaussian mixtures): on moons or rings they would fail together for the first section’s reason.

Kleinberg’s impossibility theorem

Everything above comprises debatable quality criteria. Kleinberg (2002) asked the fundamental question: is there a clustering algorithm satisfying reasonable properties everyone would want? His answer is no, with a short proof.

Each is reasonable. Changing units (meters to kilometers) should not change groups; we do not want to rule out any grouping in advance; and if found clusters become more compact and farther apart, they should remain the answer.

The proof has two steps. First, scale invariance and consistency alone force the range of ff not to contain two partitions comparable by refinement; second, richness contradicts this. (Partition Γ0\Gamma_0 refines Γ1\Gamma_1 if each Γ0\Gamma_0 cluster is contained in a Γ1\Gamma_1 cluster.)

Proof

Step 1. Suppose ff satisfies scale invariance and consistency and d0,d1d_0, d_1 exist with Γ0=f(d0)\Gamma_0 = f(d_0) and Γ1=f(d1)\Gamma_1 = f(d_1), with Γ0≠Γ1\Gamma_0 \ne \Gamma_1 and Γ0\Gamma_0 a refinement of Γ1\Gamma_1. Let a0=min⁡i≠jd0(i,j)a_0 = \min_{i \ne j} d_0(i, j), b0=max⁡i≠jd0(i,j)b_0 = \max_{i \ne j} d_0(i, j) and a1=min⁡i≠jd1(i,j)a_1 = \min_{i \ne j} d_1(i, j); all are positive. Set α=b0/a1\alpha = b_0 / a_1 and define d2d_2:

  • if i,ji, j are in the same cluster of Γ0\Gamma_0: d2(i,j)=a0d_2(i, j) = a_0;
  • if in different Γ0\Gamma_0 clusters but the same Γ1\Gamma_1 cluster: d2(i,j)=d0(i,j)d_2(i, j) = d_0(i, j);
  • if in different Γ1\Gamma_1 clusters (and hence different Γ0\Gamma_0 clusters): d2(i,j)=α d1(i,j)d_2(i, j) = \alpha\, d_1(i, j).

d2d_2 is a Γ0\Gamma_0-transformation of d0d_0: within Γ0\Gamma_0 clusters it changes from d0(i,j)≥a0d_0(i, j) \ge a_0 to a0a_0 (does not increase); between Γ0\Gamma_0 clusters it is d0d_0 or αd1(i,j)≥αa1=b0≥d0(i,j)\alpha d_1(i, j) \ge \alpha a_1 = b_0 \ge d_0(i, j) (does not decrease). By consistency, f(d2)=Γ0f(d_2) = \Gamma_0.

But d2d_2 is also a Γ1\Gamma_1-transformation of αd1\alpha d_1: within Γ1\Gamma_1 clusters, d2d_2 is a0≤b0=αa1≤αd1(i,j)a_0 \le b_0 = \alpha a_1 \le \alpha d_1(i, j) or d0(i,j)≤b0≤αd1(i,j)d_0(i, j) \le b_0 \le \alpha d_1(i, j) (does not increase); between Γ1\Gamma_1 clusters it is exactly αd1\alpha d_1. By consistency, f(d2)=f(αd1)f(d_2) = f(\alpha d_1), which by scale invariance is f(d1)=Γ1f(d_1) = \Gamma_1. Hence Γ0=f(d2)=Γ1\Gamma_0 = f(d_2) = \Gamma_1, a contradiction.

Step 2. If ff were also rich, its range would contain the singleton partition, strictly refining the one-cluster partition (distinct because n≥2n \ge 2), contradicting step 1.

∎

What is striking is how little the proof uses: consistency permits constructing a distance d2d_2 simultaneously claimed by two different partitions. The conclusion does not say clustering is impossible; every algorithm gives something up, and you must know what. Kleinberg illustrates with single linkage (whose minimum-spanning-tree connection you know) using three stopping rules, each satisfying two axioms and violating the third:

  • Stop at kk clusters satisfies scale invariance and consistency, but not richness: it always returns exactly kk clusters. (You prove this in an exercise.)
  • Stop when a merge exceeds fixed distance rr satisfies richness and consistency, but not scale invariance: change units and rr no longer means the same.
  • Stop when a merge exceeds fraction α\alpha of maximum distance satisfies scale invariance and richness, but not consistency: moving a cluster farther away raises maximum distance and threshold, merging clusters that were untouched.

The interactive has ten points and the three rules. Right are single-linkage merge heights (log scale) and each rule’s threshold: the line’s position changes across rules.

InteractiveKleinberg's three axioms
Points after transformation (hollow: original position)
ABC
Single-linkage merge heights (logarithmic scale) and stopping rule
stop: αD = 1.71
Scale invariance: satisfies it
 
Richness: satisfies it
With an appropriate distance any partition can occur.
Consistency: does not satisfy it
Valid transformation, but the partition changes from 3 to 2 clusters.
  • accepted merge (height below threshold)
  • rejected merge
  • stopping-rule threshold
Single-linkage stopping rule
0.12
Transformation
0.00
Cluster moved away
3.50
Clusters in base partition3
Clusters after transformation2
Maximum distance DD14.27
Is this a Γ\Gamma-transformation?yes
With a fraction α\alpha of maximum distance, single linkage is scale invariant and rich but not consistent: moving a cluster away increases DD, raises αD\alpha D, and merges untouched clusters.
Ten points: nearby groups AA and BB and distant group CC. Initially: fraction rule α=0.12\alpha = 0.12, 'consistency' mode, with CC moved u=3.5u = 3.5 units away. Without transformation, the partition has 3 clusters (D=10.77D = 10.77 and threshold αD=1.29\alpha D = 1.29, below height 1.68 at which AA and BB would join). Moving CC away is a valid Γ\Gamma-transformation (the cluster moves in a direction shortening no distance to the other two), but maximum distance grows, threshold αD\alpha D rises, and from u=3.25u = 3.25 height 1.68 falls below it: the partition changes from 3 to 2 clusters. Lower uu to see it. Switch to 'kk clusters' or 'distance rr' and repeat: the partition stays unchanged. In 'scale' mode the fixed-distance rule rr breaks as soon as distances are multiplied by 0.5 (3 to 2 clusters) or 2 (to 10 clusters), while the other rules are unaffected.

These properties, with qualifications, can be checked by simulation on many random configurations using SciPy single linkage (fcluster with maxclust or distance criteria). In each, compare the partition with the result after multiplying distances by a random factor and after a random Γ\Gamma-transformation (within-cluster distances multiplied by a factor at most 1 and between-cluster distances by one at least 1). Distances generated by Γ\Gamma-transformations need not be Euclidean, consistent with Kleinberg’s definition.

[ ]Three single-linkage rules under scale and consistencyBrowser
import numpy as np
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial.distance import squareform
from sklearn.metrics import adjusted_rand_score as ARI

rng = np.random.default_rng(0)

def enlace_simple(D, regla, par):
    Z = linkage(squareform(D, checks=False), "single")
    if regla == "k":     return fcluster(Z, par, "maxclust")
    if regla == "r":     return fcluster(Z, par, "distance")
    return fcluster(Z, par * D.max(), "distance")          # regla alfa: fracción de la mayor distancia

def gamma_transforma(D, l):
    """Una Γ-transformación al azar: reduce las distancias dentro de cada cluster y aumenta las de fuera."""
    mismo = l[:, None] == l[None, :]
    F = np.triu(np.where(mismo, rng.uniform(0.2, 1, D.shape), rng.uniform(1, 4, D.shape)), 1)
    F = F + F.T
    D2 = D * F
    np.fill_diagonal(D2, 0)
    return D2

pars = {"k": 3, "r": 0.9, "alpha": 0.25}
cambios = {(reg, ax): 0 for reg in pars for ax in ("escala", "consistencia")}
ensayos = 300
for _ in range(ensayos):
    P = np.vstack([rng.normal(c, 0.5, (4, 2)) for c in ((0, 0), (3, 0), (1.5, 4))])
    D = np.linalg.norm(P[:, None] - P[None], axis=2)
    for reg, par in pars.items():
        l = enlace_simple(D, reg, par)
        s = rng.uniform(0.2, 5)
        cambios[(reg, "escala")] += ARI(l, enlace_simple(s * D, reg, par)) != 1.0
        cambios[(reg, "consistencia")] += ARI(l, enlace_simple(gamma_transforma(D, l), reg, par)) != 1.0
print(f"{ensayos} configuraciones al azar de 12 puntos; veces que la partición cambia")
for reg in pars:
    print(f"  regla {reg:5s}: escala {cambios[(reg, 'escala')]:3d}   consistencia {cambios[(reg, 'consistencia')]:3d}")

For all three rules the table matches analysis: the kk rule never fails either test, fixed distance rr fails scale (in 278 of 300 configurations; in others the scale factor crosses no merge height), and fraction α\alpha fails consistency (291 of 300), while theoretically safe cells remain 0. Simulation does not prove anything: the proof above and exercise do; simulation confirms the implementation behaves as theory predicts.

What to do with an impossibility result

  • Choose the axiom you sacrifice. Fixing kk gives up richness (k-means, spectral clustering with fixed kk, cutting a dendrogram to kk); fixing a scale rr (such as DBSCAN’s ε\varepsilon) gives up scale invariance. A method asking for no parameter makes that decision for you.
  • Consistency is the most debatable axiom. Moving clusters apart and compacting them need not preserve the partition for every method: center-based methods do not satisfy it (Kleinberg’s theorem 4.1 proves that for every k≥2k \ge 2 and sufficiently large nn, kk-median and kk-means functions in his formalism with centers chosen among points are inconsistent; Cohen-Addad, Kanade and Mallmann-Trenn, 2018, show k-means violates it even on well-clusterable data). Alternatives replace it with weaker versions, such as Strazzeri and Sánchez-García’s monotonic consistency (arXiv:1806.06142). Restricting functions to fixed-kk partitions also allows axioms to coexist, as Zadeh and Ben-David (2009) study.
  • Always evaluate against a purpose. The theorem formalizes the motivating question: no “best” partition exists without specifying best for what. Silhouette answers “compact clusters”; ARI, “what this label says”; stability, “what does not depend on the sample.”

An honest evaluation protocol

These are the most common failures and how to avoid them.

  1. Separate exploration and confirmation. Make every data-informed choice (algorithm, kk, hyperparameters, preprocessing) on one part and measure on another untouched part. If labels inform any decision, the result is no longer “unsupervised.”
  2. Do not select using labels. Choosing the configuration with highest ARI on labels and presenting that ARI inflates results even without real structure. The next experiment measures this.
  3. Report sensitivity, not one number. Seeds, hyperparameters, subsamples: report the index distribution, not the best case. If the result changes with seed, it is not robust.
  4. Compare with a structureless reference (gap’s reference) and a baseline. Silhouette 0.4 means nothing without knowing what uniform data obtain.
  5. Evaluate in the clustering space. Do not calculate indices on a 2D embedding created for visualization.
  6. Decide what “good” means before looking, and state it: compactness, agreement with annotation, stability, downstream usefulness. The last matters most in practice: clustering is also evaluated by what it enables.

The next experiment illustrates point 2. Structureless data (60 Gaussian points) and random labels (3 classes): nothing to find. Test 35 configurations (k-means with kk from 2 to 6 and six seeds, plus Ward with kk from 2 to 6) on half the data and choose highest ARI against labels. Then apply that same configuration to the other half.

[ ]Choosing using labels inflates results: 12 structureless datasetsBrowser
import numpy as np, warnings
from sklearn.cluster import KMeans, AgglomerativeClustering
from sklearn.metrics import adjusted_rand_score as ARI
warnings.filterwarnings("ignore")

rng = np.random.default_rng(0)
configs = [("kmeans", k, s) for k in (2, 3, 4, 5, 6) for s in range(6)] + [("ward", k, 0) for k in (2, 3, 4, 5, 6)]

def ajusta(X, alg, k, s):
    if alg == "kmeans":
        return KMeans(k, n_init=1, random_state=s).fit_predict(X)
    return AgglomerativeClustering(k, linkage="ward").fit_predict(X)

optimo, fuera = [], []
for rep in range(12):
    X = rng.normal(size=(60, 2)); y = rng.integers(0, 3, 60)        # datos SIN estructura y etiquetas al azar
    dev, test = slice(0, 30), slice(30, 60)
    puntuaciones = [ARI(y[dev], ajusta(X[dev], *c)) for c in configs]
    mejor = configs[int(np.argmax(puntuaciones))]                   # configuración elegida MIRANDO las etiquetas
    optimo.append(max(puntuaciones))
    fuera.append(ARI(y[test], ajusta(X[test], *mejor)))             # la misma configuración sobre datos nuevos
print(f"{len(configs)} configuraciones, {len(optimo)} conjuntos sin estructura")
print(f"ARI de la mejor configuración, sobre los datos con los que se eligió: {np.mean(optimo):.3f}")
print(f"ARI de esa misma configuración sobre datos que no intervinieron:     {np.mean(fuera):.3f}")

On average, the best of 35 configurations obtains ARI 0.073 against the labels used to select it, though data are noise and labels random; the same configuration on the other half obtains 0.002. The 0.073 is not a large number, and that is the trap: with real data containing some signal, inflation of that magnitude is confused with it. The more configurations tried and less data available, the higher maximum ARI grows with nothing to find.

Exercises

NumericARI of two six-element partitions
Two partitions UU and VV of 6 elements have a contingency table with rows U1,U2U_1, U_2 and columns V1,V2,V3V_1, V_2, V_3: row 1 is (2,1,0)(2, 1, 0) and row 2 is (0,1,2)(0, 1, 2). What is ARI?
NumericSilhouette of a point on a line
On a line are three clusters: A={0,1,2}A = \{0, 1, 2\}, B={5,7}B = \{5, 7\} and C={9,10,12}C = \{9, 10, 12\}, with distance ∣x−y∣\abs{x - y}. What is silhouette s(i)s(i) of point i=2i = 2 in AA?
NumericCalinski–Harabasz from $B$ and $W$
A partition of n=63n = 63 points into k=3k = 3 clusters has between-cluster dispersion B=240B = 240 and within-cluster dispersion W=120W = 120. What is the Calinski–Harabasz index?
NumericExpected matching pairs by chance
Partition UU of 20 points has two clusters of 10 and VV has four clusters of 5. If you randomly permute VV labels, how many pairs do you expect to be together in both UU and VV, E[N11]\E[N_{11}]?
NumericApplying the one-standard-deviation rule
Gap statistics and errors for k=1,…,6k = 1, \dots, 6 are Gap=(0.10,0.45,0.62,0.78,0.80,0.71)\mathrm{Gap} = (0.10, 0.45, 0.62, 0.78, 0.80, 0.71) and s=(0.05,0.06,0.07,0.05,0.06,0.06)s = (0.05, 0.06, 0.07, 0.05, 0.06, 0.06). What k^\hat k does rule k^=min⁡{k:Gap(k)≥Gap(k+1)−sk+1}\hat k = \min\{k : \mathrm{Gap}(k) \ge \mathrm{Gap}(k+1) - s_{k+1}\} choose?
ProofSingle linkage stopped at $k$ clusters: scale and consistency, not richness
Prove: Let fkf_k map a distance function dd on n>k≥2n > k \ge 2 points to the partition produced by single linkage (Kruskal's algorithm on edges ordered ascending by (d,ıˊndices)(d, \text{índices}), merging components) when exactly kk clusters remain. Prove it satisfies scale invariance and consistency, but not richness.
0
Order all pairs by key (d(i,j),ıˊndice del par)(d(i,j), \text{índice del par}): index tie-breaking makes fkf_k well defined even with ties. Kruskal scans pairs in that order, accepting those joining distinct components, and stops at kk components.

Step 1 of 4. Why is fk(αd)=fk(d)f_k(\alpha d) = f_k(d) for α>0\alpha > 0?

ProofExpected $N_{11}$ and ARI chance correction
Prove: With UU fixed and VV labels uniformly permuted, prove E[N11]=AB/(n2)\E[N_{11}] = AB/\binom n2, and explain why ARI defined with that expectation averages 0 for independent partitions and is 1 only when identical (up to renaming).
0
Write N11N_{11} as a sum of indicators over the AA together pairs in UU and use linearity of expectation.

Step 1 of 3. How do you express N11N_{11} as a sum of indicators?

QuizWhy NMI favors many clusters
Against the same 4-class truth, you compare a 5-cluster and a 50-cluster partition, both randomly generated without any relation to truth. The latter has much higher NMI. Why?
QuizWhich protocol leaks labels?
You want to compare three clustering algorithms on labeled data and present an unsupervised evaluation. Which protocol leaks label information into fitting?
QuizWhich criteria can say 'no groups'?
Your data have no group structure. Which kk-selection criteria can by construction return k=1k = 1?
QuizSilhouette and DBSCAN noise
You run DBSCAN on two dense regions with scattered points between them. It returns 2 clusters and label −1-1 for 12% of points. You want silhouette to compare it with k-means at k=2k = 2. What do you do?
QuizWhich axiom does each practice sacrifice?
A colleague says: 'I use k-means with fixed k=8k = 8. Since single linkage stopped at kk satisfies scale invariance and consistency, my method does too: I give up only richness, the minimum Kleinberg's theorem requires.' What is correct?
CodeGap statistic with principal-component-aligned reference
The criteria benchmark uses Tibshirani, Walther and Hastie's first reference: uniform in the axis-aligned bounding box. If data are rotated, that box has empty corners and the reference no longer resembles data. Implement the second. First referencia_pca(X, rng): center X on its mean, obtain principal directions with SVD of centered data, project data onto them, generate uniform points in the projections' bounding box (a sample shaped like X), and return them to original coordinates (undo rotation and add the mean). Then gap_statistic(X, k_max, B, seed=0), returning integer k^\hat k of the one-standard-deviation rule with BB samples from referencia_pca (use one rng = np.random.default_rng(seed)), KMeans(k, n_init=2, random_state=seed) for WkW_k (inertia_), sk=sdk1+1/Bs_k = \mathrm{sd}_k\sqrt{1 + 1/B} with population standard deviation (np.std default), and the smallest k∈{1,…,kmax⁡−1}k \in \{1, \dots, k_{\max} - 1\} with Gap(k)≥Gap(k+1)−sk+1\mathrm{Gap}(k) \ge \mathrm{Gap}(k+1) - s_{k+1} (or kmax⁡k_{\max} if none). Tests check reference shape on diagonally aligned data and k^\hat k on rotated data with known kk and without structure.
import numpy as np
from sklearn.cluster import KMeans

def referencia_pca(X, rng):
  """Una muestra uniforme en la caja envolvente de X en la base de sus componentes principales."""
  X = np.asarray(X, dtype=float)
  lo, hi = X.min(0), X.max(0)
  return rng.uniform(lo, hi, X.shape)        # esto es la caja de los ejes: cámbialo

def gap_statistic(X, k_max, B, seed=0):
  """k elegido por la regla de una desviación típica, con la referencia de referencia_pca."""
  X = np.asarray(X, dtype=float)
  rng = np.random.default_rng(seed)
  # tu código: log W_k de los datos y de B referencias, gap, s_k y la regla
  return 1
Shift+Enter to run

Summary

Key idea
No single correct partition exists without saying correct for what. Internal indices (silhouette, Davies–Bouldin, Calinski–Harabasz) measure compactness and separation and reward convex clusters; external indices (ARI, AMI) compare with a reference and should correct for chance; choosing kk requires comparison with a structureless reference (gap) or reproducibility (stability); and Kleinberg’s theorem says no algorithm simultaneously satisfies scale invariance, richness and consistency. Evaluate using a protocol separating exploration and confirmation.
  • Silhouette: s(i)=(b−a)/max⁡{a,b}∈[−1,1]s(i) = (b - a)/\max\{a, b\} \in [-1, 1]. Davies–Bouldin is minimized and Calinski–Harabasz maximized, with T=B+WT = B + W. All three score compactness, not desired shape, and cannot say k=1k = 1: on moons, successful DBSCAN scores worse than k-means splitting them.
  • Rand index rises with cluster count without information. ARI =(N11−E[N11])/(12(A+B)−E[N11])= (N_{11} - \E[N_{11}])/(\frac12(A+B) - \E[N_{11}]) with E[N11]=AB/(n2)\E[N_{11}] = AB/\binom n2 under permutations; arithmetic NMI is V-measure and has positive bias ≈(r−1)(s−1)/2n\approx (r-1)(s-1)/2n nats; AMI subtracts exact hypergeometric expected mutual information. Use ARI for balanced references, AMI for small clusters.
  • Gap: Gap(k)=E∗[log⁡Wk]−log⁡Wk\mathrm{Gap}(k) = \E^*[\log W_k] - \log W_k and the one-standard-deviation rule, which can undershoot with hierarchical or symmetric structure (plot the full gap). Stability: ARI across resamples; reflects minimizer uniqueness and cannot say k=1k = 1. Consensus (matrix CijC_{ij} and PAC) is its pairwise version with the same limits: a uniform square gives “stable” k=3k = 3.
  • Kleinberg: scale invariance and consistency make the range an antichain under refinement, contradicted by richness. Single linkage stopped at kk, rr or fraction α\alpha of maximum distance sacrifices richness, scale and consistency respectively.
  • Protocol: separate exploration and confirmation, do not select with labels, report sensitivity, compare with a structureless reference, evaluate in original space, and state beforehand what “good” means.