Simple Algorithm
Machine Learning · Initialization · 17 min

Unsupervised Learning

Finding structure in data with no labels at all.

A supermarket has millions of shopping baskets, a hospital has thousands of gene readouts, and your phone has thousands of photos, and none of them come with answers attached. Unsupervised learning looks for the structure nobody labeled: groups of similar examples, a few directions that summarize many measurements, the places where data normally live. The catch: with no answer key, deciding whether that structure is real takes care.

What you’ll learn

  • Explain what unsupervised learning looks for without labels, and name its four main jobs: grouping, compressing, modeling where data live, and finding hidden factors.
  • Run k-means step by step, and explain why it can stop at a poor answer and why it cannot choose the number of clusters by itself.
  • Describe soft clustering with a mixture model, and read a point's membership probabilities.
  • Explain what principal component analysis keeps and what it throws away, read an explained-variance share, and give an example where the direction of greatest variance is not the useful one.
  • Explain how latent factors drive recommendations, and why evaluating unsupervised results is hard.

Data with no answers

In supervised learning every training example comes with the right answer, and a model is judged by how often it reproduces it. In unsupervised learning there are only the inputs: nn examples, each described by dd features, such as one shopper's spending in 20 product categories, the activity of 20,000 genes in a tissue sample, or the pixels of a photo. There is no label to predict and nothing to check the output against.

The goal is to describe the data themselves: what kinds of examples there are, which features move together, what is typical and what is unusual. Four jobs come up again and again.

JobQuestion it answersExampleMethods you will meet
Group: clusteringWhich examples are alike?Customer segments for a marketing teamk-means, mixture models
Compress: dimensionality reductionWhich few directions summarize many features?20,000 gene readings summarized by a handful of scoresprincipal component analysis
Model where data live: density estimationHow typical is this example?Flagging a card payment unlike anything the customer has made before (anomaly detection)histograms, mixture models
Find hidden factors: matrix factorizationWhat hidden tastes explain the ratings?Suggesting films a viewer has not seen (recommender systems)low-rank factorization
The jobs overlap. A mixture model, for example, groups points and is also a model of where they live.
Check your understanding

Which of these is an unsupervised learning problem?

  1. Predicting tomorrow's temperature from years of weather records
  2. Deciding whether an email is spam, using thousands of emails that users marked as spam or not
  3. Grouping news articles by topic when no list of topics exists
  4. Estimating a house's price from past sales
Show the answer

C. Grouping news articles by topic when no list of topics exists

The articles come with no answers: nobody has said which topics exist or which article belongs to which. Finding the groups is clustering, an unsupervised task. The other three learn to reproduce a known answer (a temperature, a spam mark, a sale price) and are supervised.

Grouping points: k-means

Picture customers as points on a chart, one axis per feature. If they form clumps, you want the clumps. k-means looks for kk groups (you choose kk) by placing kk centroids, one at the center of each group, and improving them in two alternating moves:

  1. Start with kk centroids, for example kk data points picked at random.
  2. Assign: every point joins its nearest centroid.
  3. Update: every centroid moves to the average position (the mean) of its points.
  4. Repeat steps 2 and 3 until no point changes group.

The score k-means drives down is the inertia: the total, over all points, of the squared distance from each point to its own centroid. Tight groups have small inertia.

Check your understanding

On the three-blob data, the lowest inertia found for k=1,2,3,4,5k = 1, 2, 3, 4, 5 is 66.7,32.7,8.12,6.8666.7, 32.7, 8.12, 6.86 and 5.845.84. Which number of clusters do these values suggest?

  1. k=5k = 5, because it has the lowest inertia
  2. k=1k = 1, because the simplest model is best
  3. k=3k = 3, because inertia falls steeply up to 33 and only slowly after
  4. None: inertia says nothing about the number of clusters
Show the answer

C. k=3k = 3, because inertia falls steeply up to 33 and only slowly after

Going from 2 to 3 clusters cuts the inertia by about 24.6; going from 3 to 4 cuts it by only 1.3. That bend, the elbow, says the third cluster captures real structure while later ones mostly split existing blobs. The lowest value is no guide, because the best inertia keeps falling as kk grows: with one cluster per point it is zero.

Soft clusters and the shape of a group

k-means makes two strong choices. Every point belongs to exactly one cluster, and every cluster is treated as a round blob: a point simply goes to the nearest centroid, so the border between two clusters is the straight line halfway between their centroids. Real groups can be stretched, overlapping or curved. On two interleaved half-moons, k-means with k=2k = 2 lands on practically the same answer from every start: a straight border that cuts the end off each moon and hands it to the other cluster. Its two groups agree with the true moons on only about three points in four.

