How do you determine the number of clusters using the elbow method?
Last updated
Fit k-means for a range of k, plot within-cluster sum of squares (WCSS, or inertia) against k, and pick the "elbow": the k after which adding clusters gives sharply diminishing reductions in WCSS.
Procedure:
Scale features. k-means is distance-based, so unscaled features distort the clusters.
For k = 1…K, run k-means with several restarts (
n_init) and recordinertia_.Plot WCSS vs k. Look for where the curve bends from steep to flat.
Intuition:
Below the true k, each new cluster splits a real group and WCSS drops a lot.
Above it, new clusters just subdivide existing groups, so the gains are small.
Making it less subjective: detect the knee automatically (Kneedle,
kneed.KneeLocator), or use the point of maximum second difference.Cross-check with silhouette score, the gap statistic, or domain needs.
[lang:python]
from sklearn.cluster import KMeans
inertias = [KMeans(n_clusters=k, n_init=10, random_state=0).fit(X).inertia_
for k in range(1, 11)]
# plot range(1, 11) vs inertias and look for the bend
- https://medium.com/@erzeneminegul/elbow-method-finding-the-optimal-number-of-clusters-in-k-means-9bc652a403ef
- https://medium.com/@wiradirgantara55/k-means-clustering-the-methods-for-choosing-the-ideal-number-of-clusters-with-practical-use-case-ade2461fd10b
- https://gist.github.com/marcoscastro/e55550646b19724aaa7f