Ravindra BagaleCourses & study guides मराठी Track your progress

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

  1. Pick K (e.g. 3).
  2. Assign → update centres → assign again.
  3. 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.