Chapter 3 — Sub-chapter 3.2

K-Means Clustering

The workhorse of unsupervised learning — discover how K-Means partitions data into meaningful groups by iteratively refining cluster centres, much like an engineer zoning a construction site into regions of similar soil properties.

40 min read 2 interactive demos 4 quiz questions

Sorting Without Labels

You are a geotechnical engineer on a large infrastructure project. The site investigation has produced 500 soil samples, each characterised by moisture content, liquid limit, plastic limit, grain size distribution, and dry density. Nobody has classified these samples yet. Your task: organise them into meaningful groups so that each zone of the site can be treated with the right foundation strategy.

You could eyeball spreadsheet rows for hours. Or you could let K-Means clustering do the heavy lifting — automatically partitioning those 500 samples into K distinct groups where samples within each group are as similar as possible. That is exactly what this sub-chapter teaches you to do.

K-Means is arguably the most widely used clustering algorithm in all of machine learning. Its elegance lies in its simplicity: initialise K cluster centres (centroids), assign each data point to the nearest centroid, recompute centroids as group averages, and repeat until convergence. Despite this simplicity, K-Means is remarkably effective across a huge range of practical applications, from market segmentation in business to soil classification in civil engineering.

In this sub-chapter, we will dissect every step of the algorithm, build intuition through civil engineering analogies, explore how to choose the right number of clusters, examine limitations, and interact with two hands-on demos that let you watch K-Means work in real time.

Prerequisites

This sub-chapter builds directly on Sub-chapter 3.1, where we introduced unsupervised learning fundamentals and clustering as a concept. You should understand what clustering means and why it differs from supervised classification. We will also reference Euclidean distance, so basic vector geometry is helpful.

What is K-Means?

K-Means is a partition-based clustering algorithm that divides a dataset of N data points into exactly K non-overlapping clusters. Each cluster is represented by its centroid — the arithmetic mean of all points assigned to that cluster. The algorithm's goal is to minimise the total within-cluster sum of squares (WCSS), also called inertia: the sum of squared distances between each point and its assigned centroid.

The Objective Function

K-Means seeks to minimise the following objective (inertia):

J = Σk=1K Σx ∈ Ck || x − μk ||2

Where Ck is the set of points assigned to cluster k, and μk is the centroid (mean) of cluster k. The double bars denote Euclidean distance. The algorithm minimises J by alternately assigning points to their nearest centroid and recomputing centroids. Convergence is guaranteed because each step can only decrease (or maintain) J.

The "K" in K-Means is a hyperparameter — a value you choose before running the algorithm. It tells the algorithm how many clusters to create. Choosing K wisely is one of the most critical decisions in clustering, and we will dedicate an entire section to it later.

Civil Engineering Analogy

K-Means is like placing K site offices on a construction site. Imagine you are managing a sprawling infrastructure project and need to position K temporary site offices so that every worker on site has the shortest possible walk to their nearest office.

You start by placing the offices at random locations. Then you ask each worker to go to the nearest office. Once everyone is assigned, you notice that some offices are too far from the workers they serve. So you move each office to the centre of its assigned group of workers. Workers re-evaluate and may switch to a different, now-closer office. You repeat this process until the offices stop moving. The final positions minimise the total walking distance — exactly like K-Means minimises WCSS.

The K-Means Algorithm Step by Step

K-Means follows a simple iterative procedure that converges to a local optimum. Let us walk through every step in detail, building intuition for what happens internally at each stage.

1

Choose K and Initialise Centroids

Decide on the number of clusters K. Then select K initial centroid positions. The simplest approach is random initialisation: pick K data points at random and use their coordinates as the starting centroids. A smarter approach is K-Means++, which spaces initial centroids far apart to avoid poor starting configurations.

In civil engineering terms, this is like randomly placing K survey flags across a construction site before deciding how to group soil samples by proximity.

2

Assign Each Point to the Nearest Centroid

For every data point in the dataset, compute the Euclidean distance to each of the K centroids. Assign the point to the cluster whose centroid is closest. After this step, every data point belongs to exactly one cluster, and each cluster has at least conceptually a set of assigned points (though some may be empty in edge cases).

