Skip to content

Intermediate: machine learning · Clustering, dimensionality reduction and feature engineering · topic 38 of 62 · 35 min

Clustering with k-means

Explanation

Clustering groups similar examples without any labels. k-means picks k centre points (centroids), assigns every example to its nearest centroid, moves each centroid to the average of its group, and repeats until nothing changes. You choose k, often with the elbow method or the silhouette score.

Why cluster?

Often there is no label to predict. A supermarket chain has purchase data for 20 lakh loyalty-card holders and wants to understand its customers. Clustering finds natural groups, such as "weekly family shoppers", "late-night snack buyers" and "festival-only shoppers", so each group can get the right offers. This is unsupervised learning: the algorithm finds structure on its own.

The k-means loop

  1. Choose k, the number of clusters, and pick k starting centroids.
  2. Assign step: put each point in the cluster of its nearest centroid (Euclidean distance).
  3. Update step: move each centroid to the mean of the points assigned to it.
  4. Repeat the assign and update steps until the assignments stop changing.
python
points = [(1, 1), (1, 2), (2, 1), (8, 8), (9, 8), (8, 9)]
centroids = [(0, 0), (10, 10)]
# assign: the first three are nearer (0, 0), the last three nearer (10, 10)
# update: new centroids are the means of each group
group_a = points[:3]
print(tuple(round(sum(c) / 3, 2) for c in zip(*group_a)))
Shows (1.33, 1.33). The second centroid moves to (8.33, 8.33). One more assign step changes nothing, so k-means stops.
Think of it like this: Imagine placing k ice-cream carts on a beach. Each person walks to the nearest cart. Then each cart owner moves to the middle of their crowd. People re-pick their nearest cart, owners move again, and soon nobody changes cart. The carts are the centroids.

Choosing k

k-means always gives exactly k clusters, even if the data has no real groups. To choose k, try several values. Inertia is the total squared distance of points to their centroid; it always falls as k grows. The elbow method plots inertia against k and picks the point where the curve bends and extra clusters stop helping much. The silhouette score (from −1 to 1) measures how much closer points are to their own cluster than to the next one; higher is better. Business sense matters too: five segments a marketing team can act on beat twelve nobody understands.

python
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

for k in range(2, 7):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X_scaled)
    print(k, round(km.inertia_), round(silhouette_score(X_scaled, km.labels_), 3))
scikit-learn starts with the k-means++ method, which spreads the first centroids apart, and n_init runs it several times keeping the best. Shown only.

Things k-means assumes

  • Clusters are roughly round blobs of similar size. Long or curved shapes confuse it.
  • Features are on similar scales; scale them first (topic 4).
  • Every point belongs to some cluster, so outliers drag centroids around.
  • The result depends on the starting centroids, which is why several restarts are used.

Common mistakes

  • Not scaling, so "annual spend in rupees" decides everything and "visits per month" is ignored.
  • Treating clusters as truth. They are a useful summary; describe each with plain statistics and check they make sense.
  • Using k-means on categories directly. Distances between encoded categories are not meaningful; use other methods (for example k-modes) or careful encoding.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Clustering with k-means · 1/7

Clustering

Clustering finds groups in data without any labels.

Prefer a video by a teacher? Find free videos on “k means clustering explained elbow method silhouette” on YouTube ↗

In real life: Segmenting shoppers for a festive sale

Before a festive sale, a fashion retailer clusters customers on scaled features like orders per year, average basket value, share of discounted items and days since last purchase. Five clusters emerge, including "full-price loyalists" and "sale-only bargain hunters". Each gets a different message: early access for loyalists, a countdown reminder for bargain hunters. The clusters are re-run every quarter because shopping habits change.

Practice (0/2 done)

Task 1 · Code · Python

Write assign(points, centroids) that returns, for each point, the index of its nearest centroid by Euclidean distance. If two centroids are equally near, choose the smaller index.

Task 2 · Code · Python

Write kmeans(points, centroids) that runs k-means from the given starting centroids: repeat (assign each point to its nearest centroid, ties to the smaller index; move each centroid to the mean of its points, keeping the old centroid if a cluster is empty) until the assignments stop changing. Return the final centroids as a list of tuples rounded to 2 decimal places.

Quick quiz

Question 1

1.What kind of learning is clustering?

Question 2

2.In the update step of k-means, each centroid moves to…

Question 3

3.Why does inertia alone not tell you the best k?

Question 4

4.Why scale features before k-means?

Question 5

5.Which shape of clusters is hardest for k-means?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

What kind of learning is clustering?

Answer: Unsupervised

There are no labels; the algorithm finds groups itself.

In the update step of k-means, each centroid moves to…

Answer: The mean of the points assigned to it

The centroid is the average of its cluster.

Why does inertia alone not tell you the best k?

Answer: It always goes down as k goes up

More clusters always reduce inertia; look for the elbow or use silhouette.

Why scale features before k-means?

Answer: So a feature with big numbers does not dominate the distances

Distances depend on units.

Which shape of clusters is hardest for k-means?

Answer: Long, curved or very unequal clusters

k-means assumes roughly spherical, similar-sized clusters.

How does k-NN classify a new point?Related

Answer: It takes a vote among the k closest training points

The k nearest neighbours vote.

From k-nearest neighbours

A Deployment wants 3 replicas. You delete one of its pods by hand. What happens?Related

Answer: A new pod is created to get back to 3

The ReplicaSet controller sees 2 of 3 and creates a replacement. That is self-healing.

From Why Kubernetes, and how a cluster works

Which method labels outliers as noise and finds clusters of any shape?Related

Answer: DBSCAN

DBSCAN is density-based and marks sparse points as −1.

From Other clustering methods and dimensionality reduction

A weekly sales report over five years of data, run by the business team, is typical of...Related

Answer: OLAP

Big read-only analysis over history is OLAP.

From Theory questions you will be asked

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Clustering, dimensionality reduction and feature engineering” before its exam: Other clustering methods and dimensionality reduction, Encoding categories and dates, Scaling and transforming numbers, Feature selection, leakage and pipelines.
  2. Module 8 exam: Clustering, dimensionality reduction and feature engineering · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Neural networks and deep learning. 62 topics left in the course before the final exam.

← Previous: Choosing and explaining a model