UMAP & Clustering
High-dimensional data is hard to cluster and impossible to eyeball. A gene-expression matrix has thousands of genes per cell; the digits used here have 64 pixels each. UMAP reduces that to two dimensions you can plot, and it keeps points that were close in the original space close in the projection. Once the natural groups are pulled apart, a plain clusterer finds them.
This page runs the whole loop on the bundled scikit-learn digits: reduce to 2D, cluster, and check the clusters against the digit labels we happen to know. Every code block runs in a container in the companion repository, so the numbers and figures are real.
Load the data
Section titled “Load the data”1797 handwritten digits, each an 8x8 image flattened to 64 features. Scaling matters: UMAP works on distances, so features on different scales would distort them.
The digit images come from Alpaydin and Kaynak, Optical Recognition of Handwritten Digits, 1998. UCI distributes the data under CC BY 4.0. This lesson uses the 1797-image scikit-learn subset and derives standardized features, projections, and cluster assignments.
from pathlib import Path
import matplotlib.pyplot as pltfrom sklearn.datasets import load_digitsfrom sklearn.preprocessing import StandardScaler
out = Path("outputs")out.mkdir(exist_ok=True)
digits = load_digits()features = StandardScaler().fit_transform(digits.data)y = digits.targetprint(features.shape, "->", len(set(y)), "known classes (digits 0-9)")(1797, 64) -> 10 known classes (digits 0-9)Reduce to 2D with UMAP
Section titled “Reduce to 2D with UMAP”Two parameters carry most of the behavior. n_neighbors sets how much local versus global
structure UMAP preserves, and min_dist sets how tightly points may pack. Setting
random_state makes UMAP single-threaded and deterministic, so the projection is the same
on every run.
import umap
reducer = umap.UMAP(n_neighbors=15, min_dist=0.1, n_components=2, random_state=42)embedding = reducer.fit_transform(features)print(embedding.shape)(1797, 2)Cluster the projection and score it
Section titled “Cluster the projection and score it”Clustering runs on the 2D embedding rather than the raw 64 dimensions. UMAP has already separated the groups, so KMeans with ten clusters recovers them. Because the digits carry true labels, three scores say how well the clusters match: the adjusted Rand index and adjusted mutual information compare clusters to labels and are corrected for chance, and the silhouette measures how well separated the clusters are on their own.
from sklearn.cluster import KMeansfrom sklearn.metrics import (adjusted_mutual_info_score, adjusted_rand_score, silhouette_score)
clusters = KMeans(n_clusters=10, n_init=10, random_state=42).fit_predict(embedding)
ari = adjusted_rand_score(y, clusters)print(f"adjusted Rand index {ari:.3f}")print( f"adjusted mutual information {adjusted_mutual_info_score(y, clusters):.3f}")print( f"silhouette (on embedding) {silhouette_score(embedding, clusters):.3f}")adjusted Rand index 0.871adjusted mutual information 0.896silhouette (on embedding) 0.705An adjusted Rand index of 0.871 is strong. KMeans never saw the labels, yet its ten clusters line up with the ten digits almost exactly. A crosstab of digit against cluster shows where they disagree. KMeans numbers its clusters in no particular order, so read each column by the digit that fills most of it.
import pandas as pd
table = pd.crosstab(y, clusters, rownames=["digit"], colnames=["cluster"])print(table.to_string())cluster 0 1 2 3 4 5 6 7 8 9digit0 0 178 0 0 0 0 0 0 0 01 27 0 154 0 0 0 1 0 0 02 164 0 0 0 0 0 3 0 10 03 0 0 0 0 0 0 170 0 1 124 0 0 1 0 0 172 0 5 3 05 0 0 0 177 1 0 1 0 0 36 0 0 0 0 181 0 0 0 0 07 0 0 0 1 0 0 0 178 0 08 0 0 3 0 0 0 4 0 167 09 0 0 0 2 1 0 2 30 3 142Most digits sit almost entirely in one cluster. The three largest disagreements are 30 nines in the cluster that holds 178 sevens, 27 ones in the cluster of 164 twos, and 12 threes in the cluster of 142 nines. The two panels below show the same story: colored by true digit and by KMeans cluster, the projection is nearly the same picture. In the left panel the strays are visible, with cyan nines next to the gray sevens at the top and orange ones at the lower tip of the green twos.
fig, axes = plt.subplots(1, 2, figsize=(10, 4.6))panels = ((axes[0], y, "Colored by true digit"), (axes[1], clusters, "Colored by KMeans cluster"))for ax, labels, title in panels: ax.scatter(embedding[:, 0], embedding[:, 1], c=labels, cmap="tab10", s=5, alpha=0.8) ax.set_title(title) ax.set_xlabel("UMAP 1") ax.set_ylabel("UMAP 2") ax.set_xticks([]) ax.set_yticks([])fig.suptitle(f"UMAP of digits: ARI {ari:.2f} between KMeans clusters " "and true labels")fig.tight_layout()fig.savefig(out / "umap-clusters.png", dpi=150)plt.close(fig)
The n_neighbors knob
Section titled “The n_neighbors knob”n_neighbors is the first parameter to reach for. Small values keep the view local, so the
data breaks into many tight islands. Large values pull in global structure, so you get
fewer, broader groups. There is no single correct value; it depends on whether you care
about fine subgroups or the overall layout. The same sweep on single-cell data is how you
decide between splitting rare cell states and showing the major lineages.
fig, axes = plt.subplots(2, 2, figsize=(9, 8))for ax, k in zip(axes.ravel(), (5, 15, 30, 100)): emb = umap.UMAP(n_neighbors=k, min_dist=0.1, random_state=42).fit_transform(features) ax.scatter(emb[:, 0], emb[:, 1], c=y, cmap="tab10", s=4, alpha=0.8) ax.set_title(f"n_neighbors = {k}") ax.set_xticks([]) ax.set_yticks([])fig.suptitle("Smaller n_neighbors favors local structure, larger favors global")fig.tight_layout()fig.savefig(out / "umap-neighbors.png", dpi=150)plt.close(fig)
Two cautions
Section titled “Two cautions”UMAP distances are not a metric you can read literally. The gap between two clusters in the plot does not mean they are that far apart in the original space, so do not compute distances on the embedding and treat them as real. And clustering on the embedding, while common and convenient, inherits whatever distortion UMAP introduced. When a cluster boundary matters, confirm it against the original features, not only the 2D picture.
Scientific references
Section titled “Scientific references”McInnes and colleagues, 2018 describe the UMAP software for uniform manifold approximation and projection.
Further reading
Section titled “Further reading”-
The original tutorial explains how dimensionality reduction changes density and clustering behavior. Its MNIST example differs from the 64-feature digits used here.
-
The loader documents the 1797 images and their 64 pixel features. It connects the bundled sample to the original UCI dataset and its class labels.