Learning path: Find Structure Without Labels: Clustering, PCA and Recommenders · Step 2 of 6
Choosing k for K-Means: the Elbow Method and the Silhouette Score
K-means always returns exactly k groups, even when k is wrong. Use the elbow plot and the silhouette score to pick k for 2,600 customers, then describe each group in plain words.
What you will learn
- Plot inertia for k = 1 to 8 and find the elbow
- Work out one point's silhouette by hand and match scikit-learn
- Pick k with silhouette_score
- Profile each cluster in plain words with groupby
Before you start
- K-Means Clustering
- Basic pandas and matplotlib
In K-Means Clustering we split our customers into four groups, but we picked four just by looking at the plot. K-means always gives you exactly k groups, even when k is wrong. So choosing k is your job. Two scores help: the elbow and the silhouette.
How many tables at a wedding?
You're planning a wedding with twelve guests. One table: way too crowded, strangers squeezed together. Twelve tables: every guest sits alone and friends are split up. Three tables: friends sit together and no table is wasted.
The guests are our customers and the tables are our clusters. We want the k where friends sit together.
The elbow: inertia for k = 1 to 8
We use the same 2,600 customers (the file is called Instagram visits clustering.csv in this notebook; it's the same data as customers.csv).
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import (
silhouette_samples, silhouette_score)
df = pd.read_csv("Instagram visits clustering.csv")
X = df.iloc[:, 1:] # visit score, spending rank
print(X.shape)
(2600, 2)
Our first score is inertia, the sum of squared distances from each point to its own centroid. Fit k-means for every k from 1 to 8 and keep it:
inertias = []
for k in range(1, 9):
km = KMeans(n_clusters=k, n_init=10,
random_state=42)
km.fit(X)
inertias.append(round(km.inertia_))
print(k, inertias[-1])
1 3985635
2 2079619
3 847025
4 440249
5 278408
6 251438
7 228196
8 208398
Inertia always falls as k grows. If every customer had its own cluster, it would be zero. So the lowest inertia is not the answer. We look for the bend.
plt.plot(range(1, 9), inertias, marker="o")
plt.xlabel("k (number of clusters)")
plt.ylabel("inertia")
plt.title("Elbow plot")
plt.show()

From 1 to 3 the line falls fast. After 5 it hardly moves: 278,408, 251,438, 228,196. That bend is the elbow, because the line looks like a bent arm. Here it's at 4 or 5. Honestly, the elbow isn't always sharp, so we ask a second score.
The silhouette: am I at the right table?
The silhouette asks every point one question: am I at the right table?
- a = my average distance to everyone at my own table.
- b = my average distance to the nearest other table.
- s = (b - a) / max(a, b), which always lands between -1 and 1.
One customer, by hand
Let's calculate it for customer 0, so there's no magic:
km = KMeans(n_clusters=4, n_init=10,
random_state=42)
labels = km.fit_predict(X)
P = X.to_numpy()
d = np.linalg.norm(P - P[0], axis=1)
own = labels == labels[0]
a = d[own].sum() / (own.sum() - 1)
others = [d[labels == c].mean()
for c in range(4) if c != labels[0]]
b = min(others)
s = (b - a) / max(a, b)
print("a =", round(a, 1), " b =", round(b, 1))
print("s =", round(s, 3))
print("sklearn:", round(
silhouette_samples(X, labels)[0], 3))
a = 23.2 b = 36.7
s = 0.368
sklearn: 0.368
d is the distance from customer 0 to everyone. For a we divide by own.sum() - 1 so the customer doesn't count its distance to itself. b is the smallest average distance to any other cluster. Our hand result, 0.368, matches silhouette_samples exactly. b is bigger than a, so customer 0 is at the right table.
The silhouette score for each k
silhouette_score averages the silhouette of all 2,600 customers. We start at k = 2, because with one cluster there's no other table to compare with.
scores = []
for k in range(2, 9):
km = KMeans(n_clusters=k, n_init=10,
random_state=42)
labels = km.fit_predict(X)
scores.append(silhouette_score(X, labels))
print(k, round(scores[-1], 3))
2 0.49
3 0.595
4 0.647
5 0.62
6 0.539
7 0.448
8 0.446
plt.bar(range(2, 9), scores)
plt.xlabel("k (number of clusters)")
plt.ylabel("silhouette score")
plt.show()

Unlike inertia, a higher silhouette is better, and the tallest bar wins: k = 4 with 0.647. The elbow said 4 or 5, the silhouette says 4. Two scores, one decision.
Profile each cluster
A cluster number like 0 or 2 means nothing to a shop owner. So we fit the final model with k = 4 and describe every group:
km = KMeans(n_clusters=4, n_init=10,
random_state=42)
df["cluster"] = km.fit_predict(X)
cols = ["Instagram visit score",
"Spending_rank(0 to 100)"]
profile = df.groupby("cluster")[cols].mean().round(1)
profile["customers"] = df["cluster"].value_counts()
profile.columns = ["visit", "spend", "customers"]
profile.reset_index()
cluster visit spend customers
0 0 83.2 19.9 1027
1 1 39.4 65.1 400
2 2 79.6 85.0 600
3 3 27.3 24.3 573
The scatter plot of this model is the same four groups you saw in K-Means Clustering. Now we can name them:
| Cluster | Visit | Spend | Customers | In plain words |
|---|---|---|---|---|
| 0 | 83.2 | 19.9 | 1,027 | Visit a lot, spend little |
| 1 | 39.4 | 65.1 | 400 | Visit rarely, spend well |
| 2 | 79.6 | 85.0 | 600 | Fans: visit a lot and spend a lot |
| 3 | 27.3 | 24.3 | 573 | Visit rarely, spend little |
Now the shop can talk to each group differently: a thank-you offer for the fans, a reminder for the rare visitors.
Common mistakes
- Picking the k with the lowest inertia. That's always the biggest k. Look for the bend.
- Running the silhouette with k = 1. There's no other cluster to compare with, so start at 2.
- Trusting one score alone. The elbow is often blurry; check it against the silhouette.
- Stopping at cluster numbers. Profile the groups so people can act on them.
Quick recap
| Score | What you look for | Our customers |
|---|---|---|
| Inertia (elbow) | Where the drop slows down | Bend at 4 or 5 |
| Silhouette | The highest average, -1 to 1 | 0.647 at k = 4 |
| Profile | Mean of each column per cluster | Fans, rare visitors and two mixed groups |
Try it yourself
Fit k = 5 and profile it. Which group from k = 4 was split in two? Does that split make sense to you?
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →K-Means Clustering: Find Groups in Data With No Labels
Next →Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
K-Means Clustering: Find Groups in Data With No Labels
How k-means finds groups without labels: the assign-update loop worked by hand on eight homes, then KMeans on 2,600 customers, bad random starts, k-means++ and why you scale first.
Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
Two more ways to find groups: agglomerative clustering builds a family tree of merges (the dendrogram), and DBSCAN grows clusters from crowds and leaves loners out as noise. Shown on eight homes, 2,600 customers and two moons.
Dimensionality Reduction with PCA: 13 Columns Down to 2
PCA squeezes many columns into a few new ones and keeps most of the information. Reduce 178 wines from 13 columns to 2, see why scaling comes first, pick the number of components and use PCA in a pipeline.
Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
Which items are bought together? Work out support, confidence and lift by hand on eight baskets, then let Apriori in mlxtend find 240 rules in 14,963 real grocery baskets.