AI State of the Art
Fundamentals/Machine Learning: The Basics/22 min
Section 5

Unsupervised Learning: Clustering, Dimensionality Reduction

Listen as a podcast →

Introduction: Learning Without a Teacher

Imagine: you arrive in an unknown city with no map, no guide. Nobody tells you "this is the wealthy neighborhood" or "this is the train station." But you explore and naturally notice: "These buildings are all new and large, people are dressed fancy. This is a wealthy area." "Here it's old, noisy, smells like fish... this is the old port."

This is unsupervised learning. No labels. No teacher. Just raw data. You have to discover the structure on your own.

Why does it matter?

The overwhelming majority of existing data is unlabeled, for a simple reason: labeling is expensive, it needs humans, time, and often expertise. Unsupervised learning lets you exploit millions of raw data points without ever paying a human to label them.

Clustering: Grouping Similar Items

Clustering = partitioning data into groups where each group contains similar things.

Example: an e-commerce site has 1 million customers. No labels. But clustering discovers:

  • Group A: buy often, small amounts, loyal (frequent buyers)
  • Group B: buy rarely, huge amounts (rare but big spenders)
  • Group C: just visitors, most of whom never buy (the window-shoppers)

Each group receives a different marketing strategy. No need to label them by hand.

K-Means: The Easy Classic

The most popular clustering algorithm. How it works:

  1. Decide the number of clusters K (2, 3, 5, whatever).
  2. Place K random points (the "centers" or centroids).
  3. Assign each point to the nearest center.
  4. Recalculate the centers as the average of points in each group.
  5. Repeat steps 3-4 until nothing changes (convergence).

The centroids move toward the "center of gravity" of each group.

Strengths:

  • Super fast (linear complexity)
  • Simple to understand and code
  • Works well when clusters are roughly spherical

Limitations:

  • You need to choose K in advance (what's the "right" number of clusters?)
  • Sensitive to the starting draw: depending on where the initial centers land, you can end up stuck on a mediocre partition
  • Assumes clusters of similar shape (spherical)
Choosing K with the Elbow Method

Plot a graph: X = number of clusters K, Y = inertia (total distance). The curve drops sharply then flattens out. The "elbow" (the transition point) is the optimal K. Visually, it's a curve that looks like a bent arm.

K-means algorithm. Training examples are shown as dots, and cluster centroids are shown as crosses. (a) Original dataset. (b) Random initial cluster centroids. (c-f) Illustration of running two iterations of k-means. In each iteration, we assign each training example to the closest cluster centroid (shown by 'painting' the training examples the same color as the cluster centroid to which is assigned); then we move each cluster centroid to the mean of the points assigned to it. Images courtesy of Michael Jordan.
K-means algorithm. Training examples are shown as dots, and cluster centroids are shown as crosses. (a) Original dataset. (b) Random initial cluster centroids. (c-f) Illustration of running two iterations of k-means. In each iteration, we assign each training example to the closest cluster centroid (shown by 'painting' the training examples the same color as the cluster centroid to which is assigned); then we move each cluster centroid to the mean of the points assigned to it. Images courtesy of Michael Jordan.Source : Stanford University

DBSCAN: Following Density

DBSCAN (Density-Based Spatial Clustering of Applications with Noise) takes the problem from the other end: instead of looking for centers, it looks for dense regions.

Principle:

  • A point that has many close neighbors (e.g., at least 5 points within a radius of 0.5) is a "core point"
  • Connect core points that are close together -> that's a cluster
  • Isolated points (not enough neighbors) -> that's noise/anomalies

Strengths:

  • No need to specify K
  • Detects clusters of any shape (not just spherical)
  • Automatically detects anomalies (isolated points)

Limitations:

  • Problematic if clusters have very different densities
  • Sensitive to the epsilon (radius) and minPts (minimum number of neighbors) parameters
Unlabeled data in concentric circles
This image illustrates unlabeled data organized in concentric circles, used to demonstrate the principles of unsupervised learning. On the right, the DBSCAN algorithm has identified clusters despite the complex data structure.Source : Towards AI

Hierarchical Clustering: The Tree of Groups

Builds a hierarchy represented as a "dendrogram" (a tree).

Agglomerative (bottom-up): each point starts alone. Iteratively merges the two closest clusters.

Divisive (top-down): everything starts together. Iteratively divides.

Advantage: you see the structure at all scales. You can cut the tree anywhere to get whatever number of clusters you want.

Two types of clustering: hierarchical and non-hierarchical. In the first case, data is grouped exclusively, so if a data point belongs to a defined cluster, it cannot be included in another cluster. The figure below shows a simple example where the spacing of points is defined by straight lines on a two-dimensional plane.
Two types of clustering: hierarchical and non-hierarchical. In the first case, data is grouped exclusively, so if a data point belongs to a defined cluster, it cannot be included in another cluster. The figure below shows a simple example where the spacing of points is defined by straight lines on a two-dimensional plane.Source : ResearchGate

Dimensionality Reduction: Seeing the World in 2D

Your data has 1,000 dimensions? 10,000 features? That's too much to visualize or even compute efficiently.

Dimensionality reduction projects data into a smaller space (typically 2D or 3D) while preserving the important information.

Why Reduce?

Visualization: impossible to see 1,000 dimensions. Reducing to 2D lets you explore the data visually.

Acceleration: fewer dimensions = faster algorithms.

Denoising: the least important dimensions are often pure noise. Removing them helps.

The curse of dimensionality: in very high dimensions, all points become very far apart from each other. K-Means, KNN, etc. become useless.

Illustration of dimensionality reduction
This image illustrates the concept of dimensionality reduction, which transforms high-dimensional data (left) into a lower-dimensional representation (right) while preserving essential information. This simplifies computations and avoids issues related to the curse of dimensionality.Source : GeeksforGeeks

PCA: Following Maximum Variance

Principal Component Analysis (PCA) looks for the directions along which your data varies the most, and keeps only those.

Imagine: 10,000 points in 3D space. But they're all aligned along a line. The true dimension is 1, not 3. PCA finds that line.

How it works:

  1. Normalize the data (subtract the mean)
  2. Compute the covariance matrix (how each feature varies with the others)
  3. Find the "principal axes" (the directions of maximum variance)
  4. Project onto the top 2-3 axes

Strengths: fast, deterministic, mathematically clear.

Limitations: only captures linear relationships.

Illustration of PCA on 2D data
This image shows the limitations of Principal Component Analysis (PCA): it only captures linear relationships between variables. On the left, data is represented in its original space (variable 1 vs variable 2). On the right, PCA projects this data onto new axes (PC1 and PC2) that maximize variance, but cannot model non-linear relationships.Source : ourcodingclub.github.io

t-SNE: For Beautiful Visualizations

t-SNE, for t-distributed Stochastic Neighbor Embedding: designed for looking only, not for feeding a downstream computation.

Idea: preserves local structures (nearby points stay nearby).

Result: very readable visualizations where you can clearly see the clusters. Magical.

But be careful:

  • It is slow: computation time grows with the square of the number of points (written O(n2)O(n^2), doubling the points quadruples the work). Past a few tens of thousands of points this becomes prohibitive
  • Non-deterministic (each run is different)
  • Never use t-SNE output as input to another algorithm: the method deliberately distorts distances, so the coordinates it produces no longer mean anything quantitatively. It is a tool for looking, not for computing.

UMAP: t-SNE But Better

UMAP, for Uniform Manifold Approximation and Projection: a more recent and generally better alternative.

Advantages:

  • Much faster than t-SNE, its authors report gains of an order of magnitude, though this stays dataset-dependent
  • Better preservation of overall structure, not just the immediate neighborhood
  • Holds up at millions of points
  • Its output stays usable as input to another algorithm, not only as a picture

Today, UMAP is generally preferred over t-SNE for exploring large datasets.

Dimensionality Reduction: PCA is applied to project the data to 2D, preserving variance. t-SNE projects data with a focus on local clustering. UMAP aims to preserve both local and global structures in the data.
Dimensionality Reduction: PCA is applied to project the data to 2D, preserving variance. t-SNE projects data with a focus on local clustering. UMAP aims to preserve both local and global structures in the data.Source : AI Competence

Anomaly Detection

The goal here is to identify observations that deviate significantly from normal behavior.

Usage examples:

  • Cybersecurity: detect intrusions
  • Finance: detect fraud
  • Maintenance: detect machines close to failure
  • Healthcare: detect rare cases/pathologies
  • Monitoring: detect dying servers

Common techniques:

Isolation Forest: builds trees of random splits. Measures how many splits are needed to isolate a point. Anomalies are isolated faster (fewer splits).

Autoencoders: a neural network that compresses then reconstructs data. Trained only on normal data. An anomaly (never seen) will be poorly reconstructed (high reconstruction error).

One-Class SVM: learns a closed boundary around the normal data. Anything falling outside is flagged as an anomaly.

Real-World Use Cases

Customer segmentation: an online retailer groups its millions of customers into five to ten segments and sends each a different campaign. This is the most widespread industrial use of clustering; reported gains vary enormously between cases, so treat the round numbers you see quoted on this with suspicion.

Data exploration: Before building a supervised model, use PCA or UMAP to visualize. It helps you see: do the classes overlap? Are there weird outliers? Are my features useful?

Compression: a 1000 x 1000 pixel image is a million numbers. If PCA shows that 50 principal components capture the essentials, you go from 1,000,000 numbers to 50, twenty thousand times fewer. Reconstruction is not exact, since information was thrown away, but it stays visually close. The achievable ratio depends entirely on the images: this calculation illustrates the principle, it is not a measured result.

Recommendation systems: Matrix factorization discovers hidden preferences. A streaming service discovers axes of taste on its own (more or less action, more or less romance) without anyone naming them, then recommends titles that sit close along those axes.

Supervised vs Unsupervised: The Table

AspectSupervisedUnsupervised
DataLabeled (X, y)Raw (X only)
ObjectivePredict yDiscover structure
EvaluationClear (accuracy, MSE)Subjective, visual
ExamplesClassification, regressionClustering, reduction
Main challengeObtaining labelsInterpreting results

Why This Matters

Unsupervised learning opens you up to analyzing raw real-world data. This is how Netflix discovers that you like science fiction. This is how banks detect fraud, and how science reveals hidden structures in data. Almost no company can label all its data. Unsupervised learning is the key to leveraging it.

Check your understanding0 / 5

1. Why is unsupervised learning so valuable in practice?

2. What advantage does DBSCAN have over K-Means?

3. You produced a beautiful 2D t-SNE projection. Can you feed those coordinates into another algorithm, say a clustering step?

4. What does the curse of dimensionality say?

5. Why is evaluating a clustering trickier than evaluating a supervised classifier?