edSlash Labs  /  Machine Learning Lab  /  Unsupervised Learning  /  K-Means Clustering
Algorithm 01 · Unsupervised learning · Clustering

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.

Beginner friendly

The big idea

Find natural groups by bringing similar points together.

K = number of clustersChoose how many groups the algorithm should find

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.

K

The number of clusters you want the algorithm to find.

Centroid

The centre of a cluster, calculated using averages.

Assignment

Each point joins the cluster with the nearest centre.

Unsupervised

The algorithm learns without correct group labels.

Remember: K-Means discovers groups. It does not know what those groups mean until a person studies the results.

1. How does K-Means work?

It repeats two main steps until the groups stop changing.

The two steps

Assignment step

Measure the distance from every point to each centroid. Give the point to the nearest centroid.

Update step

Find the average position of the points in each cluster. Move the centroid to that average.

Repeat

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.

Important: the starting centroids matter. Different starting positions can sometimes lead to different final clusters.

2. Live K-Means playground

Change K and watch the algorithm assign points and move the centroids.

Interactive experiment

Cluster map

Coloured dots are data points. Diamond markers are centroids.

The axes show two numerical features. Real datasets may contain many more features.

Iteration0
Clusters3
Data points36
Within-cluster error—
Starting centroids are ready. Select “Next iteration” to begin.
Try K = 2, 3, 4, and 5. Notice how the groups and within-cluster error change.

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:

d = √((x₂ − x₁)² + (y₂ − y₁)²)

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ₓ = (x₁ + x₂ + … + xₙ) / n
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.

WCSS = Σ (distance from each point to its centroid)²
Smaller WCSS means points are closer to their own cluster centres. But adding more clusters usually reduces WCSS, so we also need a way to choose K.

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.

LearnerStudy hoursPractice quizzes
A11
B22
C21
D78
E87
F99

Step-by-step result

Choose two starting centres

For this example, start near learner A and learner D.

Assign the learners

A, B, and C are close to the first centre. D, E, and F are close to the second.

Calculate the new centres

Group 1 centre = (1.67, 1.33). Group 2 centre = (8, 8).

Check again

Repeating the assignment step keeps the same groups, so the algorithm has settled.

The group names do not mean good or bad. K-Means only finds groups based on the numbers. A person must decide what each group means.

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

Silhouette score

Checks whether points are close to their own cluster and far from other clusters.

Domain knowledge

Ask whether the groups make sense for the real problem.

Stability

Try different starting points and see whether similar groups appear.

Important: there is no single perfect K for every dataset. Use more than one clue.

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.

Why scale the data? K-Means uses distance. If one feature has much larger numbers than another, it can dominate the distance calculation. Scaling can help features contribute more fairly.

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.

0 of 10 answered

Mini challenge

Use the playground. Try K = 2, then K = 3, then K = 4. Can you explain why the within-cluster error changes?

Can you explain why a smaller WCSS does not always mean that a larger K is the best choice?