A Gaussian mixture model describes each group as a bell-shaped cloud with its own center, its own spread and tilt (drawn as an ellipse) and its own share of the data. It is fitted by the EM algorithm, which alternates two steps much like k-means:

  • E-step: for every point, compute the probability that each cloud produced it. These are the point's responsibilities, and they add up to 100%.
  • M-step: refit each cloud's center, ellipse and share as averages in which every point counts in proportion to its responsibility.
Think first A fitted mixture gives a point responsibilities of 52% for one cloud and 48% for another. What should a careful analyst conclude?

The point sits between two groups, and the model cannot tell which one produced it. Forcing it into one cluster, as k-means would, throws that uncertainty away. Report the probabilities, or flag such points for a closer look.

Compressing: the directions that matter

Many datasets have far more features than anyone can look at, and the features are often redundant: height and arm span rise together, and so do the prices of neighboring houses. Principal component analysis (PCA) replaces the original axes with new ones. The first principal component is the direction along which the data vary most: measured along it, the points have the largest variance, their average squared distance from the mean. The second is the direction of greatest remaining variation at right angles to the first, and so on.

Keeping only the first few components and projecting every point onto them compresses the data. Of all the ways to flatten the points onto a line, a plane or another flat space with that many dimensions, this one moves them the least, measured as total squared distance.

share of variance kept by the first m components=λ1+⋯+λmλ1+⋯+λd\text{share of variance kept by the first } m \text{ components} = \frac{\lambda_1 + \dots + \lambda_m}{\lambda_1 + \dots + \lambda_d}
λj\lambda_j is the variance of the data along component jj, and λ1≥λ2≥…\lambda_1 \ge \lambda_2 \ge \dots. This share, the explained variance, is the bar chart in the widget.
Predict before you look

A 2-D cloud of points has variance 9 along its first principal component and 1 along its second. What percentage of the variance does the first component keep?

Show the answer

90 %

9/(9+1)=90%9 / (9 + 1) = 90\%. Projecting onto that single direction keeps 90% of the spread and discards the 10% across it. The pca widget's default dataset is a cloud much like this one: its first component keeps 90.8%.

Most variance is not most important

PCA ranks directions by how much the data spread along them, and nothing in that ranking reflects what you care about. A direction with little spread can still be the one that matters. Units matter too: record income in dollars and schooling in years, and income's large numbers take over the first component simply because they are large. Standardizing each feature first, to mean 0 and standard deviation 1, puts features measured in different units on an equal footing.

Check your understanding

A team compresses 50 measurements per patient to the first 2 principal components, which keep 95% of the variance, and trains a disease classifier on those 2 numbers. What is the risk?

  1. None: keeping 95% of the variance keeps 95% of the information about the disease
  2. The direction that separates sick from healthy patients may have little variance and be thrown away
  3. PCA always removes the disease signal, because it ignores labels
  4. Two components are never enough for a classifier
Show the answer

B. The direction that separates sick from healthy patients may have little variance and be thrown away

PCA keeps what varies most, whatever the cause: age, body size, the machine that took the measurement. If the disease shows up along a low-variance direction, it lands in the discarded 5%, exactly as the blue and pink groups land on PC2 above. Check by comparing the classifier with and without the reduction, or by using a method that looks at the labels.

Hidden factors, honest evaluation, and what comes next

The fourth job finds hidden factors. A film service keeps a huge table of ratings, one row per user and one column per film, and almost every cell is empty because each person rates only a few films. Suppose each film can be described by two hidden numbers, say how much action and how much romance it has, and each user by two numbers saying how much they enjoy each. A rating is then predicted as (taste for action × amount of action) + (taste for romance × amount of romance). Nobody writes these factors down: matrix factorization learns them from the ratings people did give, then uses them to fill in the empty cells.

Predict before you look

A viewer's tastes are (action 2, romance 0.5), and a film's profile is (action 1.5, romance 2). What rating does this two-factor model predict?

Show the answer

4

2×1.5+0.5×2=3+1=42 \times 1.5 + 0.5 \times 2 = 3 + 1 = 4. The viewer loves action, so the film's action carries most of the prediction. Real systems learn tens to hundreds of factors, and the learned factors rarely have names as tidy as "action".

How do you know any of this worked? There is no test set of correct answers. Worse, the usual scores always improve with more structure: the best inertia keeps falling as you add clusters, and a mixture's best likelihood keeps rising as you add clouds. Analysts lean on other evidence instead: whether the result is stable across restarts and subsamples, whether a model of where data live gives high probability to new data, whether a few labeled examples agree with it, and whether it helps the task it was built for. There is even a theorem: no clustering rule can satisfy three natural requirements at once (Kleinberg, 2002). The Convergence lesson Hierarchical & Density-Based Clustering proves it.

