# Unsupervised learning explained: clustering, PCA, density estimation and anomaly detection

Unsupervised learning finds structure in data that has no labels. This guide explains the four main jobs, clustering, dimensionality reduction, density estimation and anomaly detection, with their objectives, hand-checkable numbers and runnable scikit-learn 1.9 code.

Most data in the world has no labels. Logs, transactions, sensor readings, images and documents arrive without anyone saying what group they belong to or which ones are unusual. Unsupervised learning is the family of methods that finds structure in that raw data on its own: groups of similar points, a few directions that explain most of the variation, the shape of the probability distribution, and the rare points that do not fit.

These methods matter even in the era of large models. Embedding spaces from foundation models are explored with clustering and projection. Training datasets are deduplicated by clustering near-identical documents. Fraud and fault detection still rely on density and isolation scores. This article explains the four main jobs one at a time, with the objective each one optimises, numbers you can check by hand and code that runs on current libraries.

## What happened

### umap-learn 0.6.0 is released (10 November 2026)

The UMAP library for non-linear dimensionality reduction published version 0.6.0 on PyPI on 10 November 2026, a week after a 0.6.0 release candidate, ending a long run of 0.5.x releases. UMAP is the most common way to draw two-dimensional maps of embedding spaces, so a new release is relevant to anyone visualising model representations.

### PyOD 3.6.9 updates the main Python outlier detection toolkit (22 November 2026)

PyOD, which collects dozens of anomaly detection algorithms behind one interface, uploaded version 3.6.9 to PyPI on 22 November 2026. Alongside scikit-learn 1.9.1, the current stable scikit-learn released on 10 September 2026, it forms the usual toolbox for the methods in this article.

## Clustering: grouping points without labels

Clustering assigns each point to a group so that points in the same group are similar. The most used algorithm, k-means, minimises the within-cluster sum of squares, also called inertia:

J = Σ_k Σ_{x in cluster k} ||x − μ_k||²

where μ_k is the mean of cluster k. Lloyd's algorithm alternates two steps until nothing changes: assign each point to its nearest centre, then move each centre to the mean of its points. Each step can only lower J, so the algorithm always stops, though possibly in a local minimum. That is why scikit-learn runs several random starts (`n_init`) with k-means++ seeding and keeps the best.

**Worked example.** Take five numbers on a line: 1, 2, 6, 7, 8, and start with centres at 1 and 8. Point 6 is 5 away from the first centre and 2 from the second, so it joins the second. The groups are {1, 2} and {6, 7, 8}. The new centres are 1.5 and 7. Re-assigning changes nothing, so the algorithm has converged. Inertia is (0.5² + 0.5²) + (1² + 0² + 1²) = 0.5 + 2 = 2.5. You can watch the same two steps in two dimensions in the [k-means simulation](/ai-simulations/k-means-clustering).

K-means has strong assumptions. It expects round clusters of similar size and it forces every point into a cluster. Density-based methods relax both. HDBSCAN, built into scikit-learn since version 1.3, finds regions where points are packed densely, builds a hierarchy of those regions and keeps the most stable ones. It picks the number of clusters itself and labels points in sparse regions as noise (label −1). The trade-off is speed and a different main knob, `min_cluster_size`.

**Choosing k.** Inertia always falls as k grows, so it cannot choose k alone. The silhouette score compares, for each point, the mean distance a to its own cluster with the mean distance b to the nearest other cluster: s = (b − a) / max(a, b). It ranges from −1 to 1, and higher is better.

## Dimensionality reduction: keeping the directions that matter

High-dimensional data often lies near a much smaller surface. Principal component analysis (PCA) finds the orthogonal directions of greatest variance. Formally, it takes the covariance matrix Σ of centred data and computes its eigenvectors. The eigenvalue λ_j of each eigenvector is the variance along it, and the explained variance ratio is λ_j / Σ λ. Projecting onto the top few eigenvectors keeps as much variance as any linear projection of that size can.

