Unsupervised machine learning algorithms find hidden patterns in unlabeled datasets. K-Means Clustering is one of the most popular clustering algorithms, partitioning observations into distinct clusters by minimizing the sum of squared distances between data points and their assigned cluster centroids.
1. Summary & Key Takeaways
- Expectation-Maximization (EM): K-Means iterates between two alternating steps:
- E-Step (Assignment): Assign each data point to the nearest centroid .
- M-Step (Update): Recalculate each centroid position as the mean of all assigned points.
- Objective Function (Inertia): Minimizes within-cluster sum-of-squares (WCSS):
- Voronoi Tessellation: The resulting cluster boundaries partition feature space into convex Voronoi cells.
2. Interactive K-Means Playground
Use the interactive 2D cluster simulator below to step through Expectation-Maximization iterations and watch centroid crosshairs adjust to point clusters!
Click Step 1 Iteration repeatedly. Notice how centroids move rapidly during early iterations and quickly converge to stable cluster centers!
K-Means Clustering & Voronoi PartitionsUnsupervised ML
Alternate between Assigning Points (Expectation) and Updating Centroids (Maximization).
# K-Means Clustering in Python using NumPy
import numpy as np
def k_means(X, k, max_iters=100):
# 1. Randomly initialize k centroids
centroids = X[np.random.choice(X.shape[0], k, replace=False)]
for _ in range(max_iters):
# Step 1: Assign points to nearest centroid (E-Step)
distances = np.linalg.norm(X[:, np.newaxis] - centroids, axis=2)
labels = np.argmin(distances, axis=1)
# Step 2: Update centroids to mean of assigned points (M-Step)
new_centroids = np.array([X[labels == i].mean(axis=0) for i in range(k)])
if np.all(centroids == new_centroids):
break
centroids = new_centroids
return centroids, labels3. Mathematical Foundations
Given a set of data points , K-Means partitions them into sets :
Euclidean Distance Metric
Centroid Update Rule
4. Clustering Algorithm Comparison
| Algorithm | Type | Complexity | Handles Non-Convex Shapes? |
|---|---|---|---|
| K-Means | Centroid-based | No (Prefers spherical clusters) | |
| DBSCAN | Density-based | Yes (Arbitrary cluster shapes) | |
| Hierarchical | Tree-based | Yes (Dendrogram hierarchy) |