Sub topic 9
Choosing k with the elbow method and silhouette score
K-means needs you to supply k before it runs, and the data rarely tells you the right value. This chapter covers two common diagnostics, the elbow method and the silhouette score. It also covers how to combine them with domain knowledge and why neither gives a definitive answer.
This chapter assumes you can fit a KMeans model in scikit-learn and read its inertia_ attribute. It also assumes you know that features should be scaled before clustering. Both ideas were covered in earlier chapters.
Why k cannot be fitted like other parameters
In supervised learning you can pick a hyperparameter by measuring held-out error against labels. Clustering has no labels, so there is no ground truth to score against. Whatever criterion you choose is a proxy for "the clusters look sensible."
Inertia, the sum of squared distances from each point to its assigned centroid, is the objective k-means minimizes. It cannot be used directly to choose k, because it never increases as k grows. With k equal to the number of samples, every point is its own centroid and inertia is exactly zero. Minimizing inertia over k therefore always picks the largest k you allow.
So both methods below ask a different question. The elbow method asks where adding clusters stops paying off. The silhouette score asks how well separated the clusters are, independent of how many there are.
The elbow method
Fit k-means for a range of k values and record the inertia of each fit. Plot inertia against k. The curve falls steeply while extra clusters split genuinely distinct groups. It then flattens once extra clusters only subdivide groups that were already compact. The bend between the two regimes is the "elbow," and the k at the bend is the candidate.
The diagram below shows an illustrative inertia curve. The numbers are made up to show the shape, not output from a real run.
Where the elbow method fails
The elbow is a visual judgment, and many real curves have no clear bend. Data with overlapping or hierarchical structure gives a smooth, nearly exponential decay. Two people looking at the same plot can pick different k values.
You can reduce the subjectivity with a numeric rule. One simple rule draws a straight line from the first point to the last point of the curve. It then picks the k whose point lies farthest from that line. This works because a convex decreasing curve bows below the line, and the elbow is where it bows the most. The Kneedle algorithm, available in the third-party kneed package, is a more refined version of the same idea. Any such rule is still a heuristic and returns an answer even when the curve has no real elbow.
The silhouette score
The silhouette score measures how well each point fits its own cluster compared with the nearest other cluster. For a single point i:
a(i)is the mean distance fromito the other points in its own cluster.b(i)is the mean distance fromito the points in the nearest cluster that is not its own.- The silhouette is
s(i) = (b(i) - a(i)) / max(a(i), b(i)).
The value always lies between -1 and 1. A value near 1 means the point is much closer to its own cluster than to any other. A value near 0 means it sits on the boundary between two clusters. A negative value means it is closer, on average, to another cluster than to its own, which suggests it is probably misassigned.
silhouette_score returns the mean of s(i) over all points. Unlike inertia, this mean does not improve automatically as k grows. Splitting a real cluster in two puts many points near a boundary and pulls the average down. That is why you can pick the k with the highest mean silhouette.
Practical points about silhouette
- It is defined only for
2 <= k <= n_samples - 1. It cannot tell you whether k=1 (no cluster structure) is the right answer. - It needs all pairwise distances, so the cost grows with the square of the number of samples. For large data, pass
sample_sizetosilhouette_score, together with arandom_state, to score on a random subset. - It uses the same distance as your clustering, so unscaled features distort it in the same way they distort k-means itself. Scale first.
- It rewards compact, convex, similarly sized clusters, which is the shape k-means assumes. If your data has elongated or nested clusters, a high silhouette still may not mean the clustering is good.
Comparing both criteria in code
The script below fits k-means for several values of k on scaled data. It prints both metrics and also applies the line-distance rule to the inertia curve. Run it and compare the two answers.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
def elbow_k(ks, inertias):
"""Return the k whose point lies farthest from the line joining the curve's ends."""
ks = np.asarray(ks, dtype=float)
y = np.asarray(inertias, dtype=float)
# Rescale both axes to [0, 1] so the distance is not dominated by one axis
xn = (ks - ks[0]) / (ks[-1] - ks[0])
yn = (y - y[-1]) / (y[0] - y[-1])
# The line from (0, 1) to (1, 0) is x + y = 1, so distance is proportional to |x + y - 1|
distance = np.abs(xn + yn - 1)
return int(ks[distance.argmax()])
X, _ = make_blobs(n_samples=300, centers=4, random_state=7)
X = StandardScaler().fit_transform(X)
ks = list(range(2, 9))
inertias, silhouettes = [], []
for k in ks:
km = KMeans(n_clusters=k, n_init=10, random_state=7).fit(X)
inertias.append(km.inertia_)
silhouettes.append(silhouette_score(X, km.labels_))
print(f"k={k} inertia={km.inertia_:.1f} silhouette={silhouettes[-1]:.3f}")
print("elbow rule picks k =", elbow_k(ks, inertias))
print("best silhouette at k =", ks[int(np.argmax(silhouettes))])Note n_init=10 in the fits. Each k is a separate optimization that can land in a local minimum. A single unlucky start at one k produces a bump in the curve that looks like a real feature. Use the same n_init and random_state for every k so the comparison is fair.
On well-separated blobs like these, both criteria should agree. On real data they often do not, which is the usual case to plan for.
Reading silhouettes per cluster
A mean silhouette hides a lot. One tight cluster with a score near 0.9 can cover for another that is badly mixed. After you have a candidate k, look at the per-point scores grouped by cluster with silhouette_samples.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples
X, _ = make_blobs(n_samples=300, centers=4, random_state=7)
X = StandardScaler().fit_transform(X)
k = 4
km = KMeans(n_clusters=k, n_init=10, random_state=7).fit(X)
scores = silhouette_samples(X, km.labels_)
for j in range(k):
s = scores[km.labels_ == j]
negative = int((s < 0).sum())
print(f"cluster {j}: size={len(s):3d} mean={s.mean():.3f} min={s.min():.3f} negative={negative}")Things to look for in this output:
- A cluster whose mean is well below the overall mean may be the result of splitting one group, or of merging two.
- Many negative values in one cluster mean its points are closer to a neighbor than to their own center.
- Very different cluster sizes combined with similar means may be fine. Very different sizes combined with a low-scoring small cluster often means an outlier group.
A decision process
The last step matters. Sometimes no value of k looks good because the data is not shaped the way k-means expects. In that case the problem is the algorithm choice, not k. The next chapters cover when k-means works poorly and which alternatives to try.
When the two methods disagree
Disagreement is normal, and it carries information.
| Situation | Likely cause | What to do |
|---|---|---|
| Elbow suggests a smaller k than silhouette | Silhouette favors a finer split that is still well separated | Look at both clusterings and ask which is easier to explain or act on |
| Silhouette peaks at k=2 on data you expect to have more groups | Two large super-groups dominate the distances | Inspect k=2 and larger k, and consider hierarchical structure |
| No visible elbow, silhouette scores are all low | Little real cluster structure, or a shape k-means cannot model | Visualize in 2-D with PCA, and try another algorithm |
| Silhouette is nearly flat across k | The score cannot discriminate | Use stability checks or domain constraints instead |
Other criteria exist and are also built into scikit-learn. The Calinski-Harabasz index is the ratio of between-cluster to within-cluster variance, and higher is better. The Davies-Bouldin index measures cluster overlap, and lower is better. They are cheaper than silhouette because they avoid all pairwise distances, but they share the same bias toward compact, roughly spherical clusters.
Stability as an extra check
A good k should give similar clusters when the data is perturbed. You can test this by fitting k-means on two bootstrap samples, or two random halves, of the data. Then compare how the labels agree, using adjusted_rand_score from sklearn.metrics. If a candidate k produces very different partitions across resamples, the clusters at that k are probably not a real feature of the data.
Domain constraints come first
The statistical criteria say nothing about what you will do with the clusters. A retailer may want exactly five customer segments because the marketing team can run only five campaigns. A color-quantization task may need exactly 16 colors because of a palette limit. In those cases k is a requirement, and the diagnostics help you judge how much quality you give up. Report the choice and the reasoning, not only the number.
Common errors
- Comparing inertia across different scalings. Inertia depends on the units of the data. Only compare values from fits on the same preprocessed matrix.
- Picking k by lowest inertia. It always favors the largest k in the range.
- Using one initialization per k. The noise from local minima can create false elbows. Keep
n_initabove 1. - Scoring on unscaled data. The distances behind both inertia and silhouette are dominated by the largest-scale feature.
- Computing silhouette for k=1. This raises an error, because the score needs at least two clusters.
- Treating the best k as final. Check the per-cluster scores and the cluster sizes before accepting it.
Exercise
A colleague fits k-means for k from 2 to 10 on a scaled dataset. Inertia falls smoothly with no clear bend, and the mean silhouette peaks at k=3 with a score of 0.31. What should they conclude, and what would you do next?
Show answer
A smooth inertia curve means the elbow method gives no clear answer, and a mean silhouette of 0.31 indicates weak to moderate cluster structure. The k=3 peak is only a candidate. Next, inspect per-cluster scores with silhouette_samples to see whether any cluster has many negative values, and check cluster sizes. Run a stability check on resamples, and plot the data in 2-D with PCA to see whether the clusters are separated at all. If the structure is weak or non-spherical, try another algorithm or use a k that the application needs, and report the low silhouette honestly.
Exercise
Why can you not pick k by choosing the value with the lowest inertia, and why does the mean silhouette not have the same problem?
Show answer
Inertia never increases as k grows, and it reaches zero when k equals the number of samples, so the minimum is always at the largest k tried. The mean silhouette compares each point's distance to its own cluster with its distance to the nearest other cluster. Splitting a genuine cluster puts points close to a neighboring cluster, which lowers their silhouettes and the mean. The score therefore has an interior maximum rather than improving without limit.
Exercise
Write the one-line change that makes silhouette_score practical for a dataset with 200,000 rows, and say what you give up.
Show answer
Pass a subset size and a seed, for example silhouette_score(X, labels, sample_size=10000, random_state=0). The score is then computed on a random sample, so it is an estimate that varies slightly with the seed, but the cost drops from roughly 200,000 squared pairwise distances to 10,000 squared.