**Worked example.** Take four points: (2, 0), (0, 1), (−2, 0) and (0, −1). They are already centred. The variance along x is (4 + 0 + 4 + 0) / 4 = 2 and along y is (0 + 1 + 0 + 1) / 4 = 0.5, with zero covariance. The eigenvalues are 2 and 0.5, so the first component (the x axis) explains 2 / 2.5 = 80 percent of the variance. Dropping y keeps 80 percent of the information in this sense. The [PCA simulation](/ai-simulations/pca) shows the same idea on a rotated cloud of points.

PCA is linear. Non-linear methods such as t-SNE and UMAP build a graph of nearest neighbours in the original space and arrange points in two dimensions to preserve that graph. They produce clearer pictures of clusters, but distances between far-apart groups and the size of clusters on the map do not carry reliable meaning. Use them to look, not to measure. The [embedding map simulation](/ai-simulations/embedding-map) shows how a projection can make separate groups look closer or further apart than they are.

| Method | Linear | Keeps global distances | Typical use | Main knob |
|---|---|---|---|---|
| PCA | Yes | Approximately | Compression, denoising, preprocessing | Number of components |
| t-SNE | No | No | 2D pictures of local clusters | Perplexity |
| UMAP | No | Somewhat better than t-SNE | 2D maps of embeddings, preprocessing | n_neighbors, min_dist |
| Autoencoder | No | Depends on training | Learned compression, anomaly scores | Bottleneck size |

## Density estimation and anomaly detection

Density estimation asks a more ambitious question: what is the probability distribution p(x) that generated the data? Once you have it, you can sample new points, compare likelihoods and flag points with low probability as anomalies.

A Gaussian mixture model writes the density as a weighted sum of K Gaussians:

p(x) = Σ_k π_k · N(x | μ_k, Σ_k)

and fits it by maximising the log-likelihood Σ_i log p(x_i) with the expectation-maximisation (EM) algorithm. The E-step computes, for each point, the probability that each component produced it. The M-step re-estimates weights, means and covariances from those soft assignments. K-means is the limit of this procedure with hard assignments and equal spherical covariances. To pick K, use the Bayesian information criterion, BIC = −2 log L + p log n, where p is the number of parameters and n the number of points. Lower is better, and the p log n term stops the model from adding components forever.

Anomaly detection does not always need a full density. An isolation forest builds random trees that split on a random feature at a random value. Unusual points sit in sparse regions, so they get isolated after only a few splits. The anomaly score is s = 2^(−E[h(x)] / c(n)), where E[h(x)] is the average path length to isolate x and c(n) is the average path length of an unsuccessful search in a binary tree with n points. For the default subsample of 256 points, c(256) is about 10.2. A point isolated after 3 splits on average gets s = 2^(−3/10.25) ≈ 0.82, a strong anomaly. A point with an average path equal to c(n) gets exactly 0.5, which means it is unremarkable. Think of a game of twenty questions: the stranger at a party is identified in fewer questions than one of a hundred people in matching uniforms.

## Runnable code: all four jobs in scikit-learn 1.9

```python
import numpy as np
from sklearn.datasets import make_blobs, load_digits
from sklearn.cluster import KMeans, HDBSCAN
from sklearn.metrics import silhouette_score, adjusted_rand_score
from sklearn.decomposition import PCA
from sklearn.mixture import GaussianMixture
from sklearn.ensemble import IsolationForest

X, y_true = make_blobs(n_samples=600, centers=4, cluster_std=1.0, random_state=7)
for k in range(2, 7):
    km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
    print(f"k={k} inertia={km.inertia_:8.1f} silhouette={silhouette_score(X, km.labels_):.3f}")
km = KMeans(n_clusters=4, n_init=10, random_state=0).fit(X)
print("ARI vs hidden labels:", round(adjusted_rand_score(y_true, km.labels_), 3))
hd = HDBSCAN(min_cluster_size=20, copy=True).fit(X)
print("HDBSCAN clusters:", len(set(hd.labels_) - {-1}), "noise points:", int((hd.labels_ == -1).sum()))

D, _ = load_digits(return_X_y=True)
cum = np.cumsum(PCA().fit(D).explained_variance_ratio_)
print("components for 90% variance:", int(np.searchsorted(cum, 0.90) + 1), "of", D.shape[1])

for n in [2, 4, 6]:
    gm = GaussianMixture(n_components=n, random_state=0).fit(X)
    print(f"GMM n={n} BIC={gm.bic(X):.1f}")

rng = np.random.default_rng(0)
Z = np.vstack([X, rng.uniform(-20, 20, size=(20, 2))])
iso = IsolationForest(contamination=20 / len(Z), random_state=0).fit(Z)
flag = iso.predict(Z) == -1
print("flagged:", int(flag.sum()), "true outliers caught:", int(flag[-20:].sum()))
```

