Skip to content
E
Educatum

Optimal k in k means

Curated by Educatum AI teamLast updated:
Basic Concepts
Direct Answer

Selecting the optimal number of clusters k in K-means commonly combines the Elbow Method and Silhouette Analysis. The Elbow Method looks for diminishing returns in within-cluster sum of squares (WCSS) as k grows, while Silhouette Analysis selects the k maximizing average cluster cohesion relative to separation across all data points.

Study Card: Determining the Optimal k in K-means Clustering

Direct Answer

Because K-means requires specifying kk upfront and its objective (WCSS) strictly decreases as kk increases—reaching 00 when k=nk = n—you cannot simply pick kk by minimizing WCSS. Instead, practitioners rely on heuristic and cluster-validity methods:

  • Elbow Method: Plots Within-Cluster Sum of Squares (WCSS=∑j=1k∑xi∈Cj∥xi−μj∥22\text{WCSS} = \sum_{j=1}^k \sum_{x_i \in C_j} \|x_i - \mu_j\|_2^2) versus kk and identifies the inflection (“elbow”) where marginal WCSS gains flatten out.
  • Silhouette Method: Computes each sample’s silhouette coefficient s(i)=b(i)−a(i)max⁡(a(i),b(i))s(i) = \frac{b(i) - a(i)}{\max(a(i), b(i))} comparing mean intra-cluster distance a(i)a(i) to mean nearest-cluster distance b(i)b(i), choosing the kk (for k≥2k \ge 2) that maximizes the mean silhouette score in [−1,1][-1, 1].

Together with domain knowledge and downstream task requirements, these diagnostics balance cluster compactness against separation.

Key Terms

  • Within-Cluster Sum of Squares (WCSS / Inertia): Sum of squared Euclidean distances from each point to its assigned cluster centroid: ∑j=1k∑xi∈Cj∥xi−μj∥22\sum_{j=1}^k \sum_{x_i \in C_j} \|x_i - \mu_j\|_2^2.
  • Elbow Method: Visual diagnostic identifying where adding additional clusters yields sharply diminishing reductions in WCSS.
  • Silhouette Coefficient: Per-point score 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], where values near +1+1 indicate well-separated, compact clusters, 00 indicates overlapping boundaries, and negative values suggest misassignment.
  • Silhouette Method: Selecting k≥2k \ge 2 that maximizes the average silhouette score across the dataset.
  • Centroid: Mean vector μj\mu_j of all points in cluster CjC_j.

Example

Suppose you segment customer purchase behavior with K-means across k∈{1,…,10}k \in \{1, \dots, 10\}. Plotting WCSS shows rapid drops from k=1k=1 to k=3k=3, followed by a shallow slope for k≥4k \ge 4: the elbow at k=3k=3 suggests three clusters strike a useful balance between minimizing intra-cluster variance and avoiding overly fragmented, uninformative groups. Checking Silhouette scores across k∈{2,…,10}k \in \{2, \dots, 10\} confirms whether k=3k=3 also achieves the strongest cohesion-to-separation ratio (e.g., 0.7).

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 sample data with 4 true clusters
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=0.6, random_state=0)

# Elbow Method (k = 1..10)
wcss = []
for k in range(1, 11):
    kmeans = KMeans(n_clusters=k, init='k-means++', max_iter=300, n_init=10, random_state=0)
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)

plt.figure(figsize=(8, 6))
plt.plot(range(1, 11), wcss, marker='o')
plt.title('Elbow Method for Optimal k')
plt.xlabel('Number of clusters (k)')
plt.ylabel('WCSS')
plt.show()

# Silhouette Method (defined for k >= 2)
silhouette_scores = []
for k in range(2, 11):
    kmeans = KMeans(n_clusters=k, init='k-means++', max_iter=300, n_init=10, random_state=0)
    cluster_labels = kmeans.fit_predict(X)
    silhouette_scores.append(silhouette_score(X, cluster_labels))

plt.figure(figsize=(8, 6))
plt.plot(range(2, 11), silhouette_scores, marker='o')
plt.title('Silhouette Method for Optimal k')
plt.xlabel('Number of clusters (k)')
plt.ylabel('Silhouette Score')
plt.show()

optimal_k_silhouette = np.argmax(silhouette_scores) + 2  # Offset by 2 because range starts at k=2
print(f"Optimal k from silhouette: {optimal_k_silhouette}")
  • K-means Assumptions & Limitations: Because K-means imposes convex, isotropic Voronoi cells, non-spherical or highly imbalanced clusters can distort both the elbow curve and silhouette scores.
  • Gap Statistic: Compares log⁡(WCSSk)\log(\text{WCSS}_k) against the expected log⁡(WCSSk)\log(\text{WCSS}_k) under a uniform null reference distribution, offering a more formal criterion (and supporting k=1k=1 evaluation).
  • Davies-Bouldin & Calinski-Harabasz Indices: Alternative internal cluster validity metrics measuring the ratio of within-cluster dispersion to between-cluster separation.
  • Cluster Stability: Evaluating agreement (e.g., Adjusted Rand Index) across bootstrap subsamples—the true kk typically produces the most consistent partitions.
  • Hierarchical & Density-Based Alternatives: Agglomerative clustering (via dendrogram cutoffs) and HDBSCAN/DBSCAN avoid fixing kk upfront when cluster count is unknown.
View all →

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