Evaluate k means
Evaluating k-means clustering relies primarily on internal metrics that measure intra-cluster compactness and inter-cluster separation without ground-truth labels. Standard internal metrics include Within-Cluster Sum of Squares (WCSS / inertia), Silhouette score, Calinski-Harabasz index, and Davies-Bouldin index; when reference labels exist, external metrics such as Adjusted Rand Index (ARI) and Normalized Mutual Information (NMI) apply.
Study Card: Evaluating K-Means Clustering
Direct Answer
Because k-means is an unsupervised algorithm, evaluation usually relies on internal validation metrics that quantify both compactness (how tightly points group around centroids) and separation (how distinct clusters are from one another), supplemented by cluster visualizations and domain usefulness. Relying on raw WCSS (inertia) alone is misleading because WCSS decreases monotonically as increases; combining Silhouette score, Calinski-Harabasz index, and Davies-Bouldin index gives a balanced diagnostic. When ground-truth labels are available for benchmarking, external metrics like Adjusted Rand Index (ARI) or Normalized Mutual Information (NMI) measure agreement directly.
Key Terms
- Within-Cluster Sum of Squares (WCSS / Inertia): . Lower indicates tighter clusters, but decreases monotonically with (so look for an elbow rather than raw minimum).
- Silhouette Score: For point , , comparing mean intra-cluster distance to nearest-neighbor cluster distance (defined for ; higher is better).
- Calinski-Harabasz Index (Variance Ratio Criterion): , the ratio of between-cluster to within-cluster dispersion (higher is better; favors convex, spherical clusters).
- Davies-Bouldin Index: , measuring average worst-case similarity between each cluster and its closest neighbor (; lower is better).
Example
Imagine segmenting e-commerce shoppers by recency, frequency, and spend. A strong clustering solution combines low WCSS (shoppers inside each tier behave similarly) with a high Silhouette score (near , meaning few points sit ambiguously between segments), a peak in the Calinski-Harabasz score, and a low Davies-Bouldin index (well-separated cluster centers relative to cluster radii). Even when metrics favor , domain teams may verify whether each resulting segment corresponds to an actionable marketing persona.
Code Implementation
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import (
calinski_harabasz_score,
davies_bouldin_score,
silhouette_score,
)
# Generate synthetic data with 4 true clusters
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.60, random_state=0)
# Fit k-means with k=4
kmeans = KMeans(n_clusters=4, init='k-means++', n_init=10, random_state=42).fit(X)
labels = kmeans.labels_
print(f"WCSS (Inertia): {kmeans.inertia_:.2f}")
print(f"Silhouette Score: {silhouette_score(X, labels):.4f}")
print(f"Calinski-Harabasz Index: {calinski_harabasz_score(X, labels):.2f}")
print(f"Davies-Bouldin Index: {davies_bouldin_score(X, labels):.4f}")
# Compare internal metrics across k = 2..10
wcss_values, silhouette_scores, ch_scores, db_scores = [], [], [], []
k_values = range(2, 11)
for k in k_values:
km = KMeans(n_clusters=k, init='k-means++', n_init=10, random_state=42).fit(X)
lbl = km.labels_
wcss_values.append(km.inertia_)
silhouette_scores.append(silhouette_score(X, lbl))
ch_scores.append(calinski_harabasz_score(X, lbl))
db_scores.append(davies_bouldin_score(X, lbl))
fig, axs = plt.subplots(2, 2, figsize=(12, 8))
axs[0, 0].plot(k_values, wcss_values, marker='o')
axs[0, 0].set_title('WCSS / Inertia (Elbow Method)')
axs[0, 1].plot(k_values, silhouette_scores, marker='o')
axs[0, 1].set_title('Silhouette Score (Higher Better)')
axs[1, 0].plot(k_values, ch_scores, marker='o')
axs[1, 0].set_title('Calinski-Harabasz Index (Higher Better)')
axs[1, 1].plot(k_values, db_scores, marker='o')
axs[1, 1].set_title('Davies-Bouldin Index (Lower Better)')
for ax in axs.flat:
ax.set(xlabel='Number of Clusters (k)', ylabel='Score')
ax.grid(True)
plt.tight_layout()
plt.show()
Related Concepts
- External Clustering Metrics: When ground-truth classes are available for evaluation, Adjusted Rand Index (ARI) and Normalized Mutual Information (NMI) measure permutation-invariant cluster-label agreement corrected for chance.
- Clustering Tendency (Hopkins Statistic): Tests whether data contains genuine cluster structure rather than uniform spatial noise before interpreting any metric.
- Cluster Stability: Measuring how consistently clusters replicate across bootstrap resamples or multiple random initializations ensures the chosen is not an initialization artifact.
- Metric Biases: Silhouette, CH, and DB all favor convex, isotropic clusters; non-convex structures should be evaluated visually or using density-based indices (such as DBCV for HDBSCAN).