Descent lessonWhat you will do there
ClusteringProve that k-means never increases its objective, seed it with k-means++, choose kk with the silhouette and the gap statistic, and meet hierarchical, density-based and mixture-model clustering.
Dimensionality ReductionDerive PCA from variance, compute it with the singular value decomposition, measure what a projection loses, standardize, and see when nonlinear maps such as t-SNE and UMAP are needed.
Density Estimation & AnomaliesBuild histograms and kernel density estimates, tune the bandwidth, fit mixtures, and turn low density into anomaly scores.
Matrix Factorization & RecommendersFit latent factors to a mostly empty ratings matrix with alternating least squares, and handle missing entries, new users and implicit feedback.
In the Descent lessons each idea gets its math and its algorithms. The Convergence lessons go further: why finding the lowest-inertia clustering is NP-hard and what k-means++ guarantees, hierarchical, density-based and spectral clustering, probabilistic and high-dimensional PCA, t-SNE and UMAP, random projections, kernel density estimation, anomaly and out-of-distribution detection, normalizing flows, collaborative filtering, matrix completion, and NMF, ICA and sparse coding.

Key takeaways

  • Unsupervised learning finds structure in inputs alone: groups (clustering), compact descriptions (dimensionality reduction), where data live (density estimation and anomalies) and hidden factors (matrix factorization).
  • k-means alternates assigning points to the nearest centroid and moving each centroid to the mean of its points. Inertia never rises, so it always stops, but at a local optimum that depends on the start; restarts and k-means++ help, and kk must be chosen separately.
  • A Gaussian mixture gives soft, elliptical clusters: each point gets responsibilities that add up to 1, and the fitted mixture doubles as a density model that can flag unusual points.
  • PCA keeps the directions of greatest variance, and the explained-variance share says how much is kept. Variance is not importance, and features in different units should be standardized first.
  • Without labels, evaluation is hard: inertia and likelihood keep improving with more structure. Stability, likelihood on new data, a few labels and usefulness downstream are the evidence to look for.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why can't you choose the number of clusters kk by picking the value with the smallest inertia?

  1. Inertia is too noisy to compare across values of kk
  2. The best inertia only goes down as kk grows, reaching zero with one cluster per point
  3. Inertia rises with kk, so it would always pick k=1k = 1
  4. Inertia measures the distances between clusters, not within them
Show the answer

B. The best inertia only goes down as kk grows, reaching zero with one cluster per point

Adding a cluster can never make the best achievable inertia worse, and nn clusters for nn points give zero. The minimum therefore always sits at the largest kk allowed. Choosing kk needs other evidence: an elbow in the curve, stability, or usefulness.

Question 2

You run k-means twice on the same data with k=3k = 3 from different random starts. The runs end at inertias 8.1 and 31.3. What happened?

  1. The second run has a bug, because k-means always finds the same answer
  2. The data must have changed between the runs
  3. The first run overfitted the data
  4. The second run stopped at a worse local optimum; keep the lower inertia, or use k-means++ and several restarts
Show the answer

D. The second run stopped at a worse local optimum; keep the lower inertia, or use k-means++ and several restarts

k-means always stops, but where it stops depends on where it started. A bad start can leave one centroid covering two groups while two centroids split a third, and no single assign or update step can fix that. Running several starts and keeping the lowest inertia, or seeding with k-means++, avoids most such traps.

Question 3

What does the first principal component of a dataset maximize?

  1. The separation between the groups in the data
  2. The correlation with the label
  3. The variance of the data projected onto it
  4. The number of original features it uses
Show the answer

C. The variance of the data projected onto it

PC1 is the direction along which the projected points spread out the most. Equivalently, projecting onto it moves the points the least in total squared distance. It uses no labels and no notion of groups.

Question 4

What do a point's responsibilities under a fitted Gaussian mixture tell you?

  1. The probability that each component generated that point
  2. The distance from the point to each component's center
  3. Each component's share of all the data
  4. How many points each component contains
Show the answer

A. The probability that each component generated that point

Responsibilities are the point's membership probabilities, one per component, adding up to 1. They are computed from the point's position, each cloud's shape and each cloud's share, so a point near the edge of a big cloud can belong to it more than to a nearer, smaller one.

Question 5

You run PCA on customer records with yearly income in dollars (spread across tens of thousands) and number of children (spread of about 1). What will the first principal component mostly measure?

  1. Number of children, because it varies relative to its mean
  2. An equal mix of both features
  3. Nothing useful: PCA needs at least three features
  4. Income, because its numbers vary vastly more
Show the answer

D. Income, because its numbers vary vastly more

PCA works with raw variances, and income's variance in dollars dwarfs that of a small count. PC1 points almost exactly along income. Standardizing both features first lets PCA look at how they vary together instead of at their units.

Go deeper

Further reading

  • G. James, D. Witten, T. Hastie & R. Tibshirani, An Introduction to Statistical Learning, 2nd ed. (Springer, 2021), chapter 12.
  • K. Pearson, "On lines and planes of closest fit to systems of points in space," Philosophical Magazine (6th series) 2(11), 559–572 (1901).