Skip to main content
LearnMLAcademy
Intermediate10 min read

K-Means Clustering

Cluster unlabelled data with K-Means, inertia curves, and centroid updates, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

K-Means Clustering

K-Means Clustering is an unsupervised learning algorithm that groups similar data points into K clusters without needing class labels.

K-Means in Simple Words

Imagine dots scattered on a page. K-Means repeatedly moves a few center points until each center sits near a group of nearby dots.

1

Choose K

How many groups?

2

Assign

Send each point to its nearest center

3

Move

Move each center to its cluster mean

4

Repeat

Stop when the solution stabilizes

Tiny Example: Group Customers by Two Features

CustomerVisits / MonthAverage Spend
A2₹500
B3₹650
C10₹3,000
D11₹3,200

With K = 2, K-Means may place A/B together and C/D together because their numerical patterns are closer. The algorithm does not know names such as “low-value” or “high-value”; a human interprets the clusters afterwards.

Scaling note: Visits and spend use very different units, so a real project should consider scaling before distance-based clustering. We return to this later on the page.

Unlike supervised algorithms such as Logistic Regression or Decision Trees, K-Means does not train from target labels. It searches for structure using the numerical features supplied to it.

K-Means is commonly considered for tasks such as customer segmentation, vector quantization/image compression, exploratory grouping, and other problems where compact numeric groups are useful. It is not automatically the right choice for every unlabeled dataset.

Even today, K-Means remains one of the foundational algorithms taught in Data Science and Machine Learning because it introduces the core idea of: Learning patterns without supervision.


Why K-Means Clustering Was Needed

Many machine-learning problems are supervised and use labeled datasets (for example, Email → Spam/Not Spam). But in many real-world situations, useful target labels are unavailable.

Huge amounts of raw data existed without predefined categories. For example:

  • Millions of customers without predefined groups
  • Medical records without diagnosis labels
  • User browsing patterns without classifications
  • Images without annotations

This creates a common unsupervised-learning question: Can we discover useful structure without predefined target labels? K-Means is one classic algorithm for exploring that kind of grouping.

Real-Life Analogy of K-Means Clustering

Imagine a teacher entering a classroom full of completely unknown students. The teacher does not know who studies well, who likes sports, who prefers art, or who enjoys science. After observing behavior for several days, the teacher naturally begins grouping students based on similarities (Sports enthusiasts, Quiet learners, Highly academic students, Creative students).

Notice something important:

Nobody explicitly provided class labels for these groups. K-Means follows a similar idea mathematically: it groups nearby numerical points. However, the resulting clusters are algorithmic groups, not guaranteed “natural” or meaningful categories; people still need to interpret them.


Core Concepts: What is "K-Means"?

What Does the Word "Clustering" Mean?

Clustering means Grouping similar data points together. The goal is:

  • Similar points → same cluster
  • Dissimilar points → different clusters

What Does the "K" Mean?

The letter K represents Number of clusters.

  • K = 2 → Create 2 clusters
  • K = 3 → Create 3 clusters
  • K = 5 → Create 5 clusters

The algorithm calculates the mean position of the points assigned to each cluster. That mean becomes the cluster center, called the centroid. K-Means then assigns each point to the nearest centroid under its distance objective.

Machine Learning Hierarchy

MACHINE LEARNING

  • ├─ Supervised Learning
    • ├─ Regression
    • └─ Classification
  • └─ Unsupervised Learning
    • └─ Clustering
      • └─ K-Means

Mathematical Goal & Distance

The K-Means objective is to minimize the sum of squared distances from every point to the centroid of its assigned cluster. This encourages compact clusters. It does not directly maximize the distance between different clusters.

Distance Measurement (Euclidean Distance)

Standard K-Means is based on squared Euclidean distance. To build intuition, the ordinary Euclidean distance between two points (x₁, y₁) and (x₂, y₂) is:

d = √[(x₂ - x₁)² + (y₂ - y₁)²]

Worked Example

Suppose Point A = (2, 3) and Point B = (6, 7).

Step 1: d = √[(6 - 2)² + (7 - 3)²]

Step 2: d = √[4² + 4²]

Step 3: d = √[16 + 16] = √32

Distance ≈ 5.66


Core Working of K-Means

K-Means alternates between two main operations: assign points to the nearest centroid and recompute each centroid as a mean. A typical workflow is: Choose K ➔ Initialize Centroids ➔ Assign Points ➔ Update Centroids ➔ Repeat.

Step 1 — Choose Number of Clusters (K)

The first step is selecting how many clusters should exist. For example, K = 3 means create 3 clusters.

Step 2 — Initialize Centroids

The algorithm needs starting centers. They may be initialized randomly, but practical implementations commonly use k-means++, which chooses spread-out starting centers to improve initialization.

Step 3 — Assign Points to Nearest Centroid

Each point calculates its distance to every centroid. Then the point joins the nearest cluster.

