Intermediate: machine learning · Clustering, dimensionality reduction and feature engineering · topic 38 of 62 · 35 min
Clustering with k-means
Explanation
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
- Choose k, the number of clusters, and pick k starting centroids.
- Assign step: put each point in the cluster of its nearest centroid (Euclidean distance).
- Update step: move each centroid to the mean of the points assigned to it.
- Repeat the assign and update steps until the assignments stop changing.
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)))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.
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))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 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)
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.
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
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Other clustering methods and dimensionality reductionClustering, dimensionality reduction and feature engineering · same module
- Encoding categories and datesClustering, dimensionality reduction and feature engineering · same module
- Scaling and transforming numbersClustering, dimensionality reduction and feature engineering · same module
- Why Kubernetes, and how a cluster worksDevOps: Git, Docker, Kubernetes and CI/CD · Kubernetes fundamentals
- Theory questions you will be askedSQL and Databases · Interview questions and practice projects
- Services, Ingress and the Gateway APIDevOps: Git, Docker, Kubernetes and CI/CD · Kubernetes fundamentals
Questions people ask about this
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.
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.
A weekly sales report over five years of data, run by the business team, is typical of...Related
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
- 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.
- Module 8 exam: Clustering, dimensionality reduction and feature engineering · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Neural networks and deep learning. 62 topics left in the course before the final exam.