2. Classification: Clustering

K-Means, Gaussian Mixture Models, EM algorithm, unsupervised learning, dimensionality reduction

Contents
1. Classification vs Object Detection 2. Supervised vs Unsupervised Learning 3. K-Means Clustering 4. K-Means Mathematics 5. K-Means Applied to Digits 6. K-Means Properties 7. Gaussian Mixture Models 8. Gaussian Distributions 9. EM Algorithm 10. GMM Summary 11. Dimensionality Reduction (PCA) Interactive: K-Means Walkthrough Interactive: K-Means Visualizer Interactive: EM Walkthrough Interactive: EM/GMM Visualizer Interactive: Gaussian Explorer Interactive: PCA Explorer Flashcards

1. Classification vs Object Detection

These are two fundamentally different computer vision tasks that are frequently confused.

TaskGoalOutput
Image ClassificationLabel the entire image with a single categoryOne class label (e.g., "CAT")
Object DetectionFind, localize, and count specific objects in an imageBounding boxes + labels + counts
Classification (single label) versus Object Detection (bounding boxes)
Left: classification assigns a single label ("CAT") to the whole image. Right: detection draws bounding boxes around every object and labels each one.
Key insight
Classification asks "what is this image?" Detection asks "what is here and where?" This module focuses on classification. Object detection builds on classification in later modules.

2. Supervised vs Unsupervised Learning

Supervised learning vs unsupervised learning diagram
Supervised learning uses labeled input/target pairs; unsupervised learning discovers hidden structure in unlabeled data.
AspectSupervisedUnsupervised (Clustering)
Training dataInput vectors and labelsInput vectors only — no labels
FeedbackDirect (knows correct answer)None
GoalPredict outputs for new inputsFind hidden structure
ExampleDigit recognizer with known labelsGroup digits without knowing labels

This module covers unsupervised clustering. The running example is handwritten digit classification using the MNIST dataset (28x28 pixel images of digits 0–9), where the goal is to group similar-looking images together without using labels.

MNIST handwritten digits 0-9
MNIST digits 0–9. Wide variability in writing style motivates machine learning rather than hand-crafted rules.

3. K-Means Clustering

K-Means is the most fundamental clustering algorithm. The intuition: given a scatter plot of $N$ data points, partition them into $K$ groups such that each group's points are as close as possible to their group's center.

Initial scatter plot showing 5 natural clusters
Initial data: 5 natural clusters visible in 2D space. Goal is to recover these groups automatically.

Algorithm — Intuitive Steps

  1. Initialize: Randomly place $K$ cluster centers (centroids) in the data space.
  2. Assign: Assign each data point to its nearest cluster center.
  3. Update: Recompute each cluster center as the centroid (mean) of all points assigned to it.
  4. Repeat steps 2–3 until assignments stop changing (convergence).
K-Means Visualizer
Press "Generate Data" to begin.

Voronoi Regions and Classification

After convergence, the cluster centers define Voronoi regions: every point in space is assigned to the nearest center. New test points can be classified by finding the nearest cluster center.

K-Means at convergence with stable cluster boundaries
At convergence, the 5 cluster regions are stable and well-aligned with the natural groups.
Labeled cluster regions after K-Means convergence
Final labeled cluster regions. New points are classified by nearest-center assignment.
Local optima problem
K-Means can converge to a non-optimal solution depending on random initialization. Solution: run multiple times with different random seeds and select the result with the lowest cost function $J$.

4. K-Means Mathematics

Euclidean Distance

Distance between two points in $D$ dimensions:

