2.5.1 · HinglishUnsupervised Learning

K-Means clustering algorithm

2,457 words11 min readRead in English

2.5.1 · AI-ML › Unsupervised Learning


K-Means Kya Hai?

YEH OBJECTIVE KYUN? Hum chahte hain ki clusters mein points apne center ke around tightly packed hon. Squared distances minimize karna outliers ko heavily penalize karta hai (quadratic penalty) aur math ko gradient-based reasoning ke liye tractable banata hai.


Algorithm: First Principles se Derivation

GOAL: Data ko clusters mein partition karo taaki total variance minimize ho.

Step 1: Centroids Kyun?

Agar hum cluster assignments fix kar lein, toh cluster ke liye best representative point kaun sa hoga?

Minimize: , ke respect mein

Derivative lo aur zero set karo:

RESULT: Optimal representative cluster ke saare points ka mean (average) hota hai. Isliye inhe "centroids" kehte hain.

Step 2: Nearest-Neighbor Assignment Kyun?

Agar hum centroids fix kar lein, toh point ko kaun se cluster mein jaana chahiye?

Minimize: Total objective mein ka contribution

Point ko cluster mein jaana chahiye jahan:

KYUN? Har point independently woh centroid choose karta hai jo uski apni squared distance minimize kare. Yeh greedy assignment tab optimal hai jab centroids fixed hoon.

Step 3: Lloyd's Algorithm

Yeh do steps coupled hain: better assignments se better centroids milte hain, jinse better assignments milti hain. Hum alternate karte hain:

Initialize: Randomly points ko initial centroids ke roop mein select karo

Convergence tak repeat karo:

  1. Assignment Step: Har point ke liye, nearest centroid ko assign karo:

  2. Update Step: Har centroid ko assigned points ke mean ke roop mein recompute karo:

Convergence: Tab ruko jab assignments change karna band ho jayein (ya centroids threshold se kam move karein)

YEH CONVERGE KYUN KARTA HAI? Har step objective ko decrease karta hai (ya constant rakhta hai):

  • Assignment step: Points closer centroids ki taraf move karte hain → decrease hota hai
  • Update step: Centroids apne cluster ke mean ki taraf move karte hain → decrease hota hai (hamare derivative proof se)
  • neeche se bounded hai
  • Monotone convergence theorem se, algorithm zaroor converge karega

IMPORTANT: Convergence ek local minimum ki taraf hoti hai, necessarily global nahi. Alag-alag initializations se alag results aa sakte hain.


Worked Examples

Data: Goal: 2 clusters dhundo

Iteration 0 (Initialize):

  • Random centroids:

Iteration 1: Assignment:

  • : → Cluster 1
  • : → Cluster 1
  • : → Cluster 2
  • : → Cluster 2

Update:

Iteration 2:

Assignment: (Distances phir se check karo)

  • Saare assignments same rehte hain

Converge ho gaya! Final clusters: aur

YEH STEP KYUN? Har distance calculation Euclidean metric use karti hai kyunki hum squared distances minimize kar rahe hain. Update step coordinates ko component-wise average karta hai kyunki mean sum of squared deviations minimize karta hai.


Problem: 100 customers ko [spending, frequency] se cluster karo

# 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

YEH CHOICES KYUN?

  • K-Means++ initialization: Initial centroids ko spread out karta hai → faster convergence, bad local minima se bachata hai
  • Vectorization: cdist ek saath saare pairwise distances compute karta hai → loops se 100× faster
  • Convergence check: Centroid movement compare karo, assignments nahi → zyada stable stopping criterion

Common Mistakes aur Unhe Kaise Fix Karein

Reality: K-Means ek local minimum mein converge karta hai, jo initialization par depend karta hai. Alag-alag random starts se alag results milte hain.

Steel-man: Algorithm starting point ke given WCSS objective ko perfectly optimize karta hai. Problem yeh hai ki objective landscape mein bahut saari valleys hain.

Fix:

  • K-Means ko multiple times alag initializations ke saath run karo (sklearn default: 10 runs)
  • K-Means++ initialization use karo (provably random se better)
  • Sabse low final WCSS wala solution report karo

Reality: K-Means spherical clusters ki similar size assume karta hai. Yeh fail karta hai:

  • Elongated/elliptical clusters par
  • Crescent ya ring shapes par
  • Bahut alag densities ke clusters par

Steel-man: Spherical Gaussian distributions se generate kiye gaye data ke liye, K-Means actually optimal hai (yeh MLE solution hai).

Fix:

  • Preprocess karo: Agar scales alag hain toh features standardize karo
  • Non-convex shapes ke liye DBSCAN ya spectral clustering use karo
  • Data transform karo (e.g., kernel trick) taaki clusters zyada spherical ho jayein

Reality:

  • WCSS hamesha decrease hota hai jab badhta hai ( par, WCSS=0)
  • Koi universal "correct" K nahi hai — yeh domain-dependent hai

Steel-man: Systematic search valuable zaroor hai, lekin sahi metric chahiye.

Fix:

  • Elbow method: WCSS vs K plot karo, "elbow" dhundo jahan improvement slow ho jaaye
  • Silhouette score: Measure karo ki points apne cluster se kitne similar hain vs. doosron se
  • Domain knowledge: Kabhi kabhi K known hota hai (e.g., customer segments)
  • Gap statistic: WCSS ko null distribution se compare karo

Computational Complexity

Har iteration mein time:

  • Assignment step: points × centroids × dimensions compute karo
  • Update step: points, dimensions par sum karo

