K-Means & Hierarchical Clustering
Cluster unlabeled data with centroids or dendrograms and validate cluster quality.
In plain words
K-means groups similar items around centres that keep moving to the middle of their group; hierarchical clustering joins the closest items step by step into a tree of groups.
Think of it like…
K-means is like placing k meeting points in a city and letting everyone walk to the nearest one, then moving each point to the centre of its crowd until nobody changes; hierarchical clustering is like building a family tree from the bottom up, joining the closest relatives first.
Where you’ve seen it
Six one-dimensional values 1, 2, 3, 10, 11, 12 with k = 2 and initial centroids 1 and 12: points 1, 2, 3 are closer to 1 and 10, 11, 12 to 12, so the new centroids are 2 and 11 and the assignments stop changing. WCSS = (1² + 0² + 1²) + (1² + 0² + 1²) = 4. With k = 1 the centroid is 6.5 and WCSS = 125.5; with k = 3 the best WCSS is 2.5. The elbow is at k = 2, where WCSS drops by 121.5 (97%), while k = 3 only gains 1.5. The silhouette of point 1 is (b − a) / max(a, b) with a = mean distance to its own cluster = (1 + 2) / 2 = 1.5 and b = mean distance to the other cluster = (9 + 10 + 11) / 3 = 10, so s = 8.5 / 10 = 0.85, a well-separated point. For 50,000 customers the team runs mini-batch k-means with standardised RFM features, k = 5 (silhouette 0.41), and uses Ward hierarchical clustering on a 5,000-row sample to confirm the structure (full hierarchical on 50,000 would need 1.25 billion pairwise distances, about 10 GB).
Words you’ll hear
- Centroid
- The mean point of a cluster.
- WCSS / inertia
- Sum of squared distances from points to their cluster centroid.
- Silhouette score
- (b − a)/max(a, b): how much closer a point is to its own cluster than to the next nearest.
- Linkage
- The rule for the distance between clusters in hierarchical clustering.
Visual diagram
Theory & deep dive
K-means in detail
Lloyd's algorithm: initialise k centroids (k-means++ picks them far apart, which gives better and more stable results than random), assign each point to the nearest centroid by Euclidean distance, recompute centroids as cluster means and repeat until no assignment changes. Each iteration cannot increase WCSS, so it converges, but only to a local optimum; run several restarts and keep the lowest inertia (n_init). Cost is O(n × k × d) per iteration, so it scales to millions of rows (use MiniBatchKMeans for streaming or very large data). In the six-point example the algorithm reaches centroids 2 and 11 in one update and WCSS 4.
Assumptions and failure modes: clusters are convex, roughly spherical and of similar size and density (k-means splits an elongated cluster or two nested rings badly), the metric is Euclidean so features must be standardised (and high-dimensional or sparse data may need PCA first), outliers drag centroids (consider k-medoids or removing anomalies) and k must be chosen. Use the elbow method (plot WCSS versus k and look for the bend: WCSS 125.5, 4, 2.5 for k = 1, 2, 3 shows a sharp elbow at 2), the silhouette score (average of s = (b − a)/max(a, b) over points, in [−1, 1]; higher means better separation), the gap statistic or stability under resampling. Always check that segments are interpretable and actionable.
Clusters {1, 2, 3} and {10, 11, 12}. Point 1: a = (|1 − 2| + |1 − 3|)/2 = 1.5; b = (9 + 10 + 11)/3 = 10; s = (10 − 1.5)/10 = 0.85, close to 1 (well clustered).
Hierarchical clustering and choosing between methods
Agglomerative clustering begins with n singleton clusters and repeatedly merges the two closest clusters; the result is a dendrogram whose vertical axis is the merge distance. Cutting at a height yields clusters, and large jumps in merge height suggest natural cluster counts. The linkage defines cluster distance: single (nearest pair) can chain unrelated points into long clusters; complete (farthest pair) favours compact clusters; average is a compromise; Ward merges the pair that increases total WCSS least and tends to give balanced, k-means-like clusters, making it the usual default for Euclidean data. Any metric works (cosine, Manhattan, Gower for mixed types), and the dendrogram gives multi-resolution insight (segments within segments).
The cost is the limiting factor: the distance matrix has n(n − 1)/2 entries (1.25 billion for 50,000 points, about 10 GB in float64) and time is O(n²) to O(n³), so it suits up to roughly 10,000 to 20,000 points; use sampling, then assign the remainder with a nearest-cluster rule, or use k-means for large data. Choose k-means when data is large, clusters are compact and you need speed and simple centroids to describe segments; choose hierarchical when n is moderate, you want to explore the structure at several levels or need a non-Euclidean metric; choose DBSCAN when clusters have arbitrary shapes or noise points exist. Validate with silhouette, stability and business tests, and profile the clusters by their feature means so each segment gets a name and an action.
Merges: 1+2 (increase in WCSS 0.5), then {1,2}+3, then 10+11, then {10,11}+12; the final merge of the two groups jumps the WCSS by about 121.5, so the dendrogram shows a huge gap and a cut there gives the 2 clusters.
How it works, step by step
Step 1 of 41. Prepare features
Select behavioural features, standardise them and handle outliers and skew (log transforms).
- Reduce
- dimensions if needed
When to use it & trade-offs
What it is
K-means partitions n points into k clusters by alternating two steps (Lloyd's algorithm): assign every point to its nearest centroid, then move each centroid to the mean of its points, until assignments stop changing. It minimises the within-cluster sum of squares (WCSS, inertia). Hierarchical (agglomerative) clustering starts with every point as its own cluster and repeatedly merges the closest pair according to a linkage rule (single, complete, average or Ward), producing a dendrogram you cut at a chosen height to get any number of clusters. Both need feature scaling, and both are judged with internal measures such as the elbow method and silhouette score plus the usefulness of the segments.
Why it matters: Clustering is the workhorse of segmentation (customers, products, documents) and exploratory analysis. K-means is fast and scales to millions of rows but assumes roughly spherical, similarly sized clusters; hierarchical clustering needs no pre-chosen k and gives a multi-resolution view but costs O(n²) memory. Knowing their assumptions, how to choose k and how to validate results prevents presenting arbitrary groupings as discoveries.
When to reach for it
- Customer, product and document segmentation
- Exploratory structure discovery
- Vector quantisation and feature engineering
When to avoid or be careful
- Clustering unscaled features
- Reporting one k-means run without restarts
- Presenting clusters as ground truth
Clustering methods
Strengths: Fast; simple centroids; scalable.
Watch out: Needs k; sensitive to scale and outliers; spherical assumption.
Strengths: No fixed k; dendrogram; flexible metrics.
Watch out: O(n²) memory and time; greedy merges are irreversible.
Strengths: Finds non-convex clusters and outliers.
Watch out: Sensitive to eps and varying densities.
Interview signals & numbers to know
When this topic comes up
- “How many clusters?”
- Elbow method and silhouette
- Dendrogram and linkage
- k-means++
- Customer segmentation
Benchmarks & rules of thumb
- 125.5 → 4 → 2.5
- WCSS for k = 1, 2, 3 in the example
- 0.85
- silhouette of point 1
- n(n − 1)/2
- pairwise distances in hierarchical clustering
Common mistakes & follow-ups
Common interview mistakes
- Choosing k only from the elbow without checking silhouette or usefulness.
- Applying k-means to categorical features with Euclidean distance.
- Running full hierarchical clustering on hundreds of thousands of points.
Likely interviewer follow-ups
- How do you choose k in k-means?
- What are the differences among linkage methods?
- When does k-means fail?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply K-Means & Hierarchical Clustering with data science interview Q&A and hands-on practice.