Imagine telling every worker on site: "Walk to the nearest site office." Each worker evaluates distances and picks the closest one.

3

Recompute Centroids

For each cluster, compute the mean (average) of all points currently assigned to it. This new mean becomes the cluster's updated centroid. The centroid literally moves to the "centre of gravity" of its members.

If Cluster 2 contains points at coordinates (2, 3), (4, 5), and (6, 1), its new centroid becomes ((2+4+6)/3, (3+5+1)/3) = (4, 3). The site office relocates to the average position of all workers assigned to it.

4

Repeat Until Convergence

Go back to Step 2 and re-assign all points to the nearest (updated) centroid. Then recompute centroids again. Repeat this assign-update cycle until one of two stopping conditions is met:

  • No point changes its cluster assignment between iterations (full convergence).
  • Centroid movement falls below a threshold (approximate convergence).
  • A maximum number of iterations is reached (safety stop).

Each iteration strictly decreases (or maintains) the inertia J, so the algorithm is guaranteed to converge. However, it may converge to a local optimum that is not the global best — which is why initialisation matters so much.

Convergence Guarantee

K-Means always converges because the assignment step never increases the objective J (each point moves to its nearest centroid, reducing or maintaining its contribution to J), and the update step also never increases J (the mean minimises the sum of squared deviations). Since J is bounded below by zero and each step reduces it, the algorithm must stop in finite time.

Pseudocode: K-Means
function KMeans(data, K):
    centroids = initialise_randomly(data, K)
    repeat:
        // Assignment step
        for each point x in data:
            assign x to cluster with nearest centroid

        // Update step
        for each cluster k = 1 to K:
            centroid[k] = mean of all points assigned to cluster k

    until centroids do not change (or max iterations reached)
    return clusters, centroids

Initialisation Strategies

The choice of initial centroid positions dramatically affects the final result. Poor initialisation can lead to suboptimal clusterings, empty clusters, or slow convergence. Two primary strategies dominate practice.

Random Initialisation

The simplest approach: randomly select K data points from the dataset and use them as the initial centroids. This is fast and easy to implement, but it can produce wildly different results on different runs. If two initial centroids happen to land in the same dense region, one cluster may end up capturing most of the data while another captures almost none.

Mitigation: Run K-Means multiple times with different random seeds and keep the result with the lowest inertia J. Libraries like scikit-learn default to 10 random restarts (n_init=10).

K-Means++ Initialisation

K-Means++ (Arthur & Vassilvitskii, 2007) is a smarter initialisation that spreads centroids apart. The procedure is:

  1. Choose the first centroid uniformly at random from the data points.
  2. For each remaining data point, compute its distance to the nearest already-chosen centroid.
  3. Choose the next centroid with probability proportional to the squared distance — points far from existing centroids are more likely to be chosen.
  4. Repeat until all K centroids are selected.

This dramatically reduces the chance of poor starting positions and provably yields an initialisation that is O(log K) competitive with the optimal solution. It is the default in most modern implementations.

Civil Engineering Analogy

K-Means++ is like strategic placement of emergency stations on a highway network. Rather than dropping stations at random locations (which might cluster them all in one city), you place the first station, then position each subsequent station far from the existing ones. This ensures broad coverage from the start, reducing iterations needed to converge on optimal positions.

Choosing K: How Many Clusters?

K-Means requires you to specify K upfront. But in most real-world problems, the "correct" number of clusters is unknown. Choosing K too small forces dissimilar points into the same cluster. Choosing K too large fragments natural groups and introduces meaningless distinctions. Two widely used techniques help identify a good K.

The Elbow Method

Run K-Means for a range of K values (e.g., K = 1 to 10). For each K, record the inertia (WCSS). Plot inertia against K. As K increases, inertia always decreases (more clusters = smaller groups = lower within-cluster variance). Look for the "elbow" in the curve — the point where adding another cluster yields rapidly diminishing returns in inertia reduction.

Reading the Elbow Plot

The elbow point represents a balance between model complexity (more clusters) and explanatory power (lower inertia). Before the elbow, each additional cluster captures significant new structure. After the elbow, additional clusters provide only marginal improvement — you are essentially splitting existing groups rather than finding new ones.

