To choose the number of clusters for K-means in Python, fit KMeans(n_clusters=k) for a range of k and plot two things: inertia_ (the elbow method) and silhouette_score(X, labels). Pick the k where inertia stops dropping sharply and the silhouette score peaks. When the two disagree, a silhouette plot, one bar group per cluster made with silhouette_samples, shows which clusters are weak. The code below targets scikit-learn 1.9.
Quick Example
This generates four blobs of different spread with make_blobs, fits K-means for k from 2 to 9, and draws both charts side by side. It needs no downloads.
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=900, centers=4, cluster_std=[1.0, 1.4, 0.9, 1.2],
center_box=(-9, 9), random_state=7)
ks = range(2, 10)
inertia, sil = [], []
for k in ks:
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
inertia.append(km.inertia_)
sil.append(silhouette_score(X, km.labels_))
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.2))
ax1.plot(ks, inertia, marker="o", color="#0f766e", lw=2)
ax1.set(xlabel="Number of clusters (k)", ylabel="Inertia (within-cluster sum of squares)",
title="Elbow method")
best_k = list(ks)[int(np.argmax(sil))]
ax2.plot(ks, sil, marker="o", color="#ea580c", lw=2)
ax2.axvline(best_k, color="#94a3b8", ls="--")
ax2.set(xlabel="Number of clusters (k)", ylabel="Mean silhouette score",
title="Silhouette score")
fig.tight_layout()
print("best k", best_k)

Inertia falls from 23,844 at k=2 to 7,218 at k=3 and 2,251 at k=4, then only creeps down to 1,298 by k=9. The bend is at 4. The silhouette score agrees: it peaks at 0.759 for k=4, against 0.735 for k=3 and 0.670 for k=5. The data really has four clusters, so this is the easy case. Real data is rarely this clean.
How the Elbow Method Works
K-means minimizes inertia, the sum of squared distances from each point to its cluster center. Inertia always goes down as k grows, down to zero when every point is its own cluster, so you can't just take the minimum. You look for the "elbow": the k after which each extra cluster buys much less than the one before.
In the chart above, going from 3 to 4 clusters removes about 5,000 units of inertia. Going from 4 to 5 removes about 280. That sudden change in slope is the signal. When the curve bends gradually, with no clear corner, the elbow method won't give you an answer and you need another criterion.
How to Read the Silhouette Score
For each point, the silhouette coefficient compares two distances: a, the mean distance to the other points in its own cluster, and b, the mean distance to the points in the nearest other cluster. It is (b - a) / max(a, b):
- Near 1: the point sits well inside its cluster, far from the neighbors.
- Near 0: the point is on the border between two clusters.
- Negative: the point is probably in the wrong cluster.
silhouette_score(X, labels) returns the mean over all points, and higher is better. Unlike inertia it doesn't automatically improve with more clusters, so it has a real peak. It costs O(n²) distance computations, so on large data pass sample_size= (and random_state=) to score a subsample.
Silhouette Plot: See Every Cluster at Once
A single average hides how each cluster is doing. silhouette_samples(X, labels) returns the coefficient for every point, and plotting them sorted within each cluster gives the classic "knife" plot. Cluster thickness is its size, and the dashed line is the overall mean.
from sklearn.metrics import silhouette_samples
fig, axes = plt.subplots(1, 3, figsize=(12, 4.4), sharex=True)
colors = plt.cm.Set2(np.linspace(0, 1, 8))
for ax, k in zip(axes, [3, 4, 6]):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
s = silhouette_samples(X, km.labels_)
avg = silhouette_score(X, km.labels_)
y_lo = 10
for c in range(k):
vals = np.sort(s[km.labels_ == c])
ax.fill_betweenx(np.arange(y_lo, y_lo + len(vals)), 0, vals,
facecolor=colors[c], edgecolor=colors[c])
ax.text(-0.27, y_lo + len(vals) / 2, str(c), va="center", fontsize=9)
y_lo += len(vals) + 10
ax.axvline(avg, color="#dc2626", ls="--")
ax.set(title=f"k = {k} (mean {avg:.2f})", xlabel="Silhouette coefficient",
yticks=[], xlim=(-0.3, 1))
axes[0].set_ylabel("Cluster")
fig.tight_layout()

Three things to check in these plots:
- Every cluster should reach past the mean line. At
k=4all four clusters reach the dashed line or pass it (cluster maximums run from 0.76 to 0.89). Atk=6clusters 0, 1, 4 and 5 top out between 0.48 and 0.55, no further than the mean line, and their own means are only 0.28 to 0.37. - Widths should be similar. At
k=3the orange cluster (index 1) is has 449 points against about 225 in each of the others, because it merges two real groups. Its mean silhouette is the lowest of the three at 0.63, even though the overall mean (0.73) looks fine. - Negative values mean misassigned points.
k=4has none.k=6has 10 points below zero, all in clusters 0 and 1, where real groups were cut in half.
Even a good overall score can hide a bad cluster, which is why this plot is worth the extra code.
What the Clusters Look Like at Each k

At k=3 the two upper-left blobs share one center that sits in the gap between them. At k=6 two of the real groups are each cut by an arbitrary line. Both mistakes are visible in the scores before you ever plot the points, which matters because you can't scatter-plot data with 30 features.
When the Elbow and Silhouette Disagree
They will on real data. Some guidance:
| Situation | What to do |
|---|---|
Sharp elbow and a silhouette peak at the same k |
Take it. |
| Clear silhouette peak, vague elbow | Trust the silhouette, then check the silhouette plot for weak clusters. |
| Flat silhouette scores (all around 0.2 to 0.3) | The data may not have cluster structure. Any k is a partition, not a discovery. |
Several k with similar scores |
Choose the one that is useful: a handful of segments a team can act on beats the one with 0.01 higher silhouette. |
Practical Tips
- Scale your features first. K-means uses Euclidean distance, so a column in dollars will swamp one in years. Put
StandardScalerahead ofKMeansin aPipelinebefore computing either metric. - Set
n_initexplicitly. K-means depends on its random starts. In scikit-learn 1.9n_initdefaults to"auto", which runs 1 initialization with the defaultk-means++seeding.n_init=10costs more but gives more stable curves. - Use
random_state. Otherwise the elbow plot changes slightly on every run. - Silhouette assumes round clusters. It favors compact, similarly sized, convex groups, the same shape K-means finds. For elongated or nested shapes, K-means and the silhouette are both the wrong tools. Try
DBSCANorGaussianMixture. - Don't treat the peak as truth. These scores say which
kfits the geometry best, not which segmentation answers your business question.