Machine Learning Foundations · Chapter 10 · ~15 min · Intermediate
Unsupervised Learning: K-Means Clustering & PCA
Unlock hidden patterns without human labels. Master the iterative Lloyd-Forgy K-Means algorithm, explore K-Means++ probabilistic seeding, find optimal clusters via the Elbow method, and compress dimensions with Principal Component Analysis.
- Master the 2-step iterative Expectation-Maximization loop of K-Means
- Prevent bad local minima traps with K-Means++ distance-weighted seeding
- Determine the true cluster count K using Within-Cluster Sum of Squares (Inertia)
- Project high-dimensional datasets into orthogonal Principal Components (PCA)
Unsupervised Learning: K-Means Clustering & PCA: learn it visually
Unlock hidden patterns without human labels. Master the iterative Lloyd-Forgy K-Means algorithm, explore K-Means++ probabilistic seeding, find optimal clusters via the Elbow method, and compress dimensions with Principal Component Analysis.
1Learning Without a Teacher: The K-Means Cycle
In unsupervised learning, we are handed a feature matrix X with no target labels y. Our objective is to discover natural groupings, density cohorts, and geometric clusters.
The standard K-Means algorithm alternates between two complementary steps:
Every data point computes its Euclidean distance to all K centroids and joins the nearest cluster:c(i) = argmin_j ||x(i) - μ_j||²
Each centroid shifts its coordinates to the exact geometric center (arithmetic mean) of all its assigned member points:μ_j = (1 / |S_j|) · ∑ x(i)
Wrong idea: Picking K centroids completely at random from data
Random uniform seeding frequently places multiple centroids inside the same dense cluster, leading to poor convergence and local minima traps.
Real system: K-Means++ distance-squared probability seeding
Seeding each subsequent centroid with probability proportional to squared distance D(x)² from existing centroids spreads them out across natural clusters.
Is standard K-Means guaranteed to converge to the global optimal clustering solution?
2K-Means++: Eliminating the Initialization Lottery
Traditional K-Means picked K initial centroids randomly from the dataset. If two centroids accidentally spawned inside the same cluster, the algorithm split that single cluster while leaving another cluster orphaned!
K-Means++ solves this with a clever probabilistic seeding routine:
- Pick the 1st centroid
μ_1uniformly at random from the data. - For each remaining point
x, calculate its distanceD(x)to the closest existing centroid. - Select the next centroid with probability proportional to D(x)².
- Repeat until all
Kcentroids are chosen.
3Finding K: The Elbow Method & Silhouette Score
How do we know whether a customer database has 3, 5, or 10 segments?
We track Within-Cluster Sum of Squares (Inertia / WCSS) across candidate values of K:
As K increases, WCSS naturally drops. At K = N, WCSS reaches 0.0 (every sample is its own centroid!). The optimal K sits at the Elbow: the inflection point where adding another cluster provides diminishing returns.
Why can't we simply choose K by picking whichever K value produces the lowest Within-Cluster Sum of Squares (Inertia)?
4Hands-On: Step-by-Step K-Means Convergence
Watch the Lloyd-Forgy algorithm converge on 15 2D data points. Click Assign Points to color-code points to their closest centroid, then click Recalculate Means to shift centroids to cluster centers:
Interactive Step-by-Step K-Means Clustering Canvas (K = 3)
5Principal Component Analysis (PCA): Compressing High Dimensions
Modern datasets often contain hundreds of columns (e.g. genomic markers, sensor readings). Principal Component Analysis (PCA) is the foundational linear dimensionality reduction technique.
Covariance Eigenvectors
PCA computes the eigenvectors of the feature covariance matrix (1/m) X^T X. The 1st Principal Component (PC1) points along the axis of maximum variance.
Orthogonal Projections
Every subsequent component is strictly orthogonal (perpendicular) to all previous components, capturing the next largest slice of remaining variance.
What is the primary benefit of inspecting pca.explained_variance_ratio_ in scikit-learn?
6Bug Hunt: Fix Scaleless K-Means & Inertia Collapse
A customer segmentation pipeline was written with three severe bugs: features were not normalized (spending in dollars overwhelmed age in years), n_clusters=n_samples drove inertia to a trivial zero, and random centroid initialization was used.
Repair the clustering configuration:
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
- Standardize features before computing Euclidean distances:
X_scaled = StandardScaler().fit_transform(X). - Choose a sensible cluster count:
n_clusters=3. - Use K-Means++ initialization:
init="k-means++".
7Chapter Knowledge Challenge
Check your mastery of unsupervised clustering, K-Means++, and PCA dimensionality reduction:
What happens to K-Means clustering if you run it on raw data where Feature 1 has a range of [0, 1] and Feature 2 has a range of [0, 100,000]?
What is the key difference between feature selection (dropping columns) and PCA dimensionality reduction?
8Recap
- Unsupervised Learning discovers latent geometric groupings and structure from unlabeled feature matrices.
- K-Means alternates between Assignment (assign to closest centroid) and Update (recalculate centroid means).
- K-Means++ seeds centroids proportionally to squared distance
D(x)², eliminating the initialization lottery. - PCA projects high-dimensional data onto orthogonal eigenvectors of maximum variance, compressing feature spaces while preserving pairwise geometry.
Ready for Chapter 11? Mark this chapter as complete to proceed: