Step 4 of 6
Clustering, dimensionality reduction & embeddings
K-means, DBSCAN, t-SNE, UMAP, and the idea of learning structure without labels - the bridge to representation learning.
14 min read
Not all data comes with labels. Unsupervised learning finds structure in raw data - clusters that group similar points, lower-dimensional representations that capture the essence, and embeddings that encode meaning. These ideas are the bridge to representation learning and deep learning.
Clustering - finding groups#
Clustering groups data points so that points within a cluster are more similar to each other than to points in other clusters. No labels needed - the algorithm discovers the structure.
K-means#
The most widely used clustering algorithm. Choose k cluster centers, assign each point to the nearest center, move each center to the mean of its assigned points, and repeat:
- 01Initialize k cluster centroids (randomly or with k-means++)
- 02Assign each point to the nearest centroid
- 03Recompute each centroid as the mean of its assigned points
- 04Repeat until assignments stop changing
K-means minimizes the total within-cluster variance: the sum of squared distances from each point to its cluster center.
K-means is fast and scales well, but assumes clusters are spherical and equally sized. It's sensitive to initialization - k-means++ chooses initial centers that are spread apart, dramatically improving results.
- k-means++
- A smarter initialization for k-means - picks each starting centroid far from existing ones, avoiding the poor clusters that random init can produce.
- Inertia
- The total within-cluster sum of squared distances - lower is tighter clusters. Used in the elbow method to choose k.
- Silhouette score
- Measures how similar a point is to its own cluster vs. neighboring clusters - ranges from −1 (wrong cluster) to +1 (well-matched).
DBSCAN - density-based clustering#
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) groups points that are closely packed together, marking isolated points as noise. It doesn't need k in advance and can find clusters of arbitrary shape.
Two parameters: ε (neighborhood radius) and minPts (minimum neighbors to form a dense region). A point is a core point if it has ≥ minPts neighbors within ε; clusters grow by connecting core points whose neighborhoods overlap.
| K-means | DBSCAN |
|---|---|
| Must specify k | Finds k automatically |
| Spherical clusters only | Arbitrary shapes |
| Every point is assigned | Identifies noise/outliers |
| Sensitive to initialization | Deterministic |
| Scales well | Struggles with varying densities |
Dimensionality reduction - seeing the big picture#
High-dimensional data is hard to visualize, expensive to process, and often redundant. Dimensionality reduction compresses data to fewer dimensions while preserving the important structure.
PCA - linear reduction#
Principal Component Analysis finds the orthogonal directions of maximum variance and projects data onto the top k:
PCA: project data onto the top k eigenvectors of the covariance matrix. The eigenvalues tell you how much variance each component captures.
PCA is linear - it finds the best flat subspace. If the structure is nonlinear (data lives on a curved manifold), PCA misses it. That's where t-SNE and UMAP come in.
t-SNE - nonlinear visualization#
t-SNE (t-Distributed Stochastic Neighbor Embedding) maps high-dimensional data to 2D or 3D for visualization. It preserves local structure - points that are nearby in the original space stay nearby in the embedding.
The algorithm models pairwise similarities as probabilities in both the original and reduced spaces, then minimizes the KL divergence between them:
- Nearby points: high probability in both spaces (preserved well)
- Distant points: low probability (less important to preserve)
- Perplexity: controls the effective number of neighbors - typically 5-50
UMAP - the modern alternative#
UMAP (Uniform Manifold Approximation and Projection) is similar to t-SNE but faster, preserves more global structure, and can be used for general-purpose dimensionality reduction (not just visualization):
| t-SNE | UMAP | |
|---|---|---|
| Speed | Slow (O(n²) or O(n log n)) | Fast |
| Global structure | Not preserved | Better preserved |
| Reproducibility | Non-deterministic | Deterministic (with seed) |
| Use as features | No | Yes (stable embeddings) |
| Dimensions | Typically 2-3 | Any |
Embeddings - learned representations#
An embedding is a dense, low-dimensional vector that represents a high-dimensional or discrete object (a word, a user, a product). Unlike PCA, embeddings are learned from data by a neural network:
- Word2Vec / GloVe: words → vectors where similar words are nearby
- BERT / GPT embeddings: contextual vectors where meaning depends on surrounding words
- Item embeddings: products, movies, or users represented for recommendation
Embedding similarity: the dot product (or cosine similarity) between two embedding vectors measures semantic similarity.
Semantic search is nearest-neighbor lookup in embedding space: encode the query as a vector, find the closest document vectors. This is how modern search engines, RAG systems, and recommendation engines work under the hood.
- t-SNE
- t-Distributed Stochastic Neighbor Embedding - a visualization technique that maps high-dimensional data to 2D/3D by preserving local neighborhoods.
- UMAP
- Uniform Manifold Approximation and Projection - faster alternative to t-SNE that also preserves global structure and can be used beyond visualization.
- KL divergence
- Kullback-Leibler divergence - measures how one probability distribution differs from another. Used in t-SNE and variational methods.
- RAG
- Retrieval-Augmented Generation - feeds an LLM relevant documents retrieved by semantic search so it can answer with up-to-date, grounded information.
- Word2Vec / GloVe
- Classic word embedding methods that learn fixed vectors from co-occurrence statistics - similar words end up nearby in vector space.
Where it shows up in ML#
Clustering organizes unlabeled data
Customer segmentation, anomaly detection, topic modeling, and data exploration all start with clustering.
PCA compresses features
Reduce hundreds of features to the top 20 principal components - often with minimal accuracy loss and faster training.
t-SNE / UMAP visualize embeddings
Plot 768-dimensional BERT embeddings in 2D to see how the model groups documents, detect anomalies, or verify fine-tuning.
Embeddings are the foundation of modern AI
Every LLM, search engine, and recommender system represents entities as vectors in a learned embedding space.