In civil engineering terms, think of it like adding survey boreholes to a site. The first few boreholes reveal major soil layer changes. Beyond a certain number, additional boreholes confirm what you already know rather than uncovering new geology. The elbow is where you get the best return on investigation effort.

The Silhouette Method

The silhouette score measures how similar a point is to its own cluster compared to neighbouring clusters. For each data point i:

Silhouette Coefficient

For each point i, compute:

  • a(i) = average distance from point i to all other points in the same cluster (cohesion).
  • b(i) = average distance from point i to all points in the nearest neighbouring cluster (separation).

s(i) = (b(i) − a(i)) / max(a(i), b(i))

Values range from −1 to +1. A score near +1 means the point is well-matched to its own cluster and poorly matched to neighbouring clusters. Near 0 means the point sits on the boundary between clusters. Near −1 means the point may be assigned to the wrong cluster.

The average silhouette score across all data points provides a global quality metric. Run K-Means for multiple K values and choose the K that maximises the average silhouette score.

Practical Guidance

In practice, use both the elbow method and silhouette analysis together. The elbow gives a quick visual heuristic; the silhouette gives a quantitative score. When they agree, you can be confident in your choice of K. When they disagree, lean on domain knowledge — does the suggested K produce clusters that make physical sense for your engineering problem?

CE Application: Grouping Soil Samples

One of the most natural applications of K-Means in civil engineering is soil classification by measured properties. Rather than relying solely on traditional classification systems (like the Unified Soil Classification System), K-Means can discover data-driven groupings based on actual measured parameters from site investigations.

Scenario: Highway Embankment Investigation

A highway project requires earthworks along a 15 km corridor. Site investigation yields 400 soil samples with five measured properties: moisture content (%), liquid limit (%), plasticity index, percentage passing 75 μm sieve, and unconfined compressive strength (kPa).

Traditional classification would bin each sample into a USCS group. But K-Means can reveal more nuanced, site-specific groupings that reflect the actual variability of the corridor. For instance, it might discover that what USCS calls "CL" at this site actually contains two distinct sub-populations with very different moisture-strength relationships — information critical for embankment design.

1

Normalise the Features

Since moisture content (%) and UCS (kPa) have very different scales, normalise all features to zero mean and unit variance before clustering. Without normalisation, the feature with the largest numerical range dominates the distance calculations, and the clustering effectively ignores the smaller-scale features.

2

Run K-Means for Multiple K Values

Run K-Means with K = 2 through K = 8. Record the inertia and average silhouette score for each. The elbow plot suggests K = 4, and the silhouette analysis confirms it with a peak average score of 0.62.

3

Interpret the Clusters with Domain Knowledge

With K = 4, the engineer examines cluster centroids and discovers: Cluster A is a stiff, low-plasticity clay; Cluster B is a soft, high-moisture alluvial deposit; Cluster C is a well-graded granular material; and Cluster D is an intermediate silty clay. Each cluster maps to a distinct zone along the corridor, enabling differentiated design.

Python: Clustering Soil Samples
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import numpy as np

# Assume soil_data is (400, 5) array:
# [moisture, liquid_limit, PI, pct_passing_75um, UCS]
scaler = StandardScaler()
X = scaler.fit_transform(soil_data)

# Run K-Means with the elbow-method winner
kmeans = KMeans(n_clusters=4, init='k-means++', n_init=10,
                random_state=42)
labels = kmeans.fit_predict(X)

# Each sample now has a cluster label: 0, 1, 2, or 3
# Map clusters to engineering descriptions using centroids
centroids_original = scaler.inverse_transform(kmeans.cluster_centers_)
for k, c in enumerate(centroids_original):
    print(f"Cluster {k}: MC={c[0]:.1f}%, LL={c[1]:.1f}%, "
          f"PI={c[2]:.1f}, Pass75={c[3]:.0f}%, UCS={c[4]:.0f} kPa")

CE Application: Clustering Traffic Flow Patterns

Transportation engineers deal with enormous volumes of traffic sensor data. K-Means can identify distinct traffic flow regimes — patterns that repeat day after day — and support signal timing, capacity planning, and congestion management.