Euclidean Distance
$d(x, x') = \|x - x'\| = \sqrt{\sum_{i=1}^{D}(x_i - x_i')^2}$
Euclidean distance as hypotenuse of a right triangle
In 2D, Euclidean distance is the hypotenuse of the right triangle formed by horizontal and vertical differences.

Cost Function (Distortion)

K-Means Cost Function
$$J = \sum_{n=1}^{N} \sum_{k=1}^{K} r_{nk} \|x_n - \mu_k\|^2$$

where $r_{nk} = 1$ if point $x_n$ is assigned to cluster $k$, else $r_{nk} = 0$; $\mu_k$ is the center of cluster $k$.

$J$ is the sum of squared Euclidean distances from each data point to its assigned cluster center.

Alternating Optimization

K-Means minimizes $J$ by alternating two steps:

PhaseWhat is minimizedWhat is fixedOperation
Assignment (E-step)$J$ over $r_{nk}$$\mu_k$Assign each $x_n$ to nearest center: $k^* = \arg\min_k \|x_n - \mu_k\|^2$
Update (M-step)$J$ over $\mu_k$$r_{nk}$Recompute $\mu_k = \frac{\sum_n r_{nk}\,x_n}{\sum_n r_{nk}}$
Centroid Update Formula
$\mu_k = \dfrac{\displaystyle\sum_{n=1}^{N} r_{nk}\, x_n}{\displaystyle\sum_{n=1}^{N} r_{nk}}$

Convergence and Choosing K

K-Means is guaranteed to converge because $J$ cannot increase at any step. For choosing $K$:

3D scatter plot of clustered data
K-Means generalizes naturally to any number of dimensions — the math is identical.

5. K-Means Applied to Digit Classification

Images as Vectors

Each 28×28 pixel MNIST image is flattened into a 784-dimensional vector by reading pixels row by row:

28x28 pixel grid with grayscale intensity values
A 28x28 pixel grid — each cell is a grayscale intensity value. Most pixels are 0 (background).
Digit image alongside its intensity matrix
The digit "1" and its 28x28 intensity matrix. Flattening gives a 784-dimensional vector.
Digit as Data Point
Each 28x28 image $\Rightarrow$ a 784-dimensional vector $x \in \mathbb{R}^{784}$. K-Means with $K = 10$ groups these vectors by visual similarity.

Cluster Centroids as "Average Digits"

Each centroid $\mu_k \in \mathbb{R}^{784}$ can be reshaped back into a 28×28 image, revealing the "average" appearance of its cluster.

All 10 K-Means cluster centroids as blurry digit images
The 10 cluster centroids visualized as images. Each looks like a blurry averaged version of its digit.
K-Means centroid for digit 0
Single centroid for the "0" cluster — a soft, averaged zero shape.
Which digit clusters overlap?

Digits with similar visual structure will have cluster centers that are close in 784-dimensional space. Expected overlaps:

  • 3 and 8: similar curve structure
  • 4 and 9: similar vertical strokes with a top loop
  • 5 and 6: similar curved lower portion
  • 7 and 1: both mostly vertical with small extras

Overlapping clusters lead to more classification errors because new digits in the overlap region may be assigned to the wrong cluster.

6. K-Means Properties

PropertyDetails
Hard assignmentEvery point belongs to exactly one cluster (binary $r_{nk}$)
Convergence guaranteed$J$ decreases (or stays the same) at every step
Local minima onlyResult depends on random initialization; multi-start is essential
$K$ must be specifiedCannot automatically determine the number of clusters
Assumes spherical clustersDoes not handle elongated or irregular shapes well

K-Means Pseudocode

Full K-Means algorithm
For each seed trial:
  1. INITIALIZE: Randomly place K centers mu_1, ..., mu_K

  2. REPEAT:
     a. ASSIGNMENT: For each point x_n:
          assign to k* = argmin_k ||x_n - mu_k||^2
          set r_{n,k*} = 1, r_{n,j} = 0 for j != k*

     b. UPDATE: For each cluster k:
          mu_k = (sum of x_n where r_{nk}=1) / (count in cluster k)

     c. COMPUTE J = sum of r_{nk} * ||x_n - mu_k||^2

  UNTIL J does not improve

Select trial with lowest J as final result.
Key limitation motivating GMM
Points near cluster boundaries are forced into one cluster — even if they are almost equidistant from two centers. This hard assignment loses information. Gaussian Mixture Models replace hard 0/1 assignments with soft probabilities.

7. Gaussian Mixture Models

Why Move Beyond K-Means?

Two overlapping clusters with no clear boundary
Two overlapping groups. There is no clear boundary — many points could plausibly belong to either cluster.

GMM replaces hard cluster centers with $K$ Gaussian distributions. Each cluster is described by a full probability distribution, and each data point has a probability of belonging to each cluster.

AspectK-MeansGMM
AssignmentHard (0 or 1)Soft (probability 0–1)
Cluster shapeImplicitly spherical (Voronoi)Elliptical (covariance matrix)
Output per pointCluster label $k$Probability $P(k \mid x)$ for all $k$
ParametersCentroids $\mu_k$Means $\mu_k$, variances $\sigma_k^2$, mixing coefficients $\pi_k$
Two overlapping Gaussian clusters in 2D
Two Gaussian clusters in 2D. Points in the overlap region have high posterior probability for both clusters.
Multiple overlapping elliptical Gaussian clusters
Real-data example: multiple overlapping elliptical Gaussian clusters. K-Means would struggle with these non-spherical shapes.

8. Gaussian Distributions

1D Gaussian

1D Gaussian PDF
$$f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)$$

$\mu$ = mean (center), $\sigma$ = standard deviation (width), $\sigma^2$ = variance.

1D Gaussians with varying sigma
Same mean $\mu = 0$, varying $\sigma$: small $\sigma$ = tall narrow peak; large $\sigma$ = short wide peak.

2D and Multivariate Gaussian

Multivariate Gaussian PDF
$$f(\mathbf{x}) = \frac{1}{(2\pi)^{D/2}|\Sigma|^{1/2}} \exp\!\left(-\frac{1}{2}(\mathbf{x}-\boldsymbol{\mu})^T\Sigma^{-1}(\mathbf{x}-\boldsymbol{\mu})\right)$$

$\boldsymbol{\mu}$ = mean vector, $\Sigma$ = covariance matrix (controls shape and orientation).

2D Gaussian as a 3D bell-shaped surface
2D Gaussian: bell-shaped surface over $(x, y)$ with contour plot below. Peak is at the mean; contours are ellipses.
Likelihood vs Posterior
Do not confuse:
$P(x_i \mid k)$ = likelihood: probability density of observing $x_i$ under Gaussian $k$ (computed from the PDF).
$P(k \mid x_i)$ = posterior: probability that point $x_i$ belongs to cluster $k$ (what we want — computed via Bayes' theorem).
Gaussian Distribution Explorer
1D Gaussian
$f(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{(x-\mu)^2}{2\sigma^2}}$
2D Gaussian (contour view)

9. EM Algorithm

The Expectation-Maximization (EM) algorithm fits a GMM to data. It is the soft-assignment analog of K-Means alternating optimization.

EM / Gaussian Mixture Model Visualizer
Press "Generate Data" to begin.

E-Step: Compute Soft Assignments

For each data point $x_i$ and each Gaussian $k$, compute the posterior probability using Bayes' theorem:

E-Step — Bayesian Posterior
$$b_i = P(b \mid x_i) = \frac{P(x_i \mid b)\,P(b)}{P(x_i \mid b)\,P(b) + P(x_i \mid a)\,P(a)}$$

$P(x_i \mid b)$ = likelihood under Gaussian $b$; $P(b)$ = prior (mixing coefficient); $a_i = 1 - b_i$.

Bayesian posterior formula for soft cluster assignments
The posterior formula: probability that point $x_i$ was generated by each Gaussian.
E-step result: points colored by soft assignment
After E-step: points colored fractionally (dot size indicates strength of membership in each Gaussian).

M-Step: Recompute Gaussian Parameters

Using the soft assignments as weights, update each Gaussian's parameters:

M-Step — Weighted Mean and Variance
$$\mu_b = \frac{\sum_{i=1}^{n} b_i\, x_i}{\sum_{i=1}^{n} b_i}, \qquad \sigma_b^2 = \frac{\sum_{i=1}^{n} b_i(x_i - \mu_b)^2}{\sum_{i=1}^{n} b_i}$$
M-step update formulas for weighted mean and variance
M-step: every point contributes to every Gaussian's update, weighted by its posterior probability.

Unlike K-Means (where only assigned points update a centroid), in EM every point contributes to every Gaussian, weighted by how likely it is to belong to that Gaussian.

Visual Convergence

Initial Gaussians before EM
Initial state: two overlapping Gaussians placed randomly.
EM intermediate iteration
Mid-convergence: Gaussians shifting toward the true cluster centers.
EM converged: well-separated Gaussians
After convergence: two well-separated Gaussians accurately modeling the two clusters.

EM in 2D

GMM-EM iteration 0 for 2D data
Initial Gaussian components in 2D shown as contour ellipses.
GMM-EM 2D/3D probability surface
Converged 2D GMM: probability surface with contour projections showing Gaussian mixture.

10. GMM and EM Summary

Full EM pseudocode
Input: Data {x_1, ..., x_N}, number of Gaussians K

1. INITIALIZE: Randomly set mu_k, sigma_k, pi_k for each k

2. REPEAT:

   E-STEP: For each point x_i, each Gaussian k:
     Compute likelihood: P(x_i | k) using Gaussian PDF
     Compute posterior:  gamma(i,k) = P(k | x_i) via Bayes' theorem

   M-STEP: For each Gaussian k:
     mu_k    = weighted mean (weights = gamma(i,k))
     sigma_k = weighted variance (weights = gamma(i,k))
     pi_k    = average of gamma(i,k) over all points

UNTIL Gaussian updates are small (convergence)

K-Means vs GMM Side-by-Side

K-MeansGMM + EM
InitializationRandom centroidsRandom Gaussian parameters
E-stepAssign each point to nearest centroid (hard)Compute posterior probability for each Gaussian (soft)
M-stepRecompute centroid as mean of assigned pointsRecompute mean/variance using weighted points
Assignment typeBinary $r_{nk} \in \{0,1\}$Probabilistic $\gamma_{ik} \in [0,1]$
Cost functionDistortion $J$ (sum of squared distances)Log-likelihood
Convergence$J$ stops decreasingParameter updates become small
Cluster shapeSpherical (Voronoi)Elliptical (covariance matrix)
PropertyK-MeansGMM
Convergence guaranteedYesYes (to local min)
Global optimum guaranteedNoNo
$K$ must be specifiedYesYes
Handles overlapping clustersPoorlyWell
Computationally expensiveLessMore

11. Dimensionality Reduction (PCA)

MNIST digit images are 784-dimensional, making clustering computationally expensive (especially for GMM, which requires 784×784 covariance matrices).

Principal Component Analysis (PCA)
Find the directions (principal components) along which data varies most. Project data onto a smaller number of these directions, reducing dimensionality while retaining most meaningful variation.
BenefitExplanation
Faster computationDistance calculations in ~50D are much cheaper than 784D
Less memoryCovariance matrices shrink from 784×784 to ~50×50
Noise reductionLow-variance dimensions often correspond to noise
VisualizationReduce to 2D or 3D to plot and inspect clusters
Key insight
PCA does not discard random dimensions — it finds the most informative directions in the data. Reducing from 784D to 50D typically retains the majority of the visual information needed for digit discrimination while dramatically speeding up subsequent clustering.
PCA Explorer
Press "Generate Data" to create a point cloud with a clear principal axis.

Flashcards