Output on scikit-learn 1.9.1:

```text
k=2 inertia= 18363.1 silhouette=0.588
k=3 inertia=  5241.2 silhouette=0.762
k=4 inertia=  1127.4 silhouette=0.811
k=5 inertia=  1019.9 silhouette=0.680
k=6 inertia=   921.1 silhouette=0.577
ARI vs hidden labels: 1.0
HDBSCAN clusters: 4 noise points: 0
components for 90% variance: 21 of 64
GMM n=2 BIC=6193.8
GMM n=4 BIC=5132.9
GMM n=6 BIC=5193.1
flagged: 20 true outliers caught: 18
```

Inertia keeps falling after k = 4, but the drop from 4 to 5 is small (1127 to 1020) compared with the drop from 3 to 4 (5241 to 1127). That bend is the "elbow". The silhouette score peaks clearly at k = 4 with 0.811, and the adjusted Rand index of 1.0 confirms a perfect match with the hidden labels, which you would not have in real work. HDBSCAN finds the same four groups without being told k. On the digits data, 21 of 64 pixel features keep 90 percent of the variance. BIC is lowest at four Gaussians and rises again at six. The isolation forest flags 20 points and 18 of them are the injected outliers. The other two injected points happened to land close to a real cluster, which is what any density-based detector should do with them.

## What goes wrong in practice

**Scale decides the answer.** K-means, PCA and most distance-based methods treat all features equally in raw units. A feature measured in thousands drowns one measured in fractions. Standardise first unless the units are already comparable.

**There is no ground truth.** Without labels, a clustering is only as good as its usefulness. Internal scores such as silhouette favour certain shapes. Check clusters against a downstream task or human review.

**High dimensions flatten distances.** In hundreds of dimensions, nearest and farthest neighbours end up at similar distances. Reduce dimension with PCA first or use embeddings designed for cosine similarity.

**Pictures mislead.** t-SNE and UMAP maps change with random seeds and settings. Do not read cluster sizes or gaps between clusters as facts.

**Anomaly thresholds are guesses.** The `contamination` parameter sets how many points are flagged. If you do not know the true anomaly rate, rank by score and review the top of the list instead of trusting a fixed cut.

## How unsupervised learning is used in today's models

Large models made unsupervised methods more useful, not less. Teams cluster document embeddings to deduplicate and balance pretraining corpora, because near-duplicate text wastes compute and encourages memorisation. They cluster user prompts to discover what people actually ask and to build evaluation sets that cover each group. Vector databases use k-means inside inverted file indexes to partition millions of embeddings, so a search only visits a few clusters. Product quantisation, which compresses those vectors, runs k-means on sub-vectors.

Representation learning blurs the line further. Self-supervised pretraining learns features without labels, and the result is then explored with PCA, UMAP and clustering. Interpretability research uses sparse autoencoders, an unsupervised method, to split model activations into more interpretable features. For tables, the [tabular anomaly detection simulation](/ai-simulations/tfm-anomaly-detection) shows a foundation model scoring unusual rows in context.

## What it means in practice

Unsupervised learning answers questions you could not ask with labels: what groups exist, which few factors explain the variation, how likely a new point is, and what does not belong. Each method encodes assumptions about shape and scale, and the output is a hypothesis to test, not a fact. The best workflows pair a fast method such as k-means or PCA for a first look with a more flexible one such as HDBSCAN or a mixture model, then validate the result against a real decision.

## What to do now

