LSMA

LONDON SCHOOL OF MULTIOMICS & AI

LSMA

LONDON SCHOOL OF MULTIOMICS & AI

Free course

Free course

0 of 31 lessons

Clustering, PCA and heatmaps

Clustering, PCA and heatmaps

Clustering, PCA and heatmaps

Before predicting anything, look. This lesson runs PCA, hierarchical clustering and k-means on 150 breast tumours, draws a heatmap, and asks whether the groups it finds are real.

This lesson follows Counts to results, the project that closed the RNA-seq module.

Patterns without labels

The first four modules gave you R itself, the statistics that say how far a result can be trusted, honest figures, and a complete RNA-seq analysis. All of that answered questions you asked in advance: does this gene change with treatment? This module turns to machine learning, methods that find patterns in many measurements at once or learn to predict an outcome from them, and to the survival analysis that clinical omics studies use alongside. It comes now because you can already load, clean, test and plot data, which is exactly what checking a model honestly needs.

Machine learning splits into two kinds. In unsupervised learning the computer sees only the measurements and looks for structure: which samples resemble each other, and which genes vary together. In supervised learning, the subject of Random forests and cross-validation, it also sees a label for each sample and learns to predict it. This lesson covers the three unsupervised tools you will meet in almost every omics paper: PCA, clustering and the heatmap.

The data come from The Cancer Genome Atlas (TCGA), as packaged in the Bioconductor package mixOmics. The set holds the expression of 200 genes in 150 breast tumours, already normalised and on a log scale, and each tumour's molecular subtype: Basal (basal-like), Her2 (HER2-enriched) or LumA (luminal A). The subtypes were defined from gene expression in earlier studies, so they make a good test: useful unsupervised methods should rediscover some of that structure. The genes were heavily filtered for teaching, so treat the results as an illustration.

R · run once
BiocManager::install("mixOmics")
install.packages(c("randomForest", "pheatmap"))
R
library(mixOmics)
library(ggplot2)
library(pheatmap)
library(cluster)

data(breast.TCGA)
x       <- breast.TCGA$data.train$mrna
subtype <- breast.TCGA$data.train$subtype

dim(x)
table(subtype)
round(x[1:3, 1:4], 2)
[1] 150 200 subtype Basal Her2 LumA 45 30 75 RTN2 NDRG2 CCDC113 FAM63A A0FJ 4.36 7.53 3.96 4.46 A13E 1.98 7.46 5.43 5.44 A0G0 1.73 8.08 2.23 5.54

What this does

  • cluster ships with R, so it needs no installing; it provides the silhouette used below.
  • breast.TCGA$data.train$mrna is a matrix with one row per tumour and one column per gene. Note the orientation: it is the transpose of the airway count matrix, where genes were rows. Most R functions for machine learning expect samples in rows, so with a DESeq2 object you would use t(assay(vsd)).
  • The set also holds a separate test set of 70 tumours, data.test. This lesson leaves it alone; Random forests and cross-validation explains why it must stay untouched.

PCA: the main directions of variation

You met PCA in RNA-seq counts and exploration, where plotPCA() did the work. Here you run it yourself with prcomp(), which shows what happens inside. PCA finds new axes, the principal components, each a weighted combination of all 200 genes. PC1 is the direction along which the tumours spread out most; PC2 is the direction of greatest remaining spread at right angles to PC1, and so on. Each tumour's position on these axes is its score.

R
pca <- prcomp(x, center = TRUE, scale. = TRUE)
summary(pca)$importance[, 1:4]

pve <- 100 * pca$sdev^2 / sum(pca$sdev^2)
scores <- data.frame(pca$x[, 1:2], subtype = subtype)

ggplot(scores, aes(PC1, PC2, colour = subtype)) +
  geom_point(size = 2.5, alpha = 0.8) +
  scale_colour_manual(values = c(Basal = "#D55E00", Her2 = "#009E73", LumA = "#0072B2")) +
  labs(x = paste0("PC1: ", round(pve[1]), "% variance"),
       y = paste0("PC2: ", round(pve[2]), "% variance"), colour = "Subtype") +
  theme_minimal(base_size = 13)
PC1 PC2 PC3 PC4 Standard deviation 6.150611 5.121658 3.32147 3.288056 Proportion of Variance 0.189150 0.131160 0.05516 0.054060 Cumulative Proportion 0.189150 0.320310 0.37547 0.429520

What this does

  • center = TRUE subtracts each gene's mean, so PCA describes differences between tumours, not overall expression levels.
  • scale. = TRUE also divides each gene by its standard deviation, so every gene counts equally. Without it, the genes with the largest spread dominate.
  • pca$sdev holds the standard deviation along each component; squared, it is the variance. Dividing each by the total gives the proportion of variance explained, the percentages on the axis labels.
  • pca$x holds the scores, one row per tumour, which go straight into ggplot2.

PC1 explains 19% of the variance and PC2 13%, so the plot shows about a third of the variation among 200 genes. On the plot, basal tumours sit to the right of PC1 (median score 7.9), luminal A tumours to the left (median −5.2), and HER2-enriched tumours in between (median 0.5), overlapping both. PCA was never told the subtypes; the colours were added afterwards.

Worked example · variance explained from sdev

scaled data: each gene has variance 1, so total variance = 200
PC1: sdev 6.151 → variance 6.151² = 37.8
37.8 ÷ 200 = 0.189, the 19% on the x-axis

Step by step. Scaling gives every gene a variance of exactly 1, and PCA only rotates the data, so the variances of all components add up to the same total: 200, one per gene. sum(pca$sdev^2) confirms it. PC1 carries 37.8 of those 200 units. One gene on its own carries 1 unit, so PC1 holds as much variation as about 38 average genes.

What the answer means. A component is worth looking at when it explains clearly more than one gene's worth. PC3 and PC4 each explain about 5.5%, about 11 genes' worth, and the curve flattens from there; most of the remaining variation is spread thinly over many directions.

Loadings: which genes build each component

Each component's weights, one per gene, are its loadings, stored in pca$rotation. A large positive loading means tumours high in that gene score high on the component; a large negative one, the opposite.

R
load1 <- sort(pca$rotation[, "PC1"])
round(head(load1, 5), 3)
round(tail(load1, 5), 3)
C4orf34 ZNF552 KDM4B FUT8 LRIG1 -0.131 -0.129 -0.125 -0.124 -0.122 ASPM LMO4 E2F1 SLC43A3 CCNA2 0.107 0.107 0.110 0.113 0.122

The genes with the largest positive loadings include ASPM, E2F1 and CCNA2, which are involved in cell division. That fits the right-hand side of the plot, where the basal tumours sit: basal-like tumours tend to proliferate quickly. No loading is far larger than the rest, so PC1 is a broad pattern shared by many genes, not one gene's signal.

Does scaling matter here? Without it (scale. = FALSE), PC1 explains 21.9% instead of 18.9%, its largest loading belongs to STC2, the gene with the widest spread (standard deviation 2.54), and the PC1 scores correlate 0.99 with the scaled version. The genes in this set all sit on the same log scale with similar spreads (0.73 to 2.54), so scaling changes little. With measurements on different scales, such as genes alongside proteins or clinical variables, unscaled PCA would simply follow whichever variable has the biggest numbers.

Distances and hierarchical clustering

Clustering groups samples that are close together. "Close" needs a definition, a distance. The usual one is Euclidean distance: the straight-line distance between two tumours if each gene is an axis, computed as the square root of the sum of squared differences across genes. dist() computes it for every pair of rows.

R
xs <- scale(x)
d  <- dist(xs)
round(as.matrix(d)[1:3, 1:3], 1)

hc <- hclust(d, method = "ward.D2")
cl <- cutree(hc, k = 3)
table(cluster = cl, subtype)

plot(hc, labels = FALSE, hang = -1, main = "", xlab = "", sub = "")
rect.hclust(hc, k = 3, border = c("#E69F00", "#56B4E9", "#009E73"))
A0FJ A13E A0G0 A0FJ 0.0 18.9 17.6 A13E 18.9 0.0 18.0 A0G0 17.6 18.0 0.0 subtype cluster Basal Her2 LumA 1 44 2 0 2 1 28 55 3 0 0 20

