Explore 72 leukaemia patients with the diagnoses hidden: use PCA to find the main sources of variation, cluster the patients and test whether the clusters are real, and see why t-SNE and UMAP maps are for looking, not measuring.
Learning without answers
In Where AI fits: traditional methods and AI methods side by side you met the split between supervised and unsupervised learning. In supervised learning every sample comes with a right answer, its label, and a model learns to predict it. In unsupervised learning there are no labels: the method sees only the measurements and looks for structure in them. Before anyone trains a classifier on an omics table, they usually explore it this way first.
Three families of methods do most of this work: principal component analysis (PCA), clustering, and nonlinear embeddings such as t-SNE and UMAP. They serve quality control, discovery of unnamed subtypes, and pictures of thousands of measurements in two dimensions. All are easy to over-read, because these methods always return an answer.
This lesson uses the leukaemia data of Golub and colleagues: 72 patients and 7,129 gene probes measured on a microarray. Each patient has either acute lymphoblastic leukaemia (ALL) or acute myeloid leukaemia (AML). Here the diagnoses go into a drawer at the start. Every method runs without them, and only afterwards are they used to check what was found. The same data return later in this module, in Machine learning on an expression table, where the labels train a classifier. The code runs in Google Colab.
import numpy as np, pandas as pd
from sklearn.datasets import fetch_openml
d = fetch_openml("leukemia", version=1, as_frame=True, parser="auto")
X, labels = d.data, d.target # put the labels away for now
X = np.log10(X.clip(lower=100, upper=16000)) # floor, ceiling, then log10
spread = X.max() - X.min()
X = X.loc[:, spread > np.log10(5)] # drop genes that barely change
top = X.var().sort_values(ascending=False).index[:1000]
X_top = X[top] # the 1,000 most variable genes
print(X.shape, "->", X_top.shape)What this does
fetch_openmldownloads the table from OpenML, a public archive of datasets. The diagnoses are kept inlabelsand not touched again until the checks.clipandnp.log10set a floor and ceiling on the raw fluorescence values and take logarithms, so a tenfold change becomes a step of 1.- Genes with less than a five-fold range are dropped, and of the rest the 1,000 with the highest variance are kept.
Preparing the table, then PCA
Unsupervised methods compare samples by a distance between their rows of numbers, and whatever dominates the numbers dominates the distance. Three preparation choices matter most.
- Log transform. Raw expression is skewed: a few very high genes would decide every distance. On a log scale, equal steps mean equal fold changes. RNA-seq counts are first corrected for library size, as in Module 4, then logged after adding a small constant.
- Centring. Each gene's mean is subtracted, because PCA describes variation around the average sample. This is always done.
- Scaling. Dividing each gene by its standard deviation gives every gene equal weight. On log expression it is a real choice: it lifts thousands of quiet, noisy genes to the weight of the few that change a lot. DESeq2's PCA plot, for example, uses the 500 most variable genes and does not scale them.
PCA then finds new axes. The first principal component (PC1) is the direction along which samples vary most; PC2 is the direction of most remaining variation, at right angles to PC1, and so on. Each component is a weighted sum of genes, and the weights are its loadings. A sample's position along a component is its score. PCA is linear and deterministic: the same data always give the same components.
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
Z = StandardScaler(with_std=False).fit_transform(X_top) # centre each gene, keep its spread
pca = PCA(n_components=10, random_state=0)
scores = pca.fit_transform(Z) # one row per patient, one column per PC
ratio = pca.explained_variance_ratio_
print("variance explained (%):", np.round(ratio * 100, 1))
print("PC1 + PC2:", round(ratio[:2].sum() * 100, 1), "%")Reading the output
StandardScaler(with_std=False) centres without scaling, and explained_variance_ratio_ is each component's share of the total variation. PC1 captures 17.1% and PC2 9.0%, 26.1% together, and the shares then fall away slowly. That is typical of omics data: a few strong themes and a long tail of smaller ones and noise.
How to read this figure
Each bar is one component, and its height is the share of variation it explains. This is a scree plot. People look for an "elbow" where the bars level off; here they flatten from about PC5. The elbow is a rough guide. Many analyses keep the first 10 to 50 components for later steps.
What the components capture
A component is useful only if you can say what it means. Look at the genes with the largest loadings and at how scores relate to what you know about the samples. Now, for the first time, the labels come out of the drawer.
loadings = pd.Series(pca.components_[0], index=X_top.columns) # PC1's weight for each gene
order = loadings.sort_values()
print("most negative:", list(order.index[:3]))
print("most positive:", list(order.index[-3:]))
# only now open the drawer: does PC1 line up with the diagnosis?
s = pd.DataFrame(scores[:, :2], columns=["PC1", "PC2"])
print(s.groupby(labels.values).mean().round(1).to_string())Reading the output
ALL patients average −3.3 on PC1 and AML patients +6.1, while PC2 shows no difference. The largest source of variation among these genes is the diagnosis, found without being told about it. Among the genes loading most strongly towards the AML end is M27891_at, the probe for cystatin C. The sign of a component is arbitrary: another program might flip PC1, with no change in meaning.
This depended on the preparation. The next block repeats PCA four ways and asks how closely PC1 follows the diagnosis, as a correlation from 0 (unrelated) to 1 (identical).
def pc1_vs_diagnosis(data, scale):
z = StandardScaler(with_std=scale).fit_transform(data)
pc1 = PCA(n_components=1).fit_transform(z)[:, 0]
return abs(np.corrcoef(pc1, labels == "AML")[0, 1])
print("all 3,948 genes, scaled: ", round(pc1_vs_diagnosis(X, True), 2))
print("all 3,948 genes, centred: ", round(pc1_vs_diagnosis(X, False), 2))
print("top 1,000 genes, scaled: ", round(pc1_vs_diagnosis(X_top, True), 2))
print("top 1,000 genes, centred: ", round(pc1_vs_diagnosis(X_top, False), 2))Reading the output
With all 3,948 genes scaled to equal weight, PC1 has almost nothing to do with the diagnosis (0.12): thousands of quiet genes, each now counting fully, add up to other variation. Centring without scaling, or keeping the variable genes, brings the biology back. Decide these choices before you look, and report them.
PC1 captures the largest source of variation, whatever it is. Suppose half the samples were processed on another day and the chemistry nudged many genes. That is a batch effect: variation from how samples were handled, not from biology. These data have no batch information, so the next block simulates one, assigning each patient at random to day 1 or day 2 and shifting every gene on day 2 by a random, deliberately large amount.
rng = np.random.default_rng(0)
batch = rng.permutation(np.repeat([1, 2], 36)) # a made-up processing day per patient
drift = rng.normal(0, 0.4, X_top.shape[1]) # each gene shifts up or down on day 2
X_batch = X_top + np.outer(batch == 2, drift)
sc = PCA(n_components=2).fit_transform(StandardScaler(with_std=False).fit_transform(X_batch))
sc = pd.DataFrame(sc, columns=["PC1", "PC2"])
print(sc.groupby(batch).mean().round(1).rename(index=lambda b: f"day {b}").to_string())
print(sc.groupby(labels.values).mean().round(1).to_string())Reading the output
PC1 now separates the processing days, and the diagnosis has been pushed down to PC2. When batch is tangled with biology, for example cases from one hospital and controls from another, no method can pull them apart. So colour every PCA plot by each technical variable you have (date, plate, sequencing run, site) as well as by the biology.
Go deeper: PCA is linear, and what that costs
Each component is a straight line through gene space. Curved structure, such as cells moving along a branching path of differentiation, shows up only as a smear across several components, which is the main reason nonlinear embeddings exist. Linearity also helps: new samples can be scored with the same loadings, and the loadings say exactly which genes make each axis. For quality control and for preparing data for later steps, PCA is usually the right first tool.
Clustering: finding groups
Clustering assigns each sample to a group so that samples in the same group are similar. k-means asks for k, the number of clusters. It places k centres, assigns each sample to its nearest centre, moves each centre to the middle of its samples, and repeats until nothing changes. The result depends on the starting centres, so it is run from several starts (n_init) and the best run kept.
Two scores judge the result. The silhouette asks how much closer each sample is to its own cluster than to the next nearest; averaged, it runs from −1 to 1, higher meaning better separated, and it needs no labels. The adjusted Rand index (ARI) compares two groupings: 1 means identical, about 0 means chance agreement. Here it compares clusters with the diagnosis. Clustering runs on the ten PC scores rather than the 1,000 genes, a common way to reduce noise.
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score, adjusted_rand_score
P = scores # the 10 PC scores per patient
for k in range(2, 7):
km = KMeans(n_clusters=k, n_init=20, random_state=0).fit(P)
print(f"k={k} silhouette {silhouette_score(P, km.labels_):.2f}"
f" agreement with diagnosis (ARI) {adjusted_rand_score(labels, km.labels_):.2f}")km2 = KMeans(n_clusters=2, n_init=20, random_state=0).fit(P) print(pd.crosstab(km2.labels_, labels.values, rownames=["cluster"], colnames=[""]).to_string())
Reading the output
With two clusters, k-means finds the diagnosis almost exactly: 46 of 47 ALL patients in one cluster and 24 of 25 AML in the other (ARI 0.89). But the silhouette barely changes with k, and k = 3 scores slightly higher. On its own it would not have picked two. A commonly quoted rule of thumb calls an average silhouette below about 0.25 weak structure, yet here a weak-looking score sits on a real biological split: with many dimensions, distances between samples become more alike and such scores run low.
Hierarchical clustering
Hierarchical clustering starts with every sample alone and repeatedly joins the two closest groups, building a tree called a dendrogram, which you cut afterwards into clusters. Two choices define it: the distance between samples (Euclidean, or 1 minus correlation, which compares profile shapes) and the linkage, the distance between groups. Single linkage uses the closest pair, complete the farthest pair, average the mean of all pairs, and Ward's method joins the pair that least increases the spread within groups.
from scipy.cluster.hierarchy import linkage, fcluster
for method in ["ward", "complete", "average", "single"]:
tree = linkage(P, method=method, metric="euclidean")
groups = fcluster(tree, t=2, criterion="maxclust") # cut the tree into 2 groups
print(f"{method:9s} group sizes {np.bincount(groups)[1:]}"
f" ARI {adjusted_rand_score(labels, groups):.2f}")Reading the output
Same data, same distance, four answers. Ward's method recovers the diagnosis (ARI 0.84) and average linkage partly does. Complete linkage splits off 9 patients, and single linkage just one: it tends to chain, growing one long cluster and leaving outliers alone. Ward's is a sensible default for samples. A clustering result belongs to its settings, so report them.
Clusters always appear
A clustering method never answers "there are no groups". The next block clusters 72 rows of pure random noise, the same size as our PC table.
noise = np.random.default_rng(1).normal(size=(72, 10)) # 72 "patients", 10 columns of pure noise
for k in range(2, 6):
km = KMeans(n_clusters=k, n_init=20, random_state=0).fit(noise)
print(f"k={k} cluster sizes {np.bincount(km.labels_)}"
f" silhouette {silhouette_score(noise, km.labels_):.2f}")Reading the output
There is no structure here, yet k-means returns tidy clusters every time, and coloured on a plot they would look convincing. The silhouette is lower than on the leukaemia data (about 0.10 against 0.23), a hint but not proof. A useful comparison is to shuffle each column independently, re-cluster, and check that the real score stands clearly above the shuffled ones.
Real clusters should also be stable. The next block draws 20 bootstrap samples (72 patients drawn with replacement, so some appear twice and some not at all), re-clusters each, and compares with the clustering of the full data.
def stability(k, n=20):
full = KMeans(n_clusters=k, n_init=20, random_state=0).fit(P).labels_
out = []
for r in range(n):
idx = np.random.default_rng(r).choice(72, size=72, replace=True) # resample patients
km = KMeans(n_clusters=k, n_init=20, random_state=0).fit(P[idx])
out.append(adjusted_rand_score(full, km.predict(P)))
return np.median(out), min(out)
for k in [2, 3, 4]:
med, low = stability(k)
print(f"k={k} median ARI {med:.2f} worst {low:.2f}")Reading the output
Two clusters are stable (median ARI 0.94, though one resample drops to 0.64). Four are not (median 0.67): the extra splits move when the patients change. Name clusters that keep reappearing; treat the rest as unconfirmed.
Worked example · how good is 46 and 24?
share placed correctly = 70 ÷ 72 ≈ 97%
share if all 72 were called ALL = 47 ÷ 72 ≈ 65%
Step by step. Naming each cluster after its majority, 70 of 72 patients sit with their own diagnosis. But one group is larger, so lumping everyone together already "gets" 65% right. That is why ARI, which corrects for chance, is a better summary than a raw percentage. And in a real discovery study there are no labels to check against, which is why stability and comparison with noise matter so much.
t-SNE and UMAP: maps, not measurements
t-SNE (t-distributed stochastic neighbour embedding) and UMAP (uniform manifold approximation and projection) ignore global directions and focus on neighbours: for each sample, which others are closest in the full data. They then place samples on a flat map so those neighbours stay close. They are nonlinear, free to bend and fold the data.
They preserve who sits near whom. They distort almost everything else. The distance between clusters on the map does not say how different they are; a cluster's size does not say how varied its samples are, because these methods expand dense groups and shrink sparse ones; the empty space between clusters may be created by the method. Settings change the picture:
- Perplexity (t-SNE): roughly how many neighbours each point attends to, typically 5 to 50 and below the number of samples.
- n_neighbors (UMAP): the same role. Small values show fine local detail; large values keep more of the overall layout. The default is 15.
- min_dist (UMAP): how tightly points may pack, from dense clumps at 0 to spread-out clouds.
Both start from random positions, so fix the random seed (random_state). The block below measures two things on each map: the gap between the ALL and AML centres divided by the average group size, and how much bigger ALL looks than AML.
from sklearn.manifold import TSNE
def describe(emb):
g = labels.values
c = {v: emb[g == v].mean(axis=0) for v in ["ALL", "AML"]}
size = {v: np.linalg.norm(emb[g == v] - c[v], axis=1).mean() for v in c}
gap = np.linalg.norm(c["ALL"] - c["AML"])
return f"gap/size {gap / np.mean(list(size.values())):.1f} ALL/AML size {size['ALL'] / size['AML']:.1f}"
print("PCA (PC1, PC2) ", describe(P[:, :2]))
for perp in [5, 15, 30]:
emb = TSNE(perplexity=perp, init="pca", random_state=0).fit_transform(P)
print(f"t-SNE perp {perp:2d} ", describe(emb))
for seed in [0, 1, 2]:
emb = TSNE(perplexity=15, init="random", random_state=seed).fit_transform(P)
print(f"random start {seed} ", describe(emb))Reading the output
init="pca", the default in recent scikit-learn, starts the map from the PCA layout; init="random" starts at random. In PCA the two groups are nearly the same size (1.1). On every t-SNE map ALL looks bigger, 1.5 to 2.0 times AML depending on perplexity: ALL has 47 patients and AML 25, and t-SNE partly turns more points into more area. Random starts move the numbers a little. No map here is wrong, and none measures distance.
UMAP needs the umap-learn package. This output came from umap-learn 0.5.9; other versions may give slightly different numbers.
import umap # in Colab, first run: !pip install -q umap-learn
for nn in [5, 15, 40]:
for md in [0.0, 0.5]:
emb = umap.UMAP(n_neighbors=nn, min_dist=md, random_state=0).fit_transform(P)
print(f"n_neighbors {nn:2d} min_dist {md} ", describe(emb))Reading the output
Six settings, the same 72 patients: the gap ranges from 1.3 to 3.4 times the group size, and ALL looks 1.3 to 4.3 times as large as AML. A paper saying "AML formed a tight, distant cluster on the UMAP" has described a setting, not a biological fact. UMAP returns at much larger scale in Module 4's Single-cell data: from counts to cell types, with the same cautions.
Go deeper: why t-SNE and UMAP distort sizes and gaps
t-SNE turns distances into probabilities of being neighbours, setting each point's neighbourhood width so that every point has about the same effective number of neighbours. Dense regions get narrow widths and sparse ones wide widths, which evens out density, so tight and loose groups end up looking alike in size. On the map it uses a heavy-tailed distribution that pushes moderately distant points far apart, opening up white space between groups. UMAP builds a nearest-neighbour graph, also adjusted for local density, and lays it out on the page. Neither tries to keep large distances, so how clusters sit relative to each other is only loosely meaningful.
The data are from Golub et al. (1999, Science), whose title, "Molecular classification of cancer: class discovery and class prediction by gene expression monitoring", names both halves of this module. Alongside a classifier, they used an unsupervised method (self-organising maps) and largely rediscovered the ALL/AML split from expression alone. Leek et al. (2010, Nature Reviews Genetics) reviewed how widespread batch effects are. t-SNE was introduced by van der Maaten and Hinton (2008, Journal of Machine Learning Research) and UMAP by McInnes, Healy and Melville (2018, arXiv preprint). Wattenberg, Viégas and Johnson (2016, Distill) showed interactively how t-SNE maps can mislead.
Good practice
- Decide preparation before looking. Choose the transform, gene filter and scaling on general grounds and report them. Trying settings until the picture looks good is a form of peeking.
- Start with PCA. Check the scree plot and colour the first components by every technical and biological variable. A component that follows processing date is a warning, not a finding.
- Fix random seeds for k-means, t-SNE and UMAP, then change them on purpose and check the conclusion survives.
- Check stability and compare with noise. Re-cluster bootstrap samples and shuffled data, and try neighbouring values of k and other linkages.
- Never treat a 2D picture as evidence. A t-SNE or UMAP map suggests where to look. Claims about groups need tests on the full data and, ideally, an independent set of samples.
Key point
Unsupervised methods always find something. Prepare the table deliberately, use PCA first to see the main sources of variation (batch effects included), cluster with stated settings and check the clusters are stable and stronger than in noise, and use t-SNE or UMAP as maps for looking, never as measurements.
Further reading · Module 7How to use t-SNE effectively: interactive examples of what perplexity changes. · scikit-learn: Clustering: the main methods compared. · UMAP documentation: parameters and how to choose them. · All reading for this course
Check your understanding
1. PCA on all 3,948 genes, each scaled to equal weight, gave a PC1 almost unrelated to the diagnosis. Keeping the 1,000 most variable genes brought it back. What does this show?
2. k-means is run on 72 rows of pure random noise and asked for three clusters. What happens?
3. On a UMAP plot, one cluster looks four times as large as another and far away from it. What can you conclude?