36. K-Means Clustering in Python
36.2 How K-Means Works (Simply)
Why. A one-line mental model stops K-Means from feeling like a black box.
What. Rough loop: (1) place K centres, (2) assign each point to nearest centre, (3) move centres to the mean of their points, (4) repeat until stable. sklearn runs this for you.
How.
Say the loop out loud
- Pick K (e.g. 3).
- Assign → update centres → assign again.
- Stop when labels stop changing (or max iterations).
from sklearn.cluster import KMeans
print("KMeans does assign/update loops inside fit().")
Scale note
Features on very different scales (₹ vs order counts) can dominate distance. For real projects, scale first; this chapter keeps numbers in a similar ballpark for clarity.