Level 3 In-Depth AI · Classical Machine Learning
Unsupervised Learning
Learning from data that has no answers attached. Find groups, find simpler descriptions, and find what is normal, so you can spot what isn't.
- Level
- ●●●●● Beginner
- Reading
- 11 min
- To learn it well
- 40 minutes to read, an hour to practise
- Builds on
- 3 concepts →
- Quiz
- 4 questions ↓
The full path from zero — 3 concepts before this one
- What Is AI?
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Unsupervised Learning
Read them roughly in this order. See it on the concept map →
Why it matters
Supervised learning needs labels: an email marked spam or not, a photo tagged "cat", a house with its sale price. Labels are expensive. Someone has to look at each example and write down the answer, and for medical scans or legal documents that someone is a highly paid expert.
Unlabelled data, by contrast, is everywhere and nearly free: every purchase in a shop's database, every sensor reading from a factory, every image on the web, every sentence ever written. Unsupervised learning is the family of methods that learn from data without labels. There is no right answer to copy, so the goal changes. Instead of "predict from ", it is "describe the structure of ".
In practice that means three main tasks, each with its own chapter:
- Clustering: find groups of similar examples. Customer segments, topics in a pile of documents, cell types in biological data. See k-Means Clustering.
- Dimensionality reduction: describe each example with fewer numbers while keeping what matters. For compression, speed, and for plotting high-dimensional data on a screen. See PCA and Dimensionality Reduction and t-SNE and UMAP.
- Density estimation: learn how likely each kind of example is, so you know what "normal" looks like. That is the basis of fraud and fault detection. See Anomaly Detection.
Unsupervised ideas are also at the heart of modern AI. A large language model is first trained on trillions of words with no human labels, by predicting the next word: a form of self-supervised learning that grew out of these ideas. Word Embeddings, Autoencoders and What Generative Models Do all learn the structure of unlabelled data.
The intuition
Tip a bag of mixed buttons onto a table and ask a child to sort them. Nobody tells them the categories. They might sort by colour, by size, or by number of holes, and each sorting is reasonable. They are finding structure in unlabelled data.
Two things follow from the button example, and both are true of every unsupervised method:
- There is no single right answer. Colour, size and holes are all valid groupings. The algorithm's job is to find a grouping that is useful, and what counts as useful depends on why you are asking.
- You choose what "similar" means. Sorting by colour treats a red big button as close to a red small one. Sorting by size doesn't. In unsupervised learning, the features you include and how you scale them decide what the algorithm will find.
Key idea Unsupervised learning finds structure in data without labels: groups (clustering), simpler descriptions (dimensionality reduction) and what is typical (density estimation). Because there is no answer key, judging the result needs care and usually human judgement.
How it works
The three tasks
Clustering assigns each example to a group, called a cluster, so that examples in the same cluster are more similar to each other than to examples in other clusters. The best-known method, k-Means Clustering, represents each cluster by its centre and assigns each point to the nearest centre. Other methods find clusters of any shape (DBSCAN), build a tree of nested clusters (hierarchical clustering), or give each point a probability of belonging to each cluster (Gaussian mixture models).
Dimensionality reduction maps each example from many features to few. Often the data has latent structure: although it is recorded with many numbers, it really varies in only a few ways. A photo of a face has a million pixel values, but faces differ mainly in a few dozen ways (pose, lighting, expression, identity). PCA and Dimensionality Reduction finds the straight-line directions along which the data varies most. Nonlinear methods such as t-SNE and UMAP are built for drawing high-dimensional data as 2D maps. Autoencoders learn a compressed code with a neural network.
Density estimation learns a probability distribution over the data: a function that is high where examples are common and low where they are rare. The simplest version is a histogram. Fitting a Gaussian (bell curve) is one step up, and a mixture of several Gaussians can model lumpy, multi-peaked data. Modern What Generative Models Do (diffusion models, language models) are, at heart, extremely powerful density estimators, which is why they can also sample: generate new examples that look like the training data.
A worked example by hand
A small café has six regular customers. For each, it records visits per month and average spend per visit (in dollars):
| Customer | Visits | Spend |
|---|---|---|
| Ana | 2 | 10 |
| Ben | 3 | 12 |
| Cai | 2 | 11 |
| Dee | 10 | 8 |
| Eli | 12 | 7 |
| Fay | 11 | 9 |
No one has labelled these customers, but a glance shows two groups. Clustering: Ana, Ben and Cai visit rarely and spend more; Dee, Eli and Fay visit often and spend less. Summarise each group by its average (its centre):
- Occasional group: visits , spend .
- Regulars: visits , spend .
Now each customer can be described by one word, "occasional" or "regular", instead of two numbers. That is a crude form of compression, and it is useful: the café might send the regulars a loyalty card and the occasional visitors a voucher.
Density: a new customer, Gus, visits 25 times a month and spends $40 a visit. He is far from both centres. Gus doesn't fit the learned picture of "normal", so he stands out. Maybe he's buying for an office, maybe it's a data-entry error. Either way he deserves a look. That is Anomaly Detection in one line.
The judgement call: visits range from 2 to 12 and spend from 7 to 12, so the two features are on similar scales here. Had spend been recorded in cents (700 to 1,200), it would dominate any distance calculation and the clustering would be almost entirely about spend. Scaling is a decision about what "similar" means.
How do you know if it worked?
This is the hardest part of unsupervised learning. In supervised learning you compare predictions with true labels. Here there are none. The options:
- Internal measures score how tight and well separated the clusters are, such as the silhouette score, or how much variance a reduced representation keeps (PCA's explained variance). They tell you about geometry, not usefulness.
- External measures, when you happen to have some labels. The adjusted Rand index (ARI) compares a clustering with known categories: 1 means identical groupings, 0 means no better than random. The code below uses it.
- Downstream performance. Use the clusters or reduced features as input to a supervised task and see whether it improves.
- Human inspection. Look at examples from each cluster. Do they make sense? Can a domain expert name them? In practice this is often the deciding test.
Where it is used
- Exploration. Before modelling anything, plotting a dataset with PCA or UMAP and clustering it reveals subgroups, mistakes and surprises.
- Customer segmentation and market research.
- Preprocessing. Reducing 10,000 features to 50 speeds up and often improves a downstream supervised model.
- Anomaly detection for fraud, intrusions, machine faults and data-quality checks.
- Recommendations. Matrix factorisation learns hidden "taste" dimensions from who-bought-what, without anyone labelling tastes. See Recommender Systems.
- Pretraining. Learning general representations from unlabelled data, then fine-tuning with a few labels. This is how modern language and vision models are built (see Self-Supervised Learning and Pretraining Large Language Models).
- Semi-supervised learning combines a little labelled data with a lot of unlabelled data.
In code
All three tasks on the same dataset with scikit-learn: 1,797 small images of handwritten digits. The labels exist, but we hide them until the end and use them only to check the clusters.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
from sklearn.metrics import adjusted_rand_score
from sklearn.mixture import GaussianMixture
X, y = load_digits(return_X_y=True) # 1,797 images of handwritten digits, 8x8 = 64 pixels each
print("data shape:", X.shape) # we ignore y (the true digit) until the very end
# 1. Dimensionality reduction: 64 numbers per image -> 10
pca = PCA(n_components=10).fit(X)
Z = pca.transform(X)
print(f"10 components keep {pca.explained_variance_ratio_.sum():.0%} of the variance")
# 2. Clustering: group the images into 10 clusters, without labels
clusters = KMeans(n_clusters=10, n_init=10, random_state=0).fit_predict(Z)
print("cluster sizes:", np.bincount(clusters))
# 3. Density estimation: how typical is each image?
gmm = GaussianMixture(n_components=10, random_state=0).fit(Z)
log_density = gmm.score_samples(Z)
print("least typical images:", np.argsort(log_density)[:5])
# Only now peek at the labels: how well do the clusters match the real digits?
print(f"agreement with true digits (ARI): {adjusted_rand_score(y, clusters):.2f}")
# data shape: (1797, 64)
# 10 components keep 74% of the variance
# cluster sizes: [173 89 219 178 162 181 179 171 245 200]
# least typical images: [ 492 1553 947 1593 444]
# agreement with true digits (ARI): 0.65
Without ever being told what a "3" or a "7" is, k-means on compressed pixels finds groups that agree substantially with the real digits (ARI 0.65, where 1 would be perfect). The groups are uneven, though: one cluster has 89 images and another 245, so some digits have been merged and others split. Plotting the five "least typical" images is a good exercise. They are usually oddly written digits.
Common pitfalls
- Believing the clusters are real. Clustering algorithms always return clusters, even on random noise. Ask k-means for 10 clusters and you get 10, whether or not the data has 10 groups. Check stability (do you get the same clusters on a resample?) and meaning (can you describe them?).
- Forgetting to scale. Most methods rely on distances, so a feature with big numbers dominates. Standardise, or deliberately weight features by importance.
- Choosing the number of clusters by staring. Use the elbow and silhouette methods from k-Means Clustering, and above all ask whether the grouping is useful.
- Over-reading 2D plots. A t-SNE or UMAP plot can show tidy islands that don't exist in the original space, and distances between islands mean little. See t-SNE and UMAP.
- Leaking labels. If you fit PCA or clustering on all your data, including the test set, before a supervised model, you leak information. Fit unsupervised steps on training data only, inside a pipeline.
Watch out Every clustering algorithm will find clusters, even in pure noise. A neat picture is not evidence. Test whether the structure survives resampling, and whether it means something to someone who knows the data.
Where it leads
- k-Means Clustering: the simplest and most used clustering method, plus hierarchical clustering and DBSCAN.
- PCA and Dimensionality Reduction: the workhorse of dimensionality reduction.
- t-SNE and UMAP: nonlinear maps for visualising embeddings and other high-dimensional data.
- Anomaly Detection: density and isolation methods for spotting the unusual.
- Autoencoders and variational autoencoders: neural networks that compress and reconstruct.
- Self-Supervised Learning: invent labels from the data itself (hide a word and predict it), which is how foundation models are pretrained.
- What Generative Models Do: learn the data distribution well enough to sample new examples.
A bit of history
Unsupervised methods are older than the name. Karl Pearson described what we now call principal component analysis in 1901, and Harold Hotelling developed it further in 1933. Cluster analysis grew up in psychology and biology in the 1930s to 1960s, for classifying personality traits and species. The k-means algorithm was devised by Stuart Lloyd at Bell Labs in 1957 (published in 1982) and named by James MacQueen in 1967. The EM algorithm of Dempster, Laird and Rubin (1977) made mixture models practical for density estimation.
In neural networks, unsupervised "pretraining" of layers by Geoffrey Hinton and colleagues in 2006 helped start the deep-learning revival. Today the line between supervised and unsupervised has blurred. Self-supervised learning on huge unlabelled datasets, followed by a little supervised fine-tuning, is the recipe behind modern language and vision models.
Try it
- Add a seventh café customer who visits 6 times a month and spends $10. Which group is she closer to? Use Euclidean distance to each centre.
- In the code, change
n_clustersto 5 and then to 20. How does the ARI change? Is a lower ARI necessarily a worse clustering?- Harder: display the five least typical digit images with
matplotlib(plt.imshow(X[i].reshape(8, 8), cmap="gray")). Do they look unusual to you?Hint for 1: her distances are and .
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
An Introduction to Statistical Learning (with Python)
The friendliest rigorous introduction to classical ML, with Python labs. Free PDF.
scikit-learn User Guide
Excellent documentation that doubles as a textbook, with explanations and examples for every algorithm.
Machine Learning Specialization
The best-known first course in ML. Covers regression, classification, neural nets, trees, clustering, recommenders and RL with Python labs.
StatQuest
Short, cheerful, very clear videos on statistics and nearly every ML algorithm.
scikit-learn: Clustering
k-means, DBSCAN, hierarchical clustering, Gaussian mixtures and more, with a famous side-by-side comparison chart.
Probabilistic Machine Learning
A comprehensive two-volume reference viewing ML through probability. Free drafts online.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/unsupervised-learning.md