liveBook · Manning

Elbow method

As explained in The Well-Grounded Data Analyst

The elbow method selects an approximate number of clusters by identifying where additional clusters produce diminishing improvement in a clustering criterion.

The elbow method estimates a useful cluster count by running k-means with several values of k and locating where additional clusters deliver sharply diminishing improvement. section 13.1.4

Use the method by:

  • Fitting k-means for multiple cluster counts and recording inertia, which measures how closely observations sit to their cluster centers. section 13.1.4
  • Plotting inertia against k and selecting the bend where further clusters barely reduce the score, then checking whether the resulting groups make practical sense. section 13.1.4
from sklearn.cluster import KMeans

k_values = range(3, 15)
inertia_values = []

for k in k_values:
    kmeans = KMeans(n_clusters=k, random_state=42)
    kmeans.fit(X_scaled)
    inertia_values.append(kmeans.inertia_)

fig, axis = plt.subplots()

axis.plot(k_values, inertia_values)

_ = axis.set(
    title="'Inertia' values for different values of k",
    xlabel="Number of clusters (the 'k' in k-means)",
    ylabel="Inertia"
)

axis.set_ybound(0, 900)

plt.show()

A runnable listing tests k from 3 through 14, collects inertia values, and plots the curve used to identify the elbow. section 13.1.4

How The Well-Grounded Data Analyst covers it

How deep it goes
Explains iterative fitting, inertia, plotting, and diminishing returns, while stopping short of treating the metric as a sufficient decision rule.
Examples
Uses mobile-user data, tests three through fourteen clusters, and highlights the transition from seven to eight clusters.
What it assumes
Assumes clustering data and k-means basics, while explaining why the cluster count must be chosen and why inertia always decreases.
What you can do after
Apply it via scikit-learn and Matplotlib to compare candidate k values before assigning clusters.
How it connects
Connects k-means clustering, inertia, cluster centers, and unsupervised learning.

Also explained in

Compare how 5 books explain elbow method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Data Analyst. The section links point to the parts of the book it draws on.