2.5.1Unsupervised Learning

K-Means clustering algorithm

2,432 words11 min readdifficulty · medium6 backlinks

What is K-Means?

WHY this objective? We want clusters where points are tightly packed around their center. Minimizing squared distances penalizes outliers heavily (quadratic penalty) and makes the math tractable for gradient-based reasoning.


The Algorithm: Derivation from First Principles

GOAL: Partition data {x1,x2,...,xn}\{x_1, x_2, ..., x_n\} into KK clusters to minimize total variance.

Step 1: Why Centroids?

If we fix cluster assignments, what's the best representative point for cluster CkC_k?

Minimize: xiCkxiμk2\sum_{x_i \in C_k} ||x_i - \mu_k||^2 with respect to μk\mu_k

Take the derivative and set to zero: μkxiCkxiμk2=xiCk2(xiμk)(1)=0\frac{\partial}{\partial \mu_k} \sum_{x_i \in C_k} ||x_i - \mu_k||^2 = \sum_{x_i \in C_k} 2(x_i - \mu_k)(-1) = 0

xiCk(xiμk)=0\sum_{x_i \in C_k} (x_i - \mu_k) = 0

xiCkxi=Ckμk\sum_{x_i \in C_k} x_i = |C_k| \mu_k

μk=1CkxiCkxi\mu_k = \frac{1}{|C_k|} \sum_{x_i \in C_k} x_i

RESULT: The optimal representative is the mean (average) of all points in the cluster. This is why we call them "centroids."

Step 2: Why Nearest-Neighbor Assignment?

If we fix centroids, which cluster should point xix_i join?

Minimize: The contribution of xix_i to the total objective JJ

Point xix_i should belong to cluster kk^* where: k=argmink{1,...,K}xiμk2k^* = \arg\min_{k \in \{1,...,K\}} ||x_i - \mu_k||^2

WHY? Each point independently choses the centroid that minimizes its own squared distance. This gredy assignment is optimal when centroids are fixed.

Step 3: The Lloyd's Algorithm

These two steps are coupled: better assignments lead to better centroids, which lead to better assignments. We alternate:

Initialize: Randomly select KK points as initial centroids {μ1,...,μK}\{\mu_1, ..., \mu_K\}

Repeat until convergence:

  1. Assignment Step: For each point xix_i, assign to nearest centroid: ci=argminkxiμk2c_i = \arg\min_{k} ||x_i - \mu_k||^2

  2. Update Step: Recompute each centroid as the mean of assigned points: μk=1CkxiCkxi\mu_k = \frac{1}{|C_k|} \sum_{x_i \in C_k} x_i

Convergence: Stop when assignments no longer change (or centroids move less than threshold ϵ\epsilon)

WHY does this converge? Each step decreases (or keeps constant) the objective JJ:

  • Assignment step: Points move to closer centroids → JJ decreases
  • Update step: Centroids move to the mean of their cluster → JJ decreases (from our derivative proof)
  • J0J \geq 0 is bounded below
  • By monotone convergence theorem, algorithm must converge

IMPORTANT: Convergence is to a local minimum, not necessarily global. Different initializations can yield different results.


Worked Examples

Data: A=(1,1),B=(2,1),C=(5,5),D=(6,6)A=(1,1), B=(2,1), C=(5,5), D=(6,6) Goal: Find 2 clusters

Iteration 0(Initialize):

  • Random centroids: μ1=(1,1),μ2=(5,5)\mu_1 = (1,1), \mu_2 = (5,5)

**Iteration 1:*Assignment:

  • A=(1,1)A=(1,1): d(μ1)=0,d(μ2)=32d(\mu_1)=0, d(\mu_2)=\sqrt{32} → Cluster 1
  • B=(2,1)B=(2,1): d(μ1)=1,d(μ2)=32d(\mu_1)=1, d(\mu_2)=\sqrt{32} → Cluster 1
  • C=(5,5)C=(5,5): d(μ1)=32,d(μ2)=0d(\mu_1)=\sqrt{32}, d(\mu_2)=0 → Cluster 2
  • D=(6,6)D=(6,6): d(μ1)=50,d(μ2)=2d(\mu_1)=\sqrt{50}, d(\mu_2)=\sqrt{2} → Cluster 2

Update:

  • μ1=(1,1)+(2,1)2=(1.5,1)\mu_1 = \frac{(1,1)+(2,1)}{2} = (1.5, 1)
  • μ2=(5,5)+(6,6)2=(5.5,5.5)\mu_2 = \frac{(5,5)+(6,6)}{2} = (5.5, 5.5)

Iteration 2:

Assignment: (Check distances again)

  • All assignments remain the same

Converged! Final clusters: {A,B}\{A, B\} and {C,D}\{C, D\}

WHY THIS STEP? Each distance calculation uses Euclidean metric because we're minimizing squared distances. The update step averages coordinates component-wise because the mean minimizes sum of squared deviations.


Problem: Cluster 100 customers by [spending, frequency]

