Part 07 / Topic 2 of 5
Choosing k
k is yours to pick, and the data can grade your choice. The silhouette score (−1 to 1) measures how much closer each point is to its own cluster than to the next one; higher is better.
# examples/01_k_means_finds_groups_the_silhouette.py
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=600, centers=4, cluster_std=1.0, random_state=7)
for k in [2, 3, 4, 5, 6]:
labels = KMeans(n_clusters=k, n_init=10, random_state=0).fit_predict(X)
print(f"k={k} silhouette={silhouette_score(X, labels):.3f}")
# k=2 silhouette=0.588
# k=3 silhouette=0.762
# k=4 silhouette=0.811
# k=5 silhouette=0.680
# k=6 silhouette=0.577
The data was generated with 4 centres; the silhouette peaks at k=4. On real data the peak is rarely this clean — treat the score as a guide, and the final judge is whether the clusters mean something to a human.
🧪 Quick quiz
- On data generated with 4 clusters, which k scored best?
Show the answer
k=4, silhouette 0.811 — the highest of the sweep. Silhouette ranges −1 to 1; higher means tighter, better-separated clusters.
Done here? The practice set for Part 7 — 4 exercises with solutions — is on the part page.