Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathFind Structure Without Labels: Clustering, PCA and Recommenders
  1. 1
    K-Means Clustering: Find Groups in Data With No Labels
  2. 2
    Choosing k for K-Means: the Elbow Method and the Silhouette Score
  3. 3
    Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
  4. 4
    Dimensionality Reduction with PCA: 13 Columns Down to 2
  5. 5
    Association Rules and Market Basket Analysis: Support, Confidence, Lift and Apriori
  6. 6
    Recommender Systems: Item-Based Collaborative Filtering with Cosine Similarity
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Unsupervised Learning

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.

Chaand Sheikh

·27 November 2026Unsupervised Learning

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()
Elbow plot of inertia against k from 1 to 8. The line falls steeply from about 4 million at k = 1 to about 0.85 million at k = 3, bends around k = 4 and 5, then stays almost flat to k = 8.
The elbow plot: a fast drop up to k = 3, then the line bends and flattens around 4 or 5.

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.
Reading a silhouette value -1 0 1 wrong table right table on the border customer 0: s = 0.368 s = (b - a) / max(a, b) = (36.7 - 23.2) / 36.7
Close to 1: right table. Close to 0: on the border. Below 0: probably at the wrong table.

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()
Bar chart of the silhouette score for k from 2 to 8. The bars rise from 0.49 at k = 2 to the tallest bar, 0.647, at k = 4, then fall to about 0.45 at k = 7 and 8.
The tallest bar is k = 4.

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:

ClusterVisitSpendCustomersIn plain words
083.219.91,027Visit a lot, spend little
139.465.1400Visit rarely, spend well
279.685.0600Fans: visit a lot and spend a lot
327.324.3573Visit 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

ScoreWhat you look forOur customers
Inertia (elbow)Where the drop slows downBend at 4 or 5
SilhouetteThe highest average, -1 to 10.647 at k = 4
ProfileMean of each column per clusterFans, 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 →
← Previous
K-Means Clustering: Find Groups in Data With No Labels
Next →
Hierarchical Clustering and DBSCAN: Dendrograms, Linkage, eps and Noise
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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.

On this page
  • How many tables at a wedding?
  • The elbow: inertia for k = 1 to 8
  • The silhouette: am I at the right table?
  • One customer, by hand
  • The silhouette score for each k
  • Profile each cluster
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool
Go deeper with a course

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.