What this does

  • scale(x) centres and scales each gene, for the same reason as in PCA: otherwise the widest-spread genes decide every distance.
  • dist(xs) returns the 150 × 149 ÷ 2 = 11,175 pairwise distances. Viewed as a matrix it is symmetric with zeros on the diagonal.
  • hclust() starts with every tumour in its own cluster and repeatedly merges the two closest clusters until one remains. The result is a tree, the dendrogram; the height of each join is the distance at which the two branches merged.
  • cutree(hc, k = 3) cuts the tree into three groups. table() compares them with the known subtypes.

The linkage, set by method, decides how the distance between two clusters is measured. Complete linkage uses the two farthest members, average the mean of all pairs, single the two nearest, and Ward's method ("ward.D2") merges whichever pair increases the spread within clusters least. The choice matters a great deal. With Ward's method, cluster 1 holds 44 of the 45 basal tumours, and cluster 3 is purely luminal A, though the other luminal A and nearly all HER2-enriched tumours share cluster 2. With complete, average or single linkage on the same distances, cutting at three groups puts at least 139 of the 150 tumours into one big cluster and leaves two tiny ones: those methods peel off a few unusual tumours instead of dividing the main body.

Correlation distance, as.dist(1 - cor(t(x))), is a common alternative: two tumours are close when their genes rise and fall together. Here, with average linkage, it gave the same lopsided split. No distance or linkage is correct in general; state yours, and check that the conclusion survives another reasonable choice.

k-means and choosing k

k-means takes a different route. You choose the number of clusters, k; it places k centres at random, assigns each tumour to its nearest centre, moves each centre to the mean of its tumours, and repeats until nothing changes. The random start means two runs can end in different places, so set a seed and use several starts.

R
set.seed(42)
km <- kmeans(xs, centers = 3, nstart = 25)
km$size
table(cluster = km$cluster, subtype)

ks <- 2:8
choose_k <- sapply(ks, function(k) {
  set.seed(42)
  fit <- kmeans(xs, centers = k, nstart = 25)
  sil <- silhouette(fit$cluster, d)
  c(k = k, within_ss = round(fit$tot.withinss), silhouette = round(mean(sil[, "sil_width"]), 3))
})
t(choose_k)
[1] 36 50 64 subtype cluster Basal Her2 LumA 1 0 5 31 2 45 5 0 3 0 20 44 k within_ss silhouette [1,] 2 25184 0.163 [2,] 3 23232 0.105 [3,] 4 21993 0.091 [4,] 5 20949 0.077 [5,] 6 20334 0.077 [6,] 7 19821 0.073 [7,] 8 19281 0.077

What this does

  • set.seed(42) fixes the random starting centres, as in Multiple testing and power, so you get the same clusters each time you run the script.
  • nstart = 25 runs k-means from 25 random starts and keeps the best. With a single start, ten different seeds gave a within-cluster sum of squares of 23,232 in eight runs and worse values (23,678 and 23,729) in two: the method can get stuck.
  • tot.withinss, the total squared distance from each tumour to its cluster centre, always falls as k rises, so it cannot pick k on its own.
  • silhouette(), from the cluster package, scores each tumour from −1 to 1: how much closer it is to its own cluster than to the nearest other cluster. The mean silhouette width summarises how well separated the clusters are.

k-means with three clusters isolates the basal tumours again (cluster 2 holds all 45, plus 5 HER2-enriched), but splits the luminal A tumours across two clusters that also share the HER2-enriched ones. Cluster numbers are arbitrary labels.

The silhouette tells an honest story. It is highest at k = 2, and every value is low: as a rough guide, averages below about 0.25 mean no strong cluster structure. At k = 3, 27 tumours have negative widths, meaning they sit closer to another cluster than to their own. Put plainly, these tumours do not fall into three tidy clouds. There is one distinct group, the basal tumours, and a continuum through HER2-enriched to luminal A, which is what the PCA plot already showed. Clustering always returns k groups when asked; whether the groups are real is a separate question.

Common mistakes

  • Clustering unscaled data with variables on different scales, so a few variables decide everything.
  • Choosing k, the linkage or the gene list because the clusters then match the groups you hoped for. Decide the method first, as with any test.
  • Testing for differences between clusters found in the same data. The clusters were built to differ, so the p-values are meaningless.
  • Forgetting set.seed(), so the k-means clusters change every time the script runs.