Suppose Centroid A distance = 2, Centroid B distance = 8.
The point joins Cluster A because it is closer.

Step 4 — Recalculate Centroids

After assignments, each centroid moves to the coordinate-wise mean of the points currently assigned to it.

Points: (2,2), (4,4), (6,2)

Mean x = (2 + 4 + 6) / 3 = 4

Mean y = (2 + 4 + 2) / 3 = 8 / 3 ≈ 2.67

New centroid ≈ (4, 2.67)

Step 5 — Repeat Iteratively

Again: Assign points ➔ Update centroids. Implementations stop when the centers change only within a small tolerance, or when a maximum number of iterations is reached. The resulting solution is a local optimum, so initialization can matter.


Objective Function & Choosing K

K-Means needs both an objective to optimize and a practical way to decide whether a chosen value of K is useful.

Within Cluster Sum of Squares (WCSS)

K-Means minimizes the Within-Cluster Sum of Squares (WCSS), called inertia in Scikit-learn. For a fixed K, smaller inertia means points are closer to their assigned centroids. However, inertia always tends to fall as K grows, so “lower” does not by itself prove that one K is the most meaningful choice.

Objective

WCSS = Σ ||xᵢ - μc(i)||²

For every data point xᵢ, measure its squared distance from the centroid μ of the cluster it belongs to, then add those values.

Worked Example of WCSS

Suppose a centroid = 5, and it contains points: 4, 5, 6.

  • (4 - 5)² = 1
  • (5 - 5)² = 0
  • (6 - 5)² = 1

Total WCSS: 1 + 0 + 1 = 2

Methods to Choose a Useful K

K is a modeling choice. A small K may merge patterns that are useful to separate, while a large K may create clusters that are too fragmented for the task. Methods such as elbow plots and silhouette analysis provide evidence, but they do not guarantee one universally “correct” K.

1. The Elbow Method

Plot inertia for several K values. Inertia falls as K increases, but sometimes the curve bends and additional clusters bring much smaller improvements. That bend can be treated as a candidate K, not a mathematical guarantee of the best real-world grouping.

K=1 (1000) ➔ K=2 (600) ➔ K=3 (300) [Elbow] ➔ K=4 (250)

2. Silhouette Method

The silhouette coefficient compares how close a point is to its own cluster with how close it is to the nearest other cluster. Scores range from -1 to 1: values near 1 indicate better separation, values near 0 indicate overlap/boundary-like placement, and negative values can indicate a point may fit another cluster better.

3. Gap Statistic & 4. Davies-Bouldin

Gap Statistic compares actual clustering vs random clustering.
Davies-Bouldin Index (DBI) measures cluster separation quality. Lower DBI means better clustering.

Elbow Method Visualization

Illustrative data: K=3 is a reasonable elbow candidate here. Real datasets may have a weak or ambiguous elbow.


Feature Scaling & When K-Means Fits the Data

Why Scaling Can Matter

K-Means is distance-based. A feature with much larger numeric units can dominate Euclidean distance.

Age difference = 5
Salary difference = 20,000

Raw distance may be driven mainly by Salary.

For real data, consider scaling comparable numeric features when their units differ substantially.

Cluster Shape Matters

K-Means works most naturally when groups can be represented reasonably well by centroids under Euclidean distance.

Better fit
•••    •••
compact, separated groups
Can struggle
◜••••◝
◟••••◞
curved / irregular structure

Initialization Matters

K-Means can converge to different local solutions from different starting centroids. k-means++ is a smarter initialization than choosing every center uniformly at random.

Scikit-learn can run K-Means from multiple initializations and keep the run with the lowest inertia. In the code below, n_init=10 is written explicitly so the teaching example behaves consistently across library versions.

Implementing K-Means in Python

K-Means Python Implementation

# Step 1 — Import libraries
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans

# Step 2 — Create a simple 2D teaching dataset
X, _ = make_blobs(
    n_samples=500,
    centers=3,
    n_features=2,
    random_state=42
)

# Step 3 — Fit K-Means
model = KMeans(
    n_clusters=3,
    init="k-means++",
    n_init=10,
    random_state=42
)
labels = model.fit_predict(X)

# Step 4 — Inspect the result
print("Number of clusters:", len(np.unique(labels)))
print("Inertia:", round(model.inertia_, 2))
print("Cluster sizes:", np.bincount(labels))

# Step 5 — Visualize clusters and centroids
plt.scatter(X[:, 0], X[:, 1], c=labels, s=20)
plt.scatter(
    model.cluster_centers_[:, 0],
    model.cluster_centers_[:, 1],
    marker="*",
    s=300,
    color="red"
)
plt.xlabel("Feature 1")
plt.ylabel("Feature 2")
plt.title("K-Means Clusters")
plt.show()

Expected printed output

Number of clusters: 3
Inertia: 955.65
Cluster sizes: [167 166 167]

Interpretation: The algorithm found three cluster labels because we requested K=3. Inertia is the sum of squared distances to the assigned centroids. The underscore in X, _ deliberately ignores the true blob labels because K-Means is being trained without them.

Important: Cluster numbers such as 0, 1 and 2 are arbitrary identifiers. Cluster 0 is not inherently “better” or “lower” than Cluster 1.


Advantages & Disadvantages

Advantages

  • Simple to understand and easy to implement.
  • Often computationally efficient for numeric data with a moderate number of clusters.
  • Can scale to large datasets; Scikit-learn also provides MiniBatchKMeans for larger workloads.

Disadvantages

  • Need to choose K manually in advance.
  • Sensitive to outliers (since it calculates the mean).
  • Sensitive to centroid initialization.
  • Can give unintuitive groups when clusters have strongly irregular shapes, very different sizes, or very different densities.

K-Means vs Hierarchical Clustering

FeatureK-MeansHierarchical
RepresentationCentroidsNested merge/split structure
Choose K before fitting?YesNot always; a dendrogram can be cut later
Dataset sizeOften practical for larger datasetsCan become expensive as sample count grows
Main outputFlat cluster assignmentHierarchy of relationships

Common Mistakes

  • Calling the elbow K “the true K”: an elbow is a heuristic clue, and some datasets have no clear elbow.
  • Ignoring feature units: distance-based clustering can be dominated by large-scale features.
  • Giving clusters meaning too early: labels 0, 1, 2 are arbitrary; interpret clusters only after examining their features.
  • Expecting K-Means to discover every shape: curved or strongly unequal-density groups may need another clustering method.
  • Trusting one initialization: different starting centers can lead to different local solutions.

Quick FAQ & What to Learn Next

Does K-Means need feature scaling?

Often yes when numerical features use very different units, because K-Means relies on Euclidean-distance geometry.

Is K=3 always correct when the elbow looks like 3?

No. Treat it as a candidate and combine the plot with silhouette analysis, domain usefulness, stability, and visual inspection when possible.

What if the groups are curved or have very different densities?

K-Means may be a poor fit. Compare it with methods such as DBSCAN or hierarchical clustering.

Final Summary

K-Means Clustering is one of the foundational algorithms in Unsupervised Machine Learning. It works by Creating centroids, Measuring distances, Grouping similar points, and Updating cluster centers iteratively.

The algorithm minimizes Within-Cluster Sum of Squares (WCSS/inertia), which favors compact groups around centroids. Practical work also involves choosing K, checking cluster quality, scaling features when necessary, and deciding whether centroid-shaped clusters match the structure of the data.

Most Important Insight to Remember:

"K-Means repeatedly assigns points to the nearest centroid and moves each centroid to the mean of its assigned points. Simple loop, powerful idea — but the clusters still need validation and human interpretation."

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "K-Means Clustering"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • K-means alternates point assignment and centroid recomputation.
  • It minimizes within-cluster squared distance, so scaling matters.
  • The number of clusters k must be selected.
  • Different initializations can reach different local solutions.
  • It struggles with irregular shapes, unequal density, and outliers.
  • Use inertia, silhouette, stability, and domain usefulness together.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
K-Means produces one very large cluster and two tiny ones. Most likely cause?
Question 2 of 4
What does inertia measure, and what is wrong with minimising it alone?
Question 3 of 4
K-Means fails to detect two interlocking crescent shapes. Why?
Question 4 of 4
How does the Silhouette Score evaluate clustering quality?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1K-Means produces one very large cluster and two tiny ones. Most likely cause?▼

Correct Answer: Poor initialisation — centroids happened to start in one region. Use K-Means++ initialisation and multiple restarts, keeping the best result by inertia

K-Means is sensitive to initialisation. K-Means++ probabilistically selects centroids far apart, dramatically reducing this problem.

2What does inertia measure, and what is wrong with minimising it alone?▼

Correct Answer: Sum of squared distances from each point to its nearest centroid. Problem: inertia always decreases as k increases — k=N gives inertia=0. Use the elbow method or Silhouette score to choose k meaningfully

k=N (each point is its own cluster) perfectly minimises inertia but is useless. The elbow method finds k where improvement plateaus meaningfully.

3K-Means fails to detect two interlocking crescent shapes. Why?▼

Correct Answer: K-Means defines clusters by proximity to a single centroid — it can only create convex Voronoi regions. Crescent shapes cannot be represented as nearest to a central point. DBSCAN handles non-convex shapes

The Voronoi diagram created by K-Means centroids always produces convex regions. Non-convex cluster shapes (rings, crescents, spirals) violate this geometric constraint.

4How does the Silhouette Score evaluate clustering quality?▼

Correct Answer: For each point: a=average distance to same-cluster points, b=average distance to nearest other-cluster points, Silhouette=(b-a)/max(a,b). Values near +1 mean well-clustered; near -1 mean possibly in wrong cluster

Silhouette score captures both cohesion (how tight clusters are) and separation (how far clusters are from each other). Average above 0.5 generally indicates meaningful cluster structure.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next