Scenario: Urban Intersection Analysis

An inductive loop detector at a major intersection records vehicle count, average speed, and occupancy (percentage of time the detector is occupied) every 15 minutes for 90 days. That yields 8,640 data points, each characterised by three features.

Running K-Means with K = 4 might reveal: Cluster 1 = free-flow conditions (high speed, low count, low occupancy); Cluster 2 = moderate congestion (reduced speed, higher count); Cluster 3 = heavy congestion (low speed, high occupancy); Cluster 4 = off-peak/nighttime (very low count and occupancy). Mapping clusters back to timestamps reveals which hours and days experience each regime.

Why K-Means Works Well Here

Traffic flow states tend to form compact, roughly spherical clusters in the (count, speed, occupancy) feature space. This is exactly the kind of structure K-Means is designed for. The clear separation between free flow, congestion, and off-peak makes K-Means an excellent first tool for this problem. If traffic patterns are more complex (e.g., non-spherical clusters or overlapping regimes), more advanced methods like DBSCAN or Gaussian Mixture Models may be needed.

Scaling Matters

Vehicle count might range from 0 to 200 per interval, speed from 5 to 80 km/h, and occupancy from 0 to 100%. Always standardise features before running K-Means. Without standardisation, the feature with the broadest numerical range dominates the distance metric, and the algorithm effectively clusters on that single feature alone.

Limitations of K-Means

K-Means is powerful but not universal. Understanding its limitations is essential for knowing when to use it and when to reach for alternatives.

Sensitivity to Initialisation

Because K-Means converges to a local optimum, the final clustering depends on the initial centroid positions. Two runs with different random seeds can produce very different results. This is especially problematic when clusters are not well separated.

Mitigation: Use K-Means++ initialisation and run the algorithm multiple times (e.g., n_init=10), keeping the result with the lowest inertia.

Requires Specifying K in Advance

You must decide the number of clusters before running the algorithm. In many engineering scenarios, the "true" number of groups is unknown. While the elbow method and silhouette analysis help, they do not always give a clear answer — especially when clusters have different sizes, densities, or degrees of overlap.

Alternative: Algorithms like DBSCAN or HDBSCAN determine the number of clusters automatically from the data's density structure.

Assumes Spherical, Equally Sized Clusters

K-Means uses Euclidean distance, which implicitly assumes clusters are spherical (isotropic) in feature space and roughly the same size. When clusters are elongated, irregularly shaped, or vastly different in size, K-Means can produce poor results — splitting large clusters or merging distinct but adjacent ones.

For example, if one soil type is abundant and another is rare, K-Means may split the abundant type into two clusters while absorbing the rare type into its larger neighbour.

Alternative: Gaussian Mixture Models (GMMs) can handle elliptical clusters of different sizes by modelling each cluster as a full covariance Gaussian.

Sensitive to Outliers

Because centroids are computed as means, a single extreme outlier can pull a centroid far from the bulk of its cluster. In site investigation data, outliers are common — a sample might be contaminated, a sensor might misread, or a genuinely unusual geological feature might be encountered.

Mitigation: Remove or cap outliers before clustering, or use K-Medoids (PAM), which uses medians instead of means and is therefore more robust to outliers.

Feature Scaling Dependency

K-Means relies on Euclidean distance. If features are on different scales (e.g., moisture content in % versus shear strength in kPa), the feature with the largest numeric range will dominate clustering decisions. Always standardise or normalise features before running K-Means.

When NOT to Use K-Means

Avoid K-Means when: clusters are not roughly spherical; the number of clusters is genuinely unknown and varies widely; the dataset contains many outliers; cluster sizes are vastly unequal; or features are categorical (K-Means needs numerical distances). In these cases, consider DBSCAN, hierarchical clustering, Gaussian Mixture Models, or K-Modes (for categorical data).

K-Means in the Clustering Landscape

K-Means is one tool in a rich toolkit of clustering algorithms. Understanding where it sits relative to others helps you choose the right method for your engineering problem.

Comparison Table

Feature K-Means DBSCAN Hierarchical
Requires K? Yes No Cut-off needed
Cluster shape Spherical Arbitrary Arbitrary
Handles noise? Poorly Well Depends
Scalability Excellent Good Limited
Interpretability High Moderate High (dendrogram)

