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




