Skip to content
E
Educatum

Choosing k in k-means Clustering

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

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 kk in k-means clustering is critical because the k-means objective—Within-Cluster Sum of Squares (WCSS)—decreases monotonically to zero as kk approaches NN, so minimizing WCSS alone cannot identify kk. Instead, practitioners use heuristic and statistical criteria that balance cluster compactness and separation, including the Elbow method, Silhouette analysis (for k≥2k \ge 2), and the Gap statistic, alongside practical business and domain constraints.

Key Terms

  • k-means Clustering: An unsupervised algorithm partitioning NN points into kk 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: WCSS(k)=∑j=1k∑xi∈Cj∥xi−μj∥22\text{WCSS}(k) = \sum_{j=1}^{k} \sum_{x_i \in C_j} \|x_i - \mu_j\|_2^2
  • Elbow Method: Plots WCSS(k)\text{WCSS}(k) against kk and picks the inflection (“elbow”) where marginal reduction in inertia levels off.
  • Silhouette Analysis: Measures for each point ii how close it is to its own cluster (a(i)a(i)) relative to the nearest neighboring cluster (b(i)b(i)): s(i)=b(i)−a(i)max⁡(a(i),b(i))∈[−1,1]s(i) = \frac{b(i) - a(i)}{\max(a(i), b(i))} \in [-1, 1] (requires k≥2k \ge 2).
  • Gap Statistic: Compares the log observed WCSS against its expected value under a uniform null reference distribution over BB Monte Carlo draws: Gapn(k)=1B∑b=1Blog⁡(Wkb∗)−log⁡(Wk)\text{Gap}_n(k) = \frac{1}{B} \sum_{b=1}^{B} \log(W_{kb}^*) - \log(W_k) Selecting the smallest kk satisfying Tibshirani’s 1-standard-error criterion Gap(k)≥Gap(k+1)−sk+1\text{Gap}(k) \ge \text{Gap}(k+1) - s_{k+1} prevents over-splitting.

Example

Consider segmenting retail customers by purchase frequency and average spend. As kk increases from 11 to 44, WCSS drops sharply because distinct shopper tiers (“occasional,” “regular,” “high-value,” “churn-risk”) separate cleanly; beyond k=4k = 4, WCSS decays slowly, creating an elbow at k=4k = 4. Silhouette scores peak around k=4k = 4, confirming cohesive, well-separated clusters, while the Gap statistic shows the sharpest jump above uniform random dispersion at k=4k = 4. Even if k=5k = 5 improves a metric slightly, marketing teams may choose k=4k = 4 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()
  • 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 kk upfront; cutting the dendrogram at a chosen linkage height yields kk 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 D(x)2D(x)^2, reducing poor local minima and stabilizing kk-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 kk.
View all →

Try keywords like RoPE, FlashAttention, DPO, or Blind 75.