Chapter 10 of 13
Course Progress0 of 13 completed (0%)

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.

Unsupervised Learning: K-Means Clustering & PCAUnlock 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.UNDERSTANDFeature vectorsFOLLOW THE FLOWCluster with K-meansAPPLY ITProject with PCAUnsupervised Learning: K-Means Clustering & PCAUnlock 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.UNDERSTANDFeature vectorsFOLLOW THE FLOWCluster with K-meansAPPLY ITProject with PCA

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:

Step 1: Assignment (E-Step)

Every data point computes its Euclidean distance to all K centroids and joins the nearest cluster:
c(i) = argmin_j ||x(i) - μ_j||²

Step 2: Update (M-Step)

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 Init → 2 Centroids trapped in 1 cluster → Sub-optimal WCSSFails because nearby centroids split one natural cluster in half

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

P(x) ∝ D(x)² → Centroids seeded far apart across all clustersO(log K) competitive bound guaranteeing fast convergence to global optimum

Seeding each subsequent centroid with probability proportional to squared distance D(x)² from existing centroids spreads them out across natural clusters.

Concept Check

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:

  1. Pick the 1st centroid μ_1 uniformly at random from the data.
  2. For each remaining point x, calculate its distance D(x) to the closest existing centroid.
  3. Select the next centroid with probability proportional to D(x)².
  4. Repeat until all K centroids 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:

WCSS = ∑k=1K ∑x ∈ S_k || x - μk ||2

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.

Concept Check

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)

Iteration: 0 · Phase: SEEDED
μ1μ2μ3Normalized Feature 1 (X)Normalized Feature 2 (Y)
Inertia (WCSS):Unassigned
Cluster 1 (μ₁):[1.5, 5.5]
Cluster 2 (μ₂):[4.5, 2]
Cluster 3 (μ₃):[5.5, 7.5]
Execute K-Means Iteration:

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.

Concept Check

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:

Python Bug Hunt · K-Means Normalization & Hyperparameters
Python

🎯 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:

Concept Check 1 of 2
1

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]?

Concept Check 2 of 2
2

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:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us