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).
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 : elbow, information criteria, gap statistic and resampling stability. They compare solutions from one method at different .
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 points be partitioned into clusters with dissimilarity . For point in cluster with , measure two mean distances: to other points in its cluster and to points in its nearest other cluster.
Since , and hence . An near 1 means the point is much closer to its cluster than the neighboring one; means it lies on a boundary; means it is on average closer to another cluster. As a distance ratio, is unchanged by multiplying all distances by a positive constant. Rousseeuw plotted 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 cuts each moon in half, and silhouette rewards it; the true partition scores much lower. One point is fixed to show where and come from; hover over others.
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 even when perfectly coherent.
Davies–Bouldin and Calinski–Harabasz
The other two classical indices use cluster centroids instead of point-to-point distances, so are defined only for data with a mean (typically vectors in with Euclidean distance).
is exactly k-means inertia. Its connection to is a variance decomposition.
Proof
For , write and expand the square. Summing over , the cross term is , since is the mean of . This leaves , and summing over gives .
∎Since does not depend on the partition, minimizing (k-means) maximizes , and is the ratio of two mean squares forming the one-way ANOVA statistic. One important caveat: clusters here were chosen by looking at data, so the statistic does not follow an distribution and has no honest p-value. It only compares partitions. Moreover, is undefined for , as are 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 and .
- With noise marked as another cluster (as DBSCAN does with label ), 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 .
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 holds to the cent. Now the promised warning: what silhouette does k-means obtain on entirely structureless data?
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 (class labels, expert annotations, synthetic-data truth), compare yours, , 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 (inclusion–exclusion over pairs together in or ). 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 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 and ) and distribute the rest randomly, uniformly permuting labels while keeping fixed. Under that model expected is simple.
Proof
counts pairs together in that are also together in after permutation: . There are terms. For a fixed one, corresponds under uniform permutation to a uniform pair of distinct elements, together with probability (there are together pairs among possible pairs). Linearity of expectation gives .
∎The denominator uses the possible maximum of under Hubert and Arabie’s convention: , using the mean as a bound. ARI 0 means resembles 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 and .
Mutual information, NMI, V-measure and AMI
The other family measures how much knowing the cluster reduces uncertainty about the cluster. With Shannon entropies (and analogously ), and mutual information
normalize to . Since , any mean of the entropies can normalize; the arithmetic choice gives
scikit-learn’s default (other variants use geometric mean, maximum or minimum). Rosenberg and Hirschberg’s V-measure is the harmonic mean of homogeneity (each cluster contains elements of one class only) and completeness (each class lies in one cluster). Since , we obtain , and
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 table with elements is positive even when and are independent: the independence likelihood-ratio statistic follows, for large relative to cell count, a with degrees of freedom, so nats, growing with cluster count. NMI rises with because its numerator rises with . Vinh, Epps and Bailey (2010) correct this with the same trick as ARI.
The right-hand factor is the hypergeometric probability that cell contains elements: select elements of among and require to fall in . Computing takes 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 balanced classes and compares random partitions of clusters. Start with (no shared information) and see which index remains near 0 as grows.
The model is explicit: truth has classes of points, and a partition into clusters gives each point, with probability , a cluster compatible with its class (if , class modulo ; if , a randomly chosen subcluster of its class) and otherwise a uniform one in . Thirty partitions are averaged for each .
Now the lab: contingency table, Rand, ARI, NMI and AMI from scratch (with by the hypergeometric formula), compared with scikit-learn; the identity V-measure NMI; and a simulation check of the expectation theorem.
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 table there is “noise” mutual information. Now the interactive’s experiment in numbers: random partitions of points against truth with 4 classes of 25.
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 : they agree at small (0.015 and 0.015 with ) and diverge when there are few points per cell (0.347 versus 0.285 at ). Do not be fooled by , where they look similar again (0.724 versus 0.735): the curves cross. The approximation grows linearly without bound with , while exact expectation is bounded because nats for 4 balanced classes; at the approximation would give , impossible. Approximation needs many points per cell (here with 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 (or a substitute: , bandwidth, cut height). This section’s criteria compare solutions from one method with different and select the best by some criterion.
The elbow. , minimum inertia with clusters, does not increase with (a cluster in a -partition can always be split without increasing ), so it cannot simply be minimized. Convention plots 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 , Zador’s theorem (lesson 2) says for large , , a smooth convex curve with no privileged point, yet the eye finds an “elbow.”
Information criteria. If a Gaussian mixture is fitted, BIC penalizes likelihood by parameter count and has a minimum at finite . 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 and take the maximum (minimum for Davies–Bouldin). They inherit all previous geometric biases, and all require .
The gap statistic
Gap supplies the missing idea: compare not with other values but with what would be if data had no structure. First, write 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 adds error from approximating the reference mean with samples to reference deviation. The rule seeks the first such that increasing to improves gap by no more than one standard error: improvement is attributed to reference-sample noise.
A direct consequence: gap can say , while silhouette, DB and CH cannot. With a uniform cloud, and its reference fall alike, gap fluctuates around 0 and the rule stops at the first .
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.
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 before reading one number.
Stability
Another way to choose examines not partition geometry but reproducibility: if data sample a population with groups, two different samples should yield similar partitions at the correct . With excessive , 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 clouds of standard deviation 1 with centers at vertices of a regular polygon of side (in standard deviations). For each from 2 to 8, stability is calculated with replications and mean plotted with a one-standard-deviation band.
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, has three equivalent solutions and is unstable; with four clouds in a square, has two (horizontal or vertical cut), and also leaves an arbitrary choice. Stability therefore measures fit between model and data: it signals correct when that gives a unique objective solution well separated from alternatives and other values do not, as with clear groups but not guaranteed (cloud symmetry, for example, depresses in the triangle). Know its limits:
- It cannot say : with one cluster the partition is trivially identical. Sometimes without structure a large 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: fits per .
Consensus. The same idea pairwise yields Monti, Tamayo, Mesirov and Golub’s (2003) consensus clustering, common in genomics. Repeat clustering on subsamples (without replacement, e.g. 80%) and for each point pair calculate consensus index : the fraction of subsamples containing both in which they land in the same cluster. If the partition is reproducible, almost all are 0 or 1 and matrix reordered by clusters is block-diagonal. Şenbabaoğlu, Michailidis and Li (2014) propose summarizing it with proportion of ambiguous pairs, for an intermediate interval such as , choosing with lowest PAC. Their key warning: unimodal, groupless data yield apparently stable consensus partitions for several . The cell checks this with the benchmark’s three separated clouds and 150 uniform points.
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 (every pair always together or always apart) and rises to 0.155 as soon as a cloud splits. With uniform points, PAC for is 0.093: over 90% of pairs have clear consensus on data without groups, and the criterion would choose with the same apparent confidence the benchmark below finds when stability selects 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 (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 , including one without structure. Automate “elbow” with the commonest rule: maximizing the ratio of ‘s drop on reaching to its drop moving to .
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.
evaluar("3 nubes separadas")
evaluar("4 nubes en cuadrado")
print({k: v[:6] for k, v in tabla.items()})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")})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 (3 and 4). Choosing 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, above (the rule stops at without looking at error bars) and a global maximum at of only 0.74. With the small 15-point cloud (10% of data), gap is conservative: the rule gives 1 because improvement from to does not exceed one reference standard error.
- Without structure, only gap says . Elbow, silhouette, BIC and stability return 3 for 150 uniform points in a square. Stability of 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 between and for every .
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 not to contain two partitions comparable by refinement; second, richness contradicts this. (Partition refines if each cluster is contained in a cluster.)
Proof
Step 1. Suppose satisfies scale invariance and consistency and exist with and , with and a refinement of . Let , and ; all are positive. Set and define :
- if are in the same cluster of : ;
- if in different clusters but the same cluster: ;
- if in different clusters (and hence different clusters): .
is a -transformation of : within clusters it changes from to (does not increase); between clusters it is or (does not decrease). By consistency, .
But is also a -transformation of : within clusters, is or (does not increase); between clusters it is exactly . By consistency, , which by scale invariance is . Hence , a contradiction.
Step 2. If were also rich, its range would contain the singleton partition, strictly refining the one-cluster partition (distinct because ), contradicting step 1.
∎What is striking is how little the proof uses: consistency permits constructing a distance 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 clusters satisfies scale invariance and consistency, but not richness: it always returns exactly clusters. (You prove this in an exercise.)
- Stop when a merge exceeds fixed distance satisfies richness and consistency, but not scale invariance: change units and no longer means the same.
- Stop when a merge exceeds fraction 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.
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 -transformation (within-cluster distances multiplied by a factor at most 1 and between-cluster distances by one at least 1). Distances generated by -transformations need not be Euclidean, consistent with Kleinberg’s definition.
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 rule never fails either test, fixed distance fails scale (in 278 of 300 configurations; in others the scale factor crosses no merge height), and fraction 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 gives up richness (k-means, spectral clustering with fixed , cutting a dendrogram to ); fixing a scale (such as DBSCAN’s ) 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 and sufficiently large , -median and -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- 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.
- Separate exploration and confirmation. Make every data-informed choice (algorithm, , hyperparameters, preprocessing) on one part and measure on another untouched part. If labels inform any decision, the result is no longer “unsupervised.”
- 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.
- 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.
- Compare with a structureless reference (gap’s reference) and a baseline. Silhouette 0.4 means nothing without knowing what uniform data obtain.
- Evaluate in the clustering space. Do not calculate indices on a 2D embedding created for visualization.
- 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 from 2 to 6 and six seeds, plus Ward with from 2 to 6) on half the data and choose highest ARI against labels. Then apply that same configuration to the other half.
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
Step 1 of 4. Why is for ?
Step 1 of 3. How do you express as a sum of indicators?
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 of the one-standard-deviation rule with samples from referencia_pca (use one rng = np.random.default_rng(seed)), KMeans(k, n_init=2, random_state=seed) for (inertia_), with population standard deviation (np.std default), and the smallest with (or if none). Tests check reference shape on diagonally aligned data and on rotated data with known 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 1Summary
- Silhouette: . Davies–Bouldin is minimized and Calinski–Harabasz maximized, with . All three score compactness, not desired shape, and cannot say : on moons, successful DBSCAN scores worse than k-means splitting them.
- Rand index rises with cluster count without information. ARI with under permutations; arithmetic NMI is V-measure and has positive bias nats; AMI subtracts exact hypergeometric expected mutual information. Use ARI for balanced references, AMI for small clusters.
- Gap: 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 . Consensus (matrix and PAC) is its pairwise version with the same limits: a uniform square gives “stable” .
- Kleinberg: scale invariance and consistency make the range an antichain under refinement, contradicted by richness. Single linkage stopped at , or fraction 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.