TExcelTAD
Home › Classical ML Algorithms: Supervised & Unsupervised › Evaluating and Comparing Clusterings

Evaluating and Comparing Clusterings

A classifier is judged against labels. A clustering usually has no labels to be judged against, which is exactly why it was run. So how do you know whether a clustering is good, which algorithm to trust, or how many clusters to keep? There is no single answer, but there are three kinds of evidence: internal scores computed from the data and the clusters alone, external scores when some reference labels exist, and stability under resampling. This lesson computes each and runs the four algorithms of this section on three data sets with different shapes.

Internal scores

Silhouette. For point ii, let aia_i be its mean distance to the other points of its own cluster and bib_i its mean distance to the points of the nearest other cluster. Then

si=bi−aimax⁡(ai,bi)∈[−1,1],S=1n∑i=1nsi.s_i = \frac{b_i - a_i}{\max(a_i, b_i)} \in [-1, 1], \qquad S = \frac{1}{n} \sum_{i=1}^{n} s_i .

sis_i near 1: well inside its cluster; near 0: on a border; negative: probably in the wrong cluster. Davies-Bouldin (lower is better) compares cluster spreads with distances between centroids, and Calinski-Harabasz (higher is better) is the ratio of between- to within-cluster dispersion. All three reward compact, well-separated, convex clusters, which matters below.

External scores

When a reference labelling exists (a benchmark, a hand-labelled sample, a known grouping), the adjusted Rand index counts pairs of points that both partitions put together or apart, corrected so that a random clustering scores about 0 and identical partitions score 1. It does not care about the cluster numbers, only about who is grouped with whom. Normalised mutual information is an information-theoretic alternative. External scores are for evaluating algorithms on data where you know the answer, never a way to tune a clustering of the real data, where you do not.

Silhouette from scratch, and stability

python · try it yourself
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, silhouette_samples, adjusted_rand_score

X, _ = make_blobs(n_samples=120, centers=3, cluster_std=1.2, random_state=4)
labels = KMeans(n_clusters=3, n_init=10, random_state=0).fit_predict(X)

def silhouette(X, labels):
    D = np.sqrt(((X[:, None] - X[None]) ** 2).sum(axis=2))
    s = np.zeros(len(X))
    for i in range(len(X)):
        same = labels == labels[i]
        a = D[i, same].sum() / (same.sum() - 1)                       # mean distance to its own cluster
        b = min(D[i, labels == c].mean() for c in set(labels) if c != labels[i])   # nearest other cluster
        s[i] = (b - a) / max(a, b)
    return s

s = silhouette(X, labels)
print("silhouette ours", round(s.mean(), 4), " sklearn", round(silhouette_score(X, labels), 4))
print("per-point values match:", np.allclose(s, silhouette_samples(X, labels)))
print("points with a negative silhouette (probably in the wrong cluster):", int(np.sum(s < 0)))

# stability: cluster two random halves, compare on the points they share
rng = np.random.default_rng(0)
for k in [2, 3, 4, 6]:
    aris = []
    for rep in range(10):
        a = rng.choice(len(X), 80, replace=False)
        b = rng.choice(len(X), 80, replace=False)
        ka = KMeans(n_clusters=k, n_init=10, random_state=rep).fit(X[a])
        kb = KMeans(n_clusters=k, n_init=10, random_state=rep).fit(X[b])
        aris.append(adjusted_rand_score(ka.predict(X), kb.predict(X)))
    print(f"k={k}: stability (mean ARI between runs on different halves) {np.mean(aris):.3f}")
silhouette ours 0.5518  sklearn 0.5518
per-point values match: True
points with a negative silhouette (probably in the wrong cluster): 0
k=2: stability (mean ARI between runs on different halves) 1.000
k=3: stability (mean ARI between runs on different halves) 0.964
k=4: stability (mean ARI between runs on different halves) 0.910
k=6: stability (mean ARI between runs on different halves) 0.852

The silhouette loop matches scikit-learn point by point. Stability asks a different question: if you cluster two different random subsets and label all the data with both models, do they agree? A clustering that reflects real structure should not depend much on which rows you happened to sample. Here k=3k = 3 (the generating number) is quite stable (0.964), k=6k = 6 much less. Stability tends to favour small kk, though: splitting the data into two is always stable when two groups dominate, as it is here. As always, no one criterion decides.

Four algorithms, three shapes

Three generated data sets with known groups: blobs of different spreads, the same blobs stretched by a linear map, and two moons. Every algorithm gets the true number of clusters (DBSCAN gets ε=0.3\varepsilon = 0.3 on standardised data instead), and both the external ARI and the internal silhouette are shown:

python · try it yourself
import numpy as np
from sklearn.datasets import make_blobs, make_moons
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans, AgglomerativeClustering, DBSCAN
from sklearn.mixture import GaussianMixture
from sklearn.metrics import silhouette_score, adjusted_rand_score