Heatmaps of the most variable genes

A heatmap shows the data themselves: one row per gene, one column per sample, colour for expression, with rows and columns ordered by hierarchical clustering. You drew one in Omics figures. With many genes, a common choice is to show the most variable ones, since genes that barely change between tumours add colour but no information.

R
v   <- apply(x, 2, var)
top <- names(sort(v, decreasing = TRUE))[1:40]
z   <- t(scale(x[, top]))
range(z)
z[z >  3] <-  3
z[z < -3] <- -3

ann <- data.frame(subtype = subtype, row.names = rownames(x))
pheatmap(z,
         annotation_col = ann,
         annotation_colors = list(subtype = c(Basal = "#D55E00", Her2 = "#009E73", LumA = "#0072B2")),
         color = colorRampPalette(c("#2166AC", "white", "#B2182B"))(100),
         breaks = seq(-3, 3, length.out = 101),
         clustering_method = "ward.D2",
         show_colnames = FALSE, fontsize_row = 7)
[1] -3.803434 3.709159

What this does

  • apply(x, 2, var) computes each gene's variance across tumours; the 40 largest are kept.
  • scale() turns each gene into z-scores: how many standard deviations each tumour sits above or below that gene's mean. t() then puts genes in rows, as heatmaps expect.
  • The z-scores run from −3.8 to 3.7. The two lines that follow cap them at ±3, which affects 19 of the 6,000 values. Capping keeps a few extreme cells from stretching the colour scale; say in the legend that you did it.
  • The colours run blue–white–red with breaks symmetric around zero, so white means "average for this gene", as in Colour that works for everyone.

In the heatmap, the basal tumours form a block at one side, with the cell-division genes ASPM and CCNA2 mostly red and genes such as STC2, ZNF552 and PREX1 mostly blue; luminal A tumours show roughly the reverse. HER2-enriched tumours are scattered among the luminal A columns, matching everything above.

One caution about selecting genes. Choosing genes by their variance alone is unsupervised: it never looks at the subtypes, so it is safe. Choosing them because they differ between subtypes, and then showing that the heatmap separates the subtypes, is circular; the separation was built in. That trap returns as data leakage in Random forests and cross-validation.

Go deeper: how stable are the clusters?

A clustering can look convincing and still change with a slightly different sample. One check is to resample: draw tumours with replacement, as in Resampling: bootstrap and permutation, recluster each time, and record how often each pair of tumours lands in the same cluster. Pairs that stay together in most resamples belong to stable clusters; pairs that split half the time do not.

The fpc package's clusterboot() does this for many clustering methods, and the ConsensusClusterPlus package from Bioconductor does it for the consensus clustering common in cancer subtyping papers. When a paper reports new subtypes, look for such a check and for an independent cohort.

The intrinsic breast cancer subtypes were first described from gene expression clustering by Perou et al. 2000, "Molecular portraits of human breast tumours" (Nature). The TCGA breast cancer study is The Cancer Genome Atlas Network 2012, "Comprehensive molecular portraits of human breast tumours" (Nature), and the packaged subset comes with the DIABLO paper, Singh et al. 2019 (Bioinformatics). Jolliffe & Cadima 2016 (Philosophical Transactions of the Royal Society A) review PCA, and Rousseeuw 1987 (Journal of Computational and Applied Mathematics) introduced the silhouette.

Key point

Unsupervised methods always find something. PCA, clustering and heatmaps are for looking: they show which samples resemble each other and which genes drive it. Whether a pattern is real, stable and meaningful needs further checks, and every choice (scaling, distance, linkage, k, gene selection) belongs in your methods.

Further reading · Module 5Jolliffe & Cadima 2016: what PCA does and does not tell you. · All reading for this course

Check your understanding

1. Why is prcomp() run with scale. = TRUE when variables are on different scales?

2. k-means with k = 3 gives an average silhouette width of 0.105, and 27 tumours have negative widths. What does this suggest?

3. You pick the 40 genes that differ most between subtypes, then show that a heatmap of them separates the subtypes. What is wrong?

Ask LSMA