1. **Standardise before distances.** Scale numeric features with `StandardScaler` or use cosine distance on normalised embeddings.
2. **Look at inertia and silhouette together.** Use the elbow and the silhouette peak to shortlist k, then inspect example points from each cluster.
3. **Try HDBSCAN when shapes are irregular.** It finds the number of clusters itself and marks noise instead of forcing every point into a group.
4. **Use PCA as a first step.** Keep enough components for 90 to 95 percent of the variance before clustering or before running t-SNE or UMAP.
5. **Fit mixtures with BIC.** Compare several component counts and covariance types and keep the lowest BIC.
6. **Rank anomalies, do not just flag them.** Sort by `score_samples` and review the top of the list with someone who knows the domain.
7. **Fix seeds and report stability.** Rerun with several random seeds and measure how often points stay in the same cluster.
8. **Validate against a task.** Check whether clusters improve a downstream model, a search result or a human workflow.

## Risks and open questions

**Clusters can create false categories.** A clean-looking segmentation of customers or patients may reflect preprocessing choices more than reality. Decisions based on it need independent validation.

**Anomaly detectors drift.** What is unusual changes as behaviour changes. A detector trained last year may flag normal new patterns and miss new attacks.

**Embeddings carry their training biases.** Clustering foundation-model embeddings inherits whatever the model learned, including spurious associations.

**Watch next:** what changed in umap-learn 0.6 for large embedding maps, and how density-based clustering is used to curate and deduplicate the next generation of pretraining datasets.

## Frequently asked questions

### When should I use k-means instead of HDBSCAN?

Use k-means when clusters are roughly round, similar in size and you have a good guess of k, because it is fast and simple. Use HDBSCAN when shapes are irregular, densities differ or you expect noise points. HDBSCAN is slower on very large datasets but needs no k.

### How many principal components should I keep?

A common rule is enough components to explain 90 to 95 percent of the variance, which took 21 of 64 features on the digits data. If PCA feeds a model, treat the number of components as a hyperparameter and tune it with cross-validation.

### Is t-SNE or UMAP better?

Both are good for pictures. UMAP is usually faster on large datasets and tends to keep somewhat more global structure, while t-SNE is very good at separating local clusters. Neither preserves distances reliably, so use them to explore, not to measure.

### How do I evaluate clustering without labels?

Use internal scores such as silhouette or Davies-Bouldin to compare settings, check stability across seeds and subsamples, and inspect samples from each cluster. The final test is whether the clusters help a real task.

### Can anomaly detection work without any labelled anomalies?

Yes. Isolation forests, one-class SVMs, local outlier factor and density models all learn what normal looks like and score deviations. A small set of labelled anomalies is still valuable for choosing the threshold and measuring precision.

## Summary

Unsupervised learning finds structure without labels through four jobs. K-means minimises within-cluster squared distance and, in the worked example, converged to inertia 2.5 in one step. PCA keeps the directions of greatest variance, 80 percent in the four-point example and 21 of 64 features for 90 percent on digits. Gaussian mixtures estimate densities with EM and choose their size by BIC. Isolation forests score anomalies by how quickly random splits isolate a point. Each method encodes assumptions, so scale your data, check stability and validate against a real task. For more context, see [unsupervised learning](/tools/unsupervised-learning), [clustering](/tools/clustering), [isolation forests](/tools/isolation-forest) and [UMAP](/tools/umap).

## Sources

- [scikit-learn: Clustering user guide](https://scikit-learn.org/stable/modules/clustering.html)
- [scikit-learn: Decomposing signals in components (PCA)](https://scikit-learn.org/stable/modules/decomposition.html)
- [scikit-learn: Gaussian mixture models](https://scikit-learn.org/stable/modules/mixture.html)
- [scikit-learn: Novelty and outlier detection](https://scikit-learn.org/stable/modules/outlier_detection.html)
- [IEEE: Isolation Forest (Liu, Ting and Zhou, ICDM 2008)](https://ieeexplore.ieee.org/document/4781136)
- [arXiv: UMAP, Uniform Manifold Approximation and Projection (McInnes et al., 2018)](https://arxiv.org/abs/1802.03426)
- [PyPI: umap-learn 0.6.0](https://pypi.org/project/umap-learn/0.6.0/)
- [PyPI: pyod 3.6.9](https://pypi.org/project/pyod/3.6.9/)