Xb, yb = make_blobs(n_samples=300, centers=3, cluster_std=[1.0, 2.5, 0.5], random_state=170)
Xa = Xb @ np.array([[0.6, -0.6], [-0.4, 0.8]])        # stretched (anisotropic) blobs
Xm, ym = make_moons(n_samples=300, noise=0.05, random_state=0)
datasets = {"blobs": (Xb, yb, 3), "stretched": (Xa, yb, 3), "moons": (Xm, ym, 2)}

print(f"{'data':10s} {'algorithm':14s} {'ARI':>6s} {'silhouette':>11s}")
for name, (X, y, k) in datasets.items():
    X = StandardScaler().fit_transform(X)
    algos = {
        "k-means":       KMeans(n_clusters=k, n_init=10, random_state=0),
        "ward":          AgglomerativeClustering(n_clusters=k, linkage="ward"),
        "single link":   AgglomerativeClustering(n_clusters=k, linkage="single"),
        "GMM (full)":    GaussianMixture(n_components=k, n_init=3, random_state=0),
        "DBSCAN":        DBSCAN(eps=0.3, min_samples=5),
    }
    for aname, algo in algos.items():
        labels = algo.fit_predict(X)
        sil = silhouette_score(X, labels) if len(set(labels)) > 1 else float("nan")
        print(f"{name:10s} {aname:14s} {adjusted_rand_score(y, labels):6.3f} {sil:11.3f}")
data       algorithm         ARI  silhouette
blobs      k-means         0.722       0.637
blobs      ward            0.760       0.613
blobs      single link     0.001      -0.080
blobs      GMM (full)      0.951       0.575
blobs      DBSCAN          0.800       0.444
stretched  k-means         0.498       0.592
stretched  ward            0.521       0.577
stretched  single link     0.000      -0.066
stretched  GMM (full)      0.951       0.396
stretched  DBSCAN          0.521       0.308
moons      k-means         0.470       0.495
moons      ward            0.650       0.459
moons      single link     1.000       0.383
moons      GMM (full)      0.488       0.495
moons      DBSCAN          1.000       0.383

Read the table by data set:

  • Blobs of different spreads: the GMM, which models each blob's own covariance, is best (ARI 0.951). k-means and Ward, which prefer equal-sized round clusters, split the wide blob wrongly. Single linkage chains everything into one cluster plus two stragglers (ARI 0.001).
  • Stretched blobs: only the GMM copes with the tilted ellipses (0.951); everything else drops to about 0.5.
  • Moons: the density and chaining methods, DBSCAN and single linkage, recover the moons perfectly (1.000); the methods built on centroids and ellipses cannot.

Now compare the silhouette column. On the stretched blobs the silhouette ranks the GMM, the only correct answer, near the bottom (0.396), and on the moons it gives the perfect DBSCAN partition a lower score (0.383) than the wrong k-means one (0.495). The silhouette rewards compact, round, well-separated clusters, so it favours whatever k-means would do. Internal scores are useful for choosing kk within one algorithm; they cannot tell you which notion of "cluster" fits your data.

A practical checklist

  1. Decide what a cluster should mean for the task: compact groups (k-means, Ward), elliptical overlapping groups (GMM), dense regions with noise (DBSCAN), a hierarchy (dendrogram).
  2. Scale the features and check what the distance treats as similar.
  3. Use internal scores and stability to choose kk or ε\varepsilon within the chosen family.
  4. Look at the clusters: their sizes, their feature means, a 2-D projection (PCA), a sample of members.
  5. Validate externally when any labels or business outcomes exist: do the segments differ in what matters (churn rate, spend)?

Practice

  1. A point has mean distance 2 to its own cluster and 3 to the nearest other cluster. What is its silhouette? What if the numbers were swapped?
Answer

s=(3−2)/3=0.333s = (3 - 2)/3 = 0.333. Swapped: s=(2−3)/3=−0.333s = (2 - 3)/3 = -0.333; the point is closer on average to the other cluster, so it is probably misassigned.

  1. Why can't you use ARI to choose the number of clusters for a new customer data set?
Answer

ARI compares a clustering with reference labels. A new data set has none (otherwise you would train a classifier), so only internal scores, stability and the usefulness of the segments are available.

Test yourself

A point has a negative silhouette value. What does that suggest?

  1. It is a core point
  2. It is on average closer to another cluster than to its own
  3. It is noise
  4. The clustering is perfect

What does an adjusted Rand index of about 0 mean?

  1. Perfect agreement
  2. Agreement no better than chance
  3. Perfect disagreement in the labels' numbering
  4. The clusters are compact

On the moons, DBSCAN found the true groups but had a lower silhouette than k-means. Why?

  1. DBSCAN is wrong
  2. The silhouette favours compact, convex clusters, which the moons are not
  3. Silhouette ignores noise
  4. k-means used more clusters