Sub topic 2
Lloyd's Algorithm Step by Step
Assume you know basic Python and NumPy, means, Euclidean distance, and feature matrices where rows are samples and columns are features.
Assign and update
Lloyd's algorithm is the standard procedure for k-means. It repeats two steps:
- Assign: give each sample the label of its nearest centroid.
- Update: replace each centroid with the mean of the samples assigned to it.
A centroid is the representative point for a cluster. The process continues until the centroids barely change or a maximum iteration count is reached.
import numpy as np
def kmeans(X, k, n_iter=100, seed=0):
rng = np.random.default_rng(seed)
centroids = X[rng.choice(len(X), size=k, replace=False)]
for _ in range(n_iter):
distances = np.linalg.norm(
X[:, None, :] - centroids[None, :, :],
axis=2,
)
labels = distances.argmin(axis=1)
new_centroids = np.array([
X[labels == j].mean(axis=0)
if np.any(labels == j) else centroids[j]
for j in range(k)
])
if np.allclose(new_centroids, centroids):
break
centroids = new_centroids
inertia = ((X - centroids[labels]) ** 2).sum()
return labels, centroids, inertiaThe distance array has shape (number of samples, k). Each row contains one sample's distance to every centroid.
Convergence and local minima
Each assignment and update step does not increase k-means inertia, the total squared distance from samples to their assigned centroids. Because there are finitely many possible assignments, the process eventually stops or reaches the iteration limit.
The result is only a local minimum. It is the best solution reached from the chosen starting centroids, not necessarily the globally best arrangement.
Initialization and feature scaling
Random starting centroids can produce different results. k-means++ chooses initial centroids with preference for points far from existing centroids, usually producing better starts. Multiple restarts fit the model repeatedly and keep the run with the lowest inertia.
Scaling matters because Euclidean distance is affected by feature units. Standardize features when one column's numeric range would otherwise dominate the distance.
Exercise
Why can two runs of k-means with the same k produce different clusters?
Show answer
They may start with different centroids. Lloyd's algorithm can then converge to different local minima.