Interactive Demo: Step-by-Step K-Means

This demo lets you control each iteration of K-Means manually. Generate random data points, initialise centroids, then step through the assign-update cycle one iteration at a time. Watch the centroids migrate and cluster assignments shift until convergence.

Step Through K-Means Iteration by Iteration

Click "Generate Data" to create sample points, then "Initialise" to place random centroids. Use "Step" to advance one full iteration (assign + update). Observe how centroids move and colours change.

Click "Generate Data" to begin. Then initialise centroids and step through each iteration.

Interactive Demo: Elbow Method Visualiser

See the elbow method in action. Generate data with a known number of natural clusters, then watch the inertia-vs-K plot build as K-Means runs for each K value. The elbow should appear near the true number of clusters.

Find the Elbow

Choose the number of true clusters in the data, generate it, and then run the elbow analysis. The plot shows inertia (WCSS) for K = 1 to 8.

Data Points
Inertia vs K (Elbow Plot)
Choose the true number of clusters, generate data, then run the elbow analysis to see the inertia curve.

Practical Workflow for K-Means in Engineering

Here is a step-by-step workflow for applying K-Means to a real civil engineering dataset, from raw data to actionable insights.

1

Collect and Clean Data

Gather measurements from site investigations, sensors, or databases. Handle missing values (impute or remove). Remove or cap obvious outliers that could distort centroids.

2

Feature Selection and Scaling

Select features relevant to your engineering question. Standardise all features to zero mean and unit variance. Consider whether dimensionality reduction (PCA) is needed if you have many correlated features.

3

Determine K

Run the elbow method and silhouette analysis for a range of K values. Cross-check with domain knowledge: does the suggested K make engineering sense? If the elbow is ambiguous, test the top 2-3 candidates.

4

Run K-Means and Validate

Run K-Means with the chosen K, using K-Means++ initialisation and multiple restarts. Examine cluster centroids: do they correspond to physically distinct groups? Visualise clusters in 2D projections. Check cluster sizes for severe imbalances.

5

Apply to Engineering Decisions

Map clusters back to the physical domain. Assign soil zones on site plans. Differentiate design parameters by cluster. Use cluster labels as a new feature in downstream supervised models if needed.

Common Pitfalls and How to Avoid Them

Forgetting to Scale Features

This is the most common beginner mistake. If one feature ranges from 0 to 1000 and another from 0 to 1, the first feature will dominate all distance calculations. The resulting clusters will effectively be one-dimensional groupings based on that single feature. Always standardise before clustering.

Running K-Means Only Once

A single run may converge to a poor local optimum. Always run multiple times with different initialisations and select the best result (lowest inertia). In scikit-learn, set n_init=10 or higher.

Blindly Trusting the Elbow

The elbow method does not always produce a clear elbow. Some datasets show a smooth curve with no obvious bend. In such cases, combine with silhouette analysis and, critically, use engineering judgement. If a geotechnical engineer knows the site has three distinct geological formations, K = 3 is defensible even if the elbow suggests K = 4.

Applying K-Means to Non-Spherical Data

If your data forms elongated, crescent-shaped, or nested clusters, K-Means will fail to capture the true structure. Visualise your data first (2D scatter plots or PCA projections) to check whether K-Means' spherical assumption is reasonable. If not, switch to DBSCAN, spectral clustering, or GMMs.

CE Application: K-Means for Site Zoning

K-Means is the go-to method for dividing a construction site into geotechnical zones.

Foundation Zoning

Cluster boreholes by bearing capacity, SPT-N, and soil type to define pile vs. shallow foundation zones across a large project site.

Water Quality Stations

Group monitoring wells by chemical signature (Naâº, Clâ», SO₄²â») to identify recharge zones vs. saline intrusion areas using the elbow method for optimal k.

Land-Use Classification

Satellite spectral bands → K-Means → land-use map. Essential for watershed delineation, flood plain mapping, and environmental impact assessments.

Engineer's Tip: In geotech, always use domain knowledge to validate cluster count — 3 clusters matching "soft clay / stiff clay / sand" is better than blindly trusting the elbow curve.
Try it interactively

