Assign, Move, Repeat
Group points around centers
Clustering groups examples without known target labels. K-means asks for k clusters, initializes k centers called centroids, assigns each row to its nearest centroid, moves each centroid to the mean of assigned rows, and repeats until assignments stabilize or an iteration limit is reached.
1. choose k starting centroids
2. assign each point to nearest centroid
3. replace each centroid with its cluster mean
4. repeat steps 2-3
The objective minimizes inertia, the sum of squared distances from points to their assigned centroids. Different starting centers can find different local solutions, so n_init runs several initializations and retains the best objective.
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
model = make_pipeline(StandardScaler(), KMeans(n_clusters=4, n_init=20, random_state=42))
labels = model.fit_predict(X)
Analogy: Place k meeting points, send each person to the nearest one, then move each meeting point to the average location of its attendees. Repeat until nobody changes groups.
Tip: Save the fitted scaler and centroids together. Assigning production rows in raw units to centroids learned in standardized units produces meaningless distances.