Total: jahan = iterations ki sankhya

Space: — data aur centroids store karo

Practice mein: typically chota hota hai (<100) aur , isliye K-Means large datasets par achhe se scale karta hai.

YEH COMPLEXITY KYUN? Assignment step bottleneck hai: hum distances compute karte hain. Advanced implementations KD-trees ya ball trees use karte hain jab chota ho toh ise reduce karne ke liye.


Convergence ke Peeche ka Math

Claim: Har iteration ko decrease karta hai (ya same rakhta hai), isliye K-Means converge karta hai.

Proof: Maano iteration par objective hai.

Iteration par assignment step ke baad: kyunki har point nearest centroid ki taraf move karta hai (ya wahan rehta hai), jo uski distance increase nahi kar sakta.

Update step ke baad: kyunki (pehle prove kiya hua).

Isliye:

Kyunki aur finitely many possible labelings hain (zyada se zyada ), algorithm zaroor converge karega.

CAVEAT: Convergence ek local minimum ki taraf hoti hai. Global minimum dhundhna NP-hard hai.


Extensions aur Variations

  1. K-Means++: Smart initialization jo initial centroids ko spread karta hai jahan = nearest existing centroid tak ki distance

  2. Mini-Batch K-Means: Har iteration mein random subsets of data use karo → huge datasets ke liye faster

  3. Soft K-Means (Fuzzy C-Means): Partial membership allow karo:

  4. K-Medoids (PAM): Actual data points ko centers ke roop mein use karo (outliers ke liye robust)


Recall Ek 12-Saal ke Bachche ko Explain Karo

Socho tumhare paas ek bag hai jisme alag-alag colored candies mixed hain, lekin tumhe pehle se nahi pata ki kaun se colors hain — woh bas random candies lagti hain. K-Means ek game jaisa hai jisme:

  1. Tum K alag-alag boxes pile mein randomly rakhte ho
  2. Har candy nearest box ki taraf jaati hai
  3. Tum har box ko uske saari candies ke center par move karte ho jo usne choose ki
  4. Steps 2-3 repeat karo jab tak boxes move karna band na kar dein

Boxes "seekh" rahe hain ki similar candies ke natural groups kahan hain! Same box mein candies ek doosre se similar ho jaati hain, chahe tumne algorithm ko kabhi nahi bataya ki kaun si candies ek saath jaani chahiye.

Tricky part yeh hai ki tumhe shuru mein decide karna hota hai kitne boxes (K) use karne hain. Zyada kam boxes aur tum alag types ko ek saath squeeze kar lete ho. Zyada boxes aur tum candies ko split kar dete ho jo actually same type ki hain.


"Converge but Local" — Yeh move karna band kar deta hai, lekin overall best answer nahi ho sakta

K-Means = K-Averages — Centroids literally means (averages) hote hain, medians ya modes nahi

"Spherical, Similar Size" — Do S's jo describe karte hain ki K-Means kya pasand karta hai


Connections


#flashcards/ai-ml

K-Means kaunsa objective function minimize karta hai? :: Within-cluster sum of squares (WCSS):

Cluster representative ko "centroid" kyun kehte hain?
Kyunki optimal representative jo squared distances minimize kare woh cluster ke saare points ka mean (center of mass) hota hai, yeh WCSS ka derivative lekar aur zero set karke prove kiya jaata hai.
K-Means mein do alternating steps kaun se hain?
(1) Assignment: har point ko nearest centroid assign karo; (2) Update: har centroid ko uske assigned points ke mean ke roop mein recompute karo.
K-Means converge kyun karta hai?
Har step (assignment aur update) objective function J ko decrease ya maintain karta hai, J neeche se 0 se bounded hai, aur finitely many possible labelings hain, isliye monotone convergence se yeh zaroor converge karta hai.
Kya K-Means global optimum dhundta hai?
Nahi, yeh ek local minimum mein converge karta hai. Global minimum dhundhna NP-hard hai, isliye alag-alag initializations se alag results aa sakte hain.
K-Means++ kya hai aur ise kyun use karte hain?
Ek initialization method jo probabilistically initial centroids ko existing ones se door choose karta hai, squared distance se weighted. Yeh faster convergence deta hai aur random initialization ke comparison mein poor local minima se bachata hai.
K-Means kis tarah ke cluster shapes ke saath struggle karta hai?
Non-spherical shapes (elongated, crescent, ring-shaped clusters) aur bahut alag sizes ya densities ke clusters.
K-Means ki har iteration mein time complexity kya hai?
jahan n = points ki sankhya, K = clusters ki sankhya, d = dimensions ki sankhya. Assignment step (distances compute karna) bottleneck hai.
WCSS hamesha K badhne se kyun decrease karta hai?
Kyunki zyada clusters finer partitioning allow karte hain; extreme case mein jahan K=n (har point ka apna cluster), har point apna centroid hai aur WCSS=0.
K choose karne ke liye elbow method kya hai?
WCSS versus K plot karo aur ek "elbow" point dhundo jahan WCSS decrease ki rate dramatically slow ho jaaye, jo indicate karta hai ki aur clusters add karne se diminishing returns mil rahe hain.
Soft K-Means (Fuzzy C-Means) standard K-Means se kaise alag hai?
Yeh partial membership allow karta hai — har point ka clusters par probability distribution hota hai, na ki single cluster mein hard assignment.
K-Means aur EM algorithm mein kya relationship hai?
K-Means, EM algorithm ka ek special case hai: identity covariance matrices aur equal priors wale Gaussian mixture models ke liye hard EM.

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