Sub topic 15
Evaluating clusterings without ground truth
This chapter assumes you can run AgglomerativeClustering, scipy's linkage and fcluster, and DBSCAN, as covered earlier. It also assumes you know what a dendrogram is and what eps and min_samples control.
Clustering has no labels to compare against, so there is no accuracy score. You can still measure how well a result fits the data, but each measure carries assumptions about what a cluster looks like. This chapter covers the common internal metrics, the checks specific to hierarchical trees, the extra care DBSCAN needs because of noise, and the limits of all of them.
Internal metrics and what they assume
An internal metric scores a clustering using only the data and the assigned labels. Most of them reward two things: points close to their own cluster (cohesion) and clusters far from each other (separation).
| Metric | scikit-learn function | Range | Better is |
|---|---|---|---|
| Silhouette score | `silhouette_score` | -1 to 1 | Higher |
| Davies-Bouldin index | `davies_bouldin_score` | 0 and up | Lower |
| Calinski-Harabasz index | `calinski_harabasz_score` | 0 and up | Higher |
Silhouette. For each point, let a be its mean distance to the other points in its own cluster. Let b be its mean distance to the points in the nearest other cluster. The point's silhouette is (b - a) / max(a, b). Values near 1 mean the point sits well inside its cluster. Values near 0 mean it lies on a boundary. Negative values suggest it may be in the wrong cluster. silhouette_score averages this over all points. It takes O(n²) time, so use the sample_size argument on large datasets.
Davies-Bouldin compares each cluster's spread to the distance to its most similar neighbor cluster. Calinski-Harabasz is the ratio of between-cluster variance to within-cluster variance. Both are cheap to compute.
All three assume compact, roughly convex clusters. Ward linkage produces such clusters, so these metrics suit it well. Single linkage and DBSCAN can produce elongated or curved clusters, and the metrics often score those poorly even when the clustering is correct.
Cophenetic correlation for hierarchical trees
A dendrogram is a model of the data's distances. The cophenetic distance between two points is the merge height at which they first join the same cluster. The cophenetic correlation is the correlation between those tree distances and the original pairwise distances. A value near 1 means the tree preserves the original distances well.
This checks the tree as a whole, before you cut it. It does not tell you how many clusters to choose. It is most useful for comparing linkage methods on the same data.
Scoring a range of cuts
For hierarchical clustering, the usual workflow is to build the tree once and score several cuts. The code below does that for average linkage on four-blob data.
from scipy.cluster.hierarchy import cophenet, fcluster, linkage
from scipy.spatial.distance import pdist
from sklearn.datasets import make_blobs
from sklearn.metrics import (
calinski_harabasz_score,
davies_bouldin_score,
silhouette_score,
)
from sklearn.preprocessing import StandardScaler
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.8, random_state=3)
X = StandardScaler().fit_transform(X)
for method in ["single", "complete", "average", "ward"]:
Z = linkage(X, method=method)
corr, _ = cophenet(Z, pdist(X))
print(f"{method:9s} cophenetic correlation: {corr:.3f}")
Z = linkage(X, method="ward")
print("k silhouette davies_bouldin calinski_harabasz")
for k in range(2, 8):
labels = fcluster(Z, t=k, criterion="maxclust")
sil = silhouette_score(X, labels)
dbi = davies_bouldin_score(X, labels)
chi = calinski_harabasz_score(X, labels)
print(f"{k} {sil:10.3f} {dbi:14.3f} {chi:17.1f}")Read the table as a set of candidates, not a verdict. Silhouette and Davies-Bouldin usually agree on a good k when clusters are well separated. Calinski-Harabasz tends to keep rising as k grows on some datasets, so look for a peak, not the maximum value at the edge of your range. When the metrics disagree, that is a sign the data has no single clear cluster count.
Evaluating DBSCAN: handle noise explicitly
DBSCAN labels outliers as -1. Passing those labels straight into a metric creates problems:
- Noise is not a cluster. Treating
-1as one cluster scores a scattered set of points as if it were a compact group. - If DBSCAN finds fewer than two clusters, silhouette raises a
ValueError. - Dropping noise makes the score look better. A result that discards 40% of the data as noise can score higher than one that clusters nearly everything.
So report the metric and the noise fraction together. The function below does this and scores a small grid of eps values.
import numpy as np
from sklearn.cluster import DBSCAN
from sklearn.datasets import make_moons
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler
def score_dbscan(X, labels):
"""Return (n_clusters, noise_fraction, silhouette or None)."""
mask = labels != -1
n_clusters = len(set(labels[mask]))
noise_fraction = 1.0 - mask.mean()
if n_clusters < 2:
return n_clusters, noise_fraction, None
return n_clusters, noise_fraction, silhouette_score(X[mask], labels[mask])
X, _ = make_moons(n_samples=300, noise=0.05, random_state=0)
X = StandardScaler().fit_transform(X)
for eps in [0.1, 0.2, 0.3, 0.5, 1.0]:
labels = DBSCAN(eps=eps, min_samples=5).fit_predict(X)
n_clusters, noise, sil = score_dbscan(X, labels)
sil_text = "n/a" if sil is None else f"{sil:.3f}"
print(f"eps={eps:<4} clusters={n_clusters:<3} noise={noise:.2%} silhouette={sil_text}")Expect the silhouette on the moons to be modest even when DBSCAN separates the two crescents correctly. Points near the tips of one crescent can be closer on average to the other crescent than to their own far end, and that lowers b - a. The low score reflects the metric's convexity assumption, not a bad clustering. Plotting the labels is the more reliable check here.
There are density-aware alternatives, such as DBCV (density-based clustering validation). It is not part of scikit-learn, so you need an extra package. Use it if you must compare density-based results quantitatively.
Beyond a single score
A metric is one input. These checks cover what it cannot.
- Stability. Resample the data (for example, 80% subsets) and re-cluster. Compare the labelings of the shared points with
adjusted_rand_score. If small changes to the data produce very different clusters, the structure is fragile. - Parameter sensitivity. For DBSCAN, vary
epsby ±20% and watch the number of clusters and the noise fraction. A plateau means the result is robust. A cliff means the chosen value is at an edge. - Visual inspection. Project to two dimensions (PCA or a scatter of the two most informative features) and look at the labels.
- Domain meaning. Examine cluster profiles, such as per-cluster feature means or example members. A clustering that scores well but cannot be described is rarely useful.
- Preprocessing. Every metric depends on the feature scaling and distance metric you used. Scores computed on different scalings are not comparable.
Common mistakes
- Scoring noise as a cluster. Mask out
-1and report the noise fraction next to the score. - Picking
kfrom one metric. Check at least two metrics and a plot. - Maximizing the score blindly. Silhouette rises when you drop hard points. A grid search over
epsthat maximizes silhouette tends to choose settings that label many points as noise. - Ignoring scaling. A feature measured in thousands dominates Euclidean distance and shifts every metric.
- Over-reading small differences. A silhouette of 0.52 versus 0.50 is within the variation you would see from resampling.
Exercise
You run DBSCAN on a scaled dataset. Setting eps=0.25 gives 3 clusters, 35% noise, and a silhouette of 0.71 on non-noise points. Setting eps=0.40 gives 3 clusters, 4% noise, and a silhouette of 0.58. Which result would you prefer by default, and what would you check next?
Show answer
Lean toward eps=0.40. The higher silhouette at eps=0.25 is computed only on the points that survived, so discarding 35% of the data inflates it. The result at eps=0.40 explains almost all the data with a still-reasonable score. Next, check stability by resampling and varying eps slightly around 0.40, and plot the labels. Also confirm that the clusters are meaningful in the domain and that the 4% noise points look like true outliers.
Exercise
A hierarchical clustering using single linkage has a high cophenetic correlation but a low silhouette score for the 2-cluster cut. Give one reason this can happen.
Show answer
Cophenetic correlation measures how well the tree preserves pairwise distances, while silhouette measures compactness and separation of the flat clusters. Single linkage can produce elongated, chained clusters that follow the data's shape, so the tree is faithful but the clusters are not compact. Silhouette penalizes that shape even if the grouping is sensible.