Run k-means on real soil-sample data

Open the playground and execute scikit-learn's KMeans on the curated soil-sample snippet — fit, assign cluster labels and plot the centroids inline.

Open Playground

Test Your Understanding

Check your grasp of K-Means clustering with these four questions. Each reinforces a core concept from this sub-chapter.

Quick Check 1

What does the "K" in K-Means represent?

Quick Check 2

Why is feature scaling (standardisation) important before running K-Means?

Quick Check 3

In the elbow method, what does the "elbow" point represent?

Quick Check 4

Which is a fundamental limitation of K-Means?

Key Takeaways

What You Should Remember

  • K-Means partitions N data points into K clusters by iteratively assigning points to their nearest centroid and recomputing centroids as cluster means.
  • The algorithm minimises the within-cluster sum of squares (inertia) and is guaranteed to converge, but only to a local optimum.
  • Initialisation matters: use K-Means++ and multiple restarts to mitigate sensitivity to starting positions.
  • Choose K using the elbow method (plot inertia vs K) and silhouette analysis (measure cluster cohesion vs separation), combined with domain knowledge.
  • Always standardise features before running K-Means to prevent scale-dependent distortions.
  • K-Means assumes spherical, equally sized clusters and is sensitive to outliers. Use DBSCAN, hierarchical clustering, or GMMs when these assumptions are violated.
  • In civil engineering, K-Means is valuable for soil classification, traffic flow analysis, structural health monitoring, and any scenario where unlabelled data needs to be grouped by similarity.
Looking Ahead

In the next sub-chapter, we explore hierarchical clustering, which does not require specifying K in advance and produces a dendrogram that reveals the nested structure of clusters at every level. This addresses one of K-Means' key limitations and provides a complementary perspective on grouping data.

Real-world case study · K-means on freeway loop-detector data

Caltrans PeMS — K-means clustering finds the three traffic regimes that drive ramp metering

The Caltrans PeMS system streams 5-minute speed/flow/occupancy from ~40,000 loop detectors across California's freeways. K-means clustering in (q, v, k) space recovers the textbook Greenshields regimes — free-flow, congested, jammed — that drive ramp-metering, VSL and incident-detection decisions.

0Loop detectors
0Traffic regimes
0Sample interval
0Continuous archive

Operations needs to label every 5-minute detector observation as free-flow, congested or jammed so it can trigger the right control action: ramp metering, variable speed limits, or alternate-route advisories. Hard thresholds (e.g. "speed < 40 mph") fail because the boundary shifts with weather, day-of-week and grade.

  • Per-detector calibration of thresholds is impossible at 40,000 detectors.
  • Manual labelling 20 years of 5-minute records is similarly impossible.
  • The model needs to be transparent enough that traffic engineers trust it for control.

Published Caltrans / PATH methodology applies K-means clustering with K = 3 to each detector's (flow q, speed v, occupancy k) cloud.

  • Features: the three fundamental variables of macroscopic traffic flow theory.
  • Why K = 3: matches Greenshields' free-flow / congested / jammed regimes — the centroid is physically meaningful.
  • Per-detector fitting: centroids adapt to local geometry (grade, lane count, on-ramp density).
  • Output: every 5-minute reading gets a regime label; PeMS dashboards colour-code time-space plots in real time.

K-means is a 60-year-old algorithm. Paired with the fundamental diagram of traffic flow it controls one of the largest road networks on Earth.

  • PeMS regime classifications feed Caltrans ramp-metering algorithms and Variable Speed Limit deployments on I-5, I-80 and the Bay Area corridors.
  • Public PeMS dashboards expose the same labels to MPOs, researchers and travel-time service providers.
  • The methodology has been adopted (with K=3 or K=4 variations) by Florida DOT, Minnesota DOT and Transport for London.
  • Domain physics picks K. Don't waste an elbow plot when the discipline already tells you "there are three regimes".
  • Cluster per location. One global model loses to 40,000 small ones when the geometry differs.
  • Operationalise via dashboards. The win wasn't the algorithm — it was the colour-coded time-space plot that engineers could read at a glance.