# Pseudocode with reasoning
data = load_customers()  # Shape: (100, 2)
K = 3
 
# Initialize: K-Means++ (smarter than random)
centroids = [random_point()]
for in range(K-1):
    # Pick next centroid far from existing ones
    distances = [min(dist(p, c) for c in centroids) for p in data]
    centroids.append(weighted_random(data, distances))
 
for iteration in range(max_iters):
    # Assignment: Vectorized for speed
    distances = cdist(data, centroids)  # Shape (100, 3)
    labels = argmin(distances, axis=1)   # Shape (100,)
    # Update
    new_centroids = []
    for k in range(K):
        cluster_points = data[labels == k]
        new_centroids.append(mean(cluster_points, axis=0))
    
    if converged(centroids, new_centroids):
        break
    centroids = new_centroids

WHY THESE CHOICES?

  • K-Means++ initialization: Spreads initial centroids out → faster convergence, avoids bad local minima
  • Vectorization: cdist computes all pairwise distances at once → 100× faster than loops
  • Convergence check: Compare centroid movement, not assignments → more stable stopping criterion

Common Mistakes & How to Fix Them

The reality: K-Means converges to a local minimum, which depends on initialization. Different random starts give different results.

Steel-man: The algorithm does optimize the WCSS objective perfectly given the starting point. The issue is the objective landscape has many valleys.

Fix:

  • Run K-Means multiple times with different initializations (sklearn default: 10 runs)
  • Use K-Means++ initialization (provably better than random)
  • Report the solution with lowest final WCSS

The reality: K-Means assumes spherical clusters of similar size. It fails on:

  • Elongated/elliptical clusters
  • Crescent or ring shapes
  • Clusters of very different densities

Steel-man: For data generated from spherical Gaussian distributions, K-Means is actually optimal (it's the MLE solution).

Fix:

  • Preprocess: Standardize features if scales differ
  • Use DBSCAN or spectral clustering for non-convex shapes
  • Transform data (e.g., kernel trick) to make clusters more spherical

The reality:

  • WCSS always decreases as KK increases (at K=nK=n, WCSS=0)
  • No universal "correct" K—it's domain-dependent

Steel-man: Systematic search is valuable, but you need the right metric.

Fix:

  • Elbow method: Plot WCSS vs K, look for "elbow" where improvement slows
  • Silhouette score: Measures how similar points are to their own cluster vs. others
  • Domain knowledge: Sometimes K is known (e.g., customer segments)
  • Gap statistic: Compare WCSS to null distribution

Computational Complexity

Time per iteration:

  • Assignment step: O(nKd)O(nKd) — compute nn points × KK centroids × dd dimensions
  • Update step: O(nd)O(nd) — sum over nn points, dd dimensions

Total: O(IKnd)O(IKnd) where II = number of iterations

Space: O((n+K)d)O((n+K)d) — store data and centroids

In practice: II is typically small (<100) and KnK \ll n, so K-Means scales well to large datasets.

WHY this complexity? The assignment step is the bottleneck: we compute nKnK distances. Advanced implementations use KD-trees or ball trees to reduce this when dd is small.


The Math Behind Convergence

Claim: Each iteration decreases JJ (or keeps it the same), so K-Means converges.

Proof: Let J(t)J^{(t)} be the objective at iteration tt.

After assignment step at iteration t+1t+1: Jassign(t+1)J(t)J_{\text{assign}}^{(t+1)} \leq J^{(t)} because each point moves to the nearest centroid (or stays), which cannot increase its distance.

After update step: J(t+1)Jassign(t+1)J^{(t+1)} \leq J_{\text{assign}}^{(t+1)} because μk=argminmuxiCkxiμ2\mu_k = \arg\min_mu \sum_{x_i \in C_k} ||x_i - \mu||^2 (proved earlier).

Therefore: J(t+1)J(t)J^{(t+1)} \leq J^{(t)}

Since J0J \geq 0 and there are finitely many possible labelings (at most KnK^n), the algorithm must converge. \square

CAVEAT: Convergence is to a local minimum. The global minimum is NP-hard to find.


Extensions and Variations

  1. K-Means++: Smart initialization that spreads initial centroids P(choose xi)D(xi)2P(\text{choose } x_i) \propto D(x_i)^2 where D(xi)D(x_i) = distance to nearest existing centroid

  2. Mini-Batch K-Means: Use random subsets of data each iteration → faster for huge datasets

  3. Soft K-Means (Fuzzy C-Means): Allow partial membership: p(Ckxi)=eβxiμk2jeβxiμj2p(C_k | x_i) = \frac{e^{-\beta ||x_i - \mu_k||^2}}{\sum_j e^{-\beta ||x_i - \mu_j||^2}}

  4. K-Medoids (PAM): Use actual data points as centers (robust to outliers)


Recall Explain to a 12-Year-Old

Imagine you have a bag of different colored candies all mixed up, but you don't know which colors they are beforehand—they just look like random candies. K-Means is like playing a game where:

  1. You put down K different boxes randomly in the pile
  2. Each candy walks to the nearest box
  3. You move each box to the center of all the candies that chose it
  4. Repeat steps 2-3 until the boxes stop moving

The boxes are "learning" where the groups of similar candies naturally are! The candies in the same box end up being similar to each other, even though you never told the algorithm which candies should go together.

The tricky part is you have to decide how many boxes (K) to use at the start. Too few boxes and you squish different types together. Too many boxes and you split up candies that are actually the same type.


"Converge but Local" — It stops moving, but might not be the best answer overall

K-Means = K-Averages — Centroids are literally means (averages), not medians or modes

"Spherical, Similar Size" — The two S's that describe what K-Means likes


Connections


#flashcards/ai-ml

What is the objective function that K-Means minimizes? :: Within-cluster sum of squares (WCSS): J=k=1KxiCkxiμk2J = \sum_{k=1}^{K} \sum_{x_i \in C_k} ||x_i - \mu_k||^2

Why is the cluster representative called a "centroid"?
Because the optimal representative that minimizes squared distances is the mean (center of mass) of all points in the cluster, proven by taking the derivative of WCSS and setting it to zero.
What are the two alternating steps in K-Means?
(1) Assignment: assign each point to the nearest centroid; (2) Update: recompute each centroid as the mean of its assigned points.
Why does K-Means converge?
Each step (assignment and update) decreases or maintains the objective function J, J is bounded below by 0, and there are finitely many possible labelings, so by monotone convergence it must converge.
Does K-Means find the global optimum?
No, it converges to a local minimum. The global minimum is NP-hard to find, so different initializations can yield different results.
What is K-Means++ and why use it?
An initialization method that probabilistically choses initial centroids far from existing ones, weighted by squared distance. It leads to faster convergence and avoids poor local minima compared to random initialization.
What types of cluster shapes does K-Means struggle with?
Non-spherical shapes (elongated, crescent, ring-shaped clusters) and clusters of very different sizes or densities.
What is the time complexity of K-Means per iteration?
O(nKd)O(nKd) where n = number of points, K = number of clusters, d = number of dimensions. The assignment step (computing distances) is the bottleneck.
Why does WCSS always decrease as K increases?
Because more clusters allow finer partitioning; at the extreme where K=n (one cluster per point), every point is its own centroid and WCSS=0.
What is the elbow method for choosing K?
Plot WCSS versus K and look for an "elbow" point where the rate of WCSS decrease slows dramatically, indicating diminishing returns from adding more clusters.
How is soft K-Means (Fuzzy C-Means) different from standard K-Means?
It allows partial membership—each point has a probability distribution over clusters rather than hard assignment to a single cluster.
What is the relationship between K-Means and EM algorithm?
K-Means is a special case of the EM algorithm: hard EM for Gaussian mixture models with identity covariance matrices and equal priors.

Concept Map

minimizes

penalizes

alternates

alternates

assigns to nearest

recomputes as

derived from

proves optimal

greedy argmin

feeds back into

coupled loop

until stable

K-Means Clustering

Within-Cluster Sum of Squares J

Squared Euclidean Distance

Assignment Step

Update Step

Centroids

Cluster Mean

Derivative set to zero

Convergence

Hinglish (regional understanding)

Intuition Hinglish mein samjho

K-Means clustering ek bahut hi powerful aur simple algorithm hai jo bina labels ke data mein groups dhundhta hai. Socho tumhare pas customers ka data hai—kitna kharch karte hain, kitnibaar ate hain—lekin tumhe nahi pata kaun "premium customer" hai aur kaun "occasional buyer". K-Means automatically in patterns ko discover kar leta hai!

Algorithm ka logic bilkul simple hai: pehle K random points choose karo as "cluster centers" (centroids). Phir har data point ko uske sabse najdek wale centroid ke paas bhej do (assignment step). Ab har centroid ko apne assigned points ke exact center mein move karo (update step, jismein hum mean lete hain). Yeh dono steps repeat karo jab tak centroids stabilize na ho jayein. Mathematical guarantee hai ki har iteration mein objective function (total squared distances) decrease hoga ya same rahega, isliye algorithm definitely converge karega.

Lekin dhyan rakhna—K-Means ko K (number of clusters) pehle se batana padta hai, aur yeh spherical (gol) clusters ke liye best kaam karta hai. Agar tumhare clusters elongated ya crescent-shaped hain, toh K-Means struggle karega. Aur ek aur baat: different initializations se different results mil sakte hain kyunki yeh sirf local minimum tak pohochta hai, global minimum tak nahi. Isliye practice mein hum K-Means++ initialization use karte hain aur algorithm ko kaibaar different starting points se run karte hain, phir sabse best result choose karte hain. Overall, yeh fast, scalable, aur intuitive hai—industry mein bahut widely use hota hai customer segmentation, image compression, aur anomaly detection ke liye!

Go deeper — visual, from zero

Test yourself — Unsupervised Learning

Connections