K-Means Clustering
Learn how a computer discovers groups in data without being given the answers first. Explore how points gather around cluster centres, then build clusters yourself in the live playground.
The big idea
Find natural groups by bringing similar points together.
K-Means is an unsupervised learning algorithm. It divides data points into K groups, called clusters. It uses the features of each point to decide which points are close to one another.
The algorithm is not given the correct group for each point. It finds groups by measuring distances and moving cluster centres.
At a glance
Four useful ideas to remember.
The number of clusters you want the algorithm to find.
The centre of a cluster, calculated using averages.
Each point joins the cluster with the nearest centre.
The algorithm learns without correct group labels.
1. How does K-Means work?
It repeats two main steps until the groups stop changing.
The two steps
Measure the distance from every point to each centroid. Give the point to the nearest centroid.
Find the average position of the points in each cluster. Move the centroid to that average.
Assign points again, then update the centres again. Stop when the groups no longer change much.
A simple way to picture it
Imagine placing K flags on a map. Each house joins the flag closest to it. Then each flag moves to the middle of the houses in its group. Repeat until the flags settle.
2. Live K-Means playground
Change K and watch the algorithm assign points and move the centroids.
Cluster map
Coloured dots are data points. Diamond markers are centroids.
The axes show two numerical features. Real datasets may contain many more features.
3. The mathematics behind K-Means
The algorithm uses distance, averages, and a measure of cluster error.
Distance between two points
For points (x₁, y₁) and (x₂, y₂), straight-line distance is:
The algorithm compares this distance to decide which centroid is nearest.
Finding the centroid
A centroid is the average position of all points in its cluster.
Cᵧ = (y₁ + y₂ + … + yₙ) / n
Calculate the average X and average Y separately. Together they give the new centre.
What is K-Means trying to reduce?
It tries to keep points close to the centroid of their own cluster. The total squared distance is called within-cluster sum of squares (WCSS), also known as inertia.
4. Worked example: grouping learners
Follow a small example with two features.
Example data
Each learner has two values: study hours and practice quizzes completed. Suppose we choose K = 2.
| Learner | Study hours | Practice quizzes |
|---|---|---|
| A | 1 | 1 |
| B | 2 | 2 |
| C | 2 | 1 |
| D | 7 | 8 |
| E | 8 | 7 |
| F | 9 | 9 |
Step-by-step result
For this example, start near learner A and learner D.
A, B, and C are close to the first centre. D, E, and F are close to the second.
Group 1 centre = (1.67, 1.33). Group 2 centre = (8, 8).
Repeating the assignment step keeps the same groups, so the algorithm has settled.
5. How do we choose the right K?
The best number of clusters is not always obvious.
The Elbow Method
Run K-Means with several K values and record WCSS. The error usually falls as K grows. Look for a bend where adding more clusters gives only a small improvement.
This chart uses the current sample data. It is a guide, not an automatic answer.
Other useful checks
Checks whether points are close to their own cluster and far from other clusters.
Ask whether the groups make sense for the real problem.
Try different starting points and see whether similar groups appear.
Too few clusters
Different groups may be pushed together, hiding useful patterns.
Too many clusters
Natural groups may be split into tiny groups that are hard to explain.
6. K-Means in Python
Scikit-learn provides KMeans, which handles the main steps for us.
Clustering with scikit-learn
Copy this example into a Python notebook.
# Install the libraries if needed:
# pip install numpy scikit-learn
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# Example data: study hours and practice quizzes
X = np.array([
[1, 1], [2, 2], [2, 1],
[7, 8], [8, 7], [9, 9]
])
# Scale features when their ranges are very different
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Create and train a K-Means model with two clusters
model = KMeans(n_clusters=2, random_state=42, n_init=10)
model.fit(X_scaled)
# Cluster number for each row
print("Cluster labels:", model.labels_)
# The centre of each cluster
print("Cluster centres:", model.cluster_centers_)
# Within-cluster sum of squares
print("WCSS / inertia:", model.inertia_)
The cluster labels are numbers such as 0 and 1. These numbers are group IDs, not rankings.
Useful Python terms
n_clusters sets K. fit() learns the clusters. labels_ gives each row's cluster number. cluster_centers_ gives the centroids. inertia_ gives WCSS.
7. Where is K-Means used in real life?
It can help find natural groups in many kinds of data.
Customer grouping
Group customers by shopping habits so a business can understand different types of shoppers.
Image compression
Group similar colours and use fewer colours to represent an image.
Document grouping
Group articles that discuss similar topics after turning text into numerical features.
Location planning
Find groups of nearby places or areas with similar activity patterns.
Strengths and limitations
Know when K-Means is useful—and when it may struggle.
Strengths
- Easy to understand and fairly quick.
- Works well for many compact, separated groups.
- Can handle many data points.
Limitations
- You must choose K before fitting.
- Starting centroids can change the result.
- Outliers can pull centroids away.
- It may struggle with curved or unevenly sized groups.
- Feature scaling can matter a lot.
8. Knowledge check
Answer one question at a time. Your score and explanations will appear after the final question.
Mini challenge
Use the playground. Try K = 2, then K = 3, then K = 4. Can you explain why the within-cluster error changes?