Choosing k in k-means Clustering
Selecting the optimal number of clusters k in k-means balances intra-cluster compactness against inter-cluster separation because raw within-cluster variance decreases monotonically as k grows. Common empirical techniques include the Elbow method on WCSS, Silhouette analysis (defined for k >= 2), and the Gap statistic, complemented by downstream domain constraints.
Study Card: Choosing k in k-means Clustering
Direct Answer
Choosing the number of clusters in k-means clustering is critical because the k-means objective—Within-Cluster Sum of Squares (WCSS)—decreases monotonically to zero as approaches , so minimizing WCSS alone cannot identify . Instead, practitioners use heuristic and statistical criteria that balance cluster compactness and separation, including the Elbow method, Silhouette analysis (for ), and the Gap statistic, alongside practical business and domain constraints.
Key Terms
- k-means Clustering: An unsupervised algorithm partitioning points into clusters by iteratively assigning each point to its nearest centroid and updating centroids to cluster means.
- Within-Cluster Sum of Squares (WCSS / Inertia): Total squared Euclidean distance from points to their assigned centroids:
- Elbow Method: Plots against and picks the inflection (“elbow”) where marginal reduction in inertia levels off.
- Silhouette Analysis: Measures for each point how close it is to its own cluster () relative to the nearest neighboring cluster (): (requires ).
- Gap Statistic: Compares the log observed WCSS against its expected value under a uniform null reference distribution over Monte Carlo draws: Selecting the smallest satisfying Tibshirani’s 1-standard-error criterion prevents over-splitting.
Example
Consider segmenting retail customers by purchase frequency and average spend. As increases from to , WCSS drops sharply because distinct shopper tiers (“occasional,” “regular,” “high-value,” “churn-risk”) separate cleanly; beyond , WCSS decays slowly, creating an elbow at . Silhouette scores peak around , confirming cohesive, well-separated clusters, while the Gap statistic shows the sharpest jump above uniform random dispersion at . Even if improves a metric slightly, marketing teams may choose if four campaigns match operational capacity.
Code Implementation
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.datasets import make_blobs
# Generate synthetic data with 4 true centers
random_state = 42
rng = np.random.default_rng(random_state)
X, _ = make_blobs(n_samples=300, centers=4, random_state=random_state)
# 1. Elbow Method (WCSS / inertia_)
k_range = range(1, 11)
wcss = []
for k in k_range:
kmeans = KMeans(n_clusters=k, init='k-means++', max_iter=300, n_init=10, random_state=random_state)
kmeans.fit(X)
wcss.append(kmeans.inertia_) # using inertia_ attribute for WCSS
plt.figure(figsize=(8, 5))
plt.plot(k_range, wcss, marker='o')
plt.title('Elbow Method')
plt.xlabel('Number of clusters (k)')
plt.ylabel('WCSS (Inertia)')
plt.show()
# 2. Silhouette Analysis (requires k >= 2)
k_sil_range = range(2, 11)
silhouette_scores = []
for k in k_sil_range:
clusterer = KMeans(n_clusters=k, init='k-means++', n_init=10, random_state=random_state)
labels = clusterer.fit_predict(X)
silhouette_scores.append(silhouette_score(X, labels))
plt.figure(figsize=(8, 5))
plt.plot(k_sil_range, silhouette_scores, marker='o')
plt.title('Silhouette Analysis')
plt.xlabel('Number of clusters (k)')
plt.ylabel('Mean Silhouette Score')
plt.show()
# 3. Gap Statistic: E*[log(W_k)] - log(W_k) with 1-SE selection rule
def generate_uniform_reference(X_data, rng_gen):
min_vals = np.min(X_data, axis=0)
max_vals = np.max(X_data, axis=0)
return rng_gen.uniform(low=min_vals, high=max_vals, size=X_data.shape)
n_refs = 10
gaps = []
sks = []
for k, wcss_obs in zip(k_range, wcss):
log_wcss_refs = []
for _ in range(n_refs):
ref_X = generate_uniform_reference(X, rng)
km_ref = KMeans(n_clusters=k, init='k-means++', n_init=10, random_state=random_state).fit(ref_X)
log_wcss_refs.append(np.log(km_ref.inertia_))
mean_log_ref = np.mean(log_wcss_refs)
sd_log_ref = np.std(log_wcss_refs, ddof=0)
gaps.append(mean_log_ref - np.log(wcss_obs))
sks.append(sd_log_ref * np.sqrt(1.0 + 1.0 / n_refs))
# Tibshirani 1-SE rule: smallest k where Gap(k) >= Gap(k+1) - s_{k+1}
optimal_k = next(
(k for idx, k in enumerate(list(k_range)[:-1]) if gaps[idx] >= gaps[idx + 1] - sks[idx + 1]),
list(k_range)[-1]
)
print(f"Gap Statistic optimal k (1-SE rule): {optimal_k}")
plt.figure(figsize=(8, 5))
plt.errorbar(list(k_range), gaps, yerr=sks, marker='o', capsize=4)
plt.title("Gap Statistic")
plt.xlabel("Number of Clusters (k)")
plt.ylabel("Gap Value")
plt.show()
Related Concepts
- Alternative Clustering Indices: Calinski-Harabasz index (higher is better) and Davies-Bouldin index (lower is better) offer fast analytical checks without reference resampling.
- Hierarchical Clustering: Builds a dendrogram across all granularity levels without fixing upfront; cutting the dendrogram at a chosen linkage height yields clusters.
- DBSCAN and HDBSCAN: Density-based algorithms that infer the number of clusters automatically, discover non-convex shapes, and label low-density points as noise.
- K-Means++ Initialization: Spreads initial centroids probabilistically proportional to squared distance , reducing poor local minima and stabilizing -selection curves.
- Curse of Dimensionality: In high dimensions, Euclidean distances concentrate and pairwise contrasts shrink; dimensionality reduction (e.g., PCA or UMAP) before clustering often clarifies .