Sub topic 9
Choosing k with the elbow method and silhouette score
K-means needs you to choose the number of clusters, k, before it runs. This chapter covers two common ways to choose it. It assumes you can fit KMeans in scikit-learn and know that inertia is the sum of squared distances from each point to its assigned centroid.
Why inertia alone cannot pick k
Adding a centroid never makes the best achievable inertia worse. With k equal to the number of points, every point is its own centroid and inertia is 0. So "pick the k with the lowest inertia" always picks the largest k you try.
You need a criterion that rewards compact clusters but also notices when extra clusters stop helping. The elbow method and the silhouette score do this in different ways.
The elbow method
Fit k-means for a range of k values and plot inertia against k. Inertia falls steeply while you add clusters that match real structure. After that it falls slowly, because you are only splitting clusters that were already coherent. The bend in the curve is the "elbow", and its k is the candidate.
The elbow is a visual judgment. Real data often gives a smooth curve with no clear bend. Treat the elbow as a hint, not a result.
The silhouette score
The silhouette score measures how well each point fits its own cluster compared with the nearest other cluster. For a point i:
- a(i) is the mean distance from i to the other points in its own cluster.
- b(i) is the mean distance from i to the points in the nearest cluster that i does not belong to.
- The silhouette is s(i) = (b(i) - a(i)) / max(a(i), b(i)).
The value lies between -1 and 1. Near 1 means the point sits well inside its cluster. Near 0 means it lies on a boundary. Negative means it is probably closer to another cluster. silhouette_score returns the mean of s(i) over all points. Unlike inertia, this mean can drop as k grows, so you can choose the k with the highest value.
Comparing both on one dataset
This code fits k-means for k from 2 to 7 on data generated with four true clusters. It prints both criteria for each k.
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=300, centers=4, random_state=7)
for k in range(2, 8):
km = KMeans(n_clusters=k, n_init=10, random_state=7).fit(X)
score = silhouette_score(X, km.labels_)
print(f"k={k} inertia={km.inertia_:.1f} silhouette={score:.3f}")Read the output in two passes:
- Look down the inertia column. It decreases at every row. Find where the drop per step shrinks sharply. On well-separated blobs this happens at the true number of clusters.
- Look down the silhouette column. Pick the row with the highest score. On well-separated blobs this is usually k=4 as well.
The exact numbers depend on your scikit-learn version and the random seed, so compare the shape of the columns rather than specific values.
Common errors
- Skipping feature scaling. Both criteria use distances. If one feature dominates, the "best" k reflects that feature only. Scale first, as in the earlier chapter on scaling.
- Using
n_init=1. A bad local minimum can create a fake bump in the curve. Use several restarts so each k gets a fair fit. - Forcing an elbow. If the curve is smooth, say so and lean on the silhouette score or on what the clusters are for.
- Trusting the highest silhouette blindly. Silhouette favors compact, round, similarly sized clusters. It often gives k=2 for data that has two broad groups with sub-structure inside each.
- Starting the range at k=1. Silhouette is undefined for one cluster. Start at 2 for silhouette. Include k=1 in the elbow plot only if you want to see the baseline.
- Ignoring cluster sizes. A k with a high mean silhouette can still contain a tiny cluster of outliers. Check
np.bincount(km.labels_).
Summary of the trade-offs
| Criterion | What it uses | Strength | Weakness |
|---|---|---|---|
| Elbow (inertia) | Within-cluster squared distance | Cheap, one number per k | Subjective, often no clear bend |
| Silhouette | Distances within and between clusters | Gives a number to maximize | Costly on large data, biased toward round clusters |
Exercise
You run k-means for k = 2 to 10. Inertia falls smoothly with no visible bend, and the mean silhouette is highest at k=2 (0.61) and lower at k=5 (0.48). Why might you still prefer k=5, and what should you check before deciding?
Show answer
A high silhouette at k=2 can mean the data has two broad groups, while a finer structure inside them is what matters for your task. Silhouette favors compact, round clusters and often rewards a coarse split. Before deciding, check the cluster sizes and per-cluster silhouette values at k=5, confirm the features were scaled, and see whether the five clusters are meaningful for the problem. If they are, choose k=5. If one cluster is tiny or has a negative average silhouette, k=2 or a smaller k may be better.