Lecture 8. Clustering and cell type annotation
Lecture 7 ended with a batch-corrected embedding and a kNN graph built on it. This lecture covers the last step, the one all previous steps exist for: turning that graph into biological answers. It covers clustering, deciding which cell type each cluster is, finding marker genes and the pitfalls of testing them, and transferring labels from an annotated reference. The practical part annotates the PBMC dataset from Lectures 6–7.
A useful way to see the whole pipeline: the data "say" something, and processing is how we learn their language. QC, normalization, PCA, batch correction and the graph are only means; interpretation is the point.
1. Annotation is usually a step, not the goal
Sometimes characterizing the cell types is the scientific goal itself, for example in a newly described organism, where you want to know which cell types it has and what they do. In the first years of single-cell transcriptomics (roughly 2015–2020) this was true for many tissues. Single-cell RNA-seq was a new kind of microscope, and simply looking at a tissue with it, describing its cell types, was publishable. That needed money and analysis experience more than a hypothesis.
Today, annotation usually comes before the real question. Typical questions are whether the proportion of a cell type changes between conditions, or how a cell type's state changes. For example, a study of several mouse models of autism, each carrying a mutation in a different gene, can ask whether these models share changes in cell-type proportions or states in the developing brain. The cell types of the developing mouse brain are already described; annotation is just the prerequisite for the comparison.
2. Cell types, cell states, and clusters
There is no agreed definition of a cell type. A working intuition:
- Cell states interconvert under normal conditions: cells fluctuate or move between them.
- Cell types rarely or never convert into each other in the organism. With the right cocktail of signals almost any cell can be pushed into almost anything, but such conditions usually don't occur in vivo.
The distinction is fuzzy, and below "state" is used for both.
Computationally we work with clusters in transcriptional space: groups of cells with similar expression profiles that differ from each other mostly by noise. In an idealized statistical model, each state would have one "true" expression profile, and its cells would be that profile plus Poisson or negative binomial sampling noise. Each state would then form a compact blob, and clustering would be straightforward.
In reality, cells of one state differ more than sampling noise allows. Even a clonal, homogeneous cell line shows biological fluctuations in metabolism, cell cycle and so on. If you look for heterogeneity, you will find it almost anywhere. So clustering is partly subjective: where to draw boundaries depends on biological expectations about the tissue and on the question.
3. Why not k-means: clustering on the graph
k-means, familiar from machine-learning courses, assigns each point to the nearest of K centroids, choosing centroids to minimize the total squared distance. It has two problems here.
- K must be chosen in advance. Heuristics exist, but none works reliably.
- It assumes compact, roughly spherical clusters. Imagine two elongated clouds lying side by side, separated by a gap. Biologically we want to split them along the gap: within each cloud there is a continuous spectrum of states, so its cells plausibly convert into each other, while crossing the gap is much less likely. k-means, which only looks at distances to centroids, may instead cut both clouds across their length, because points at the two ends of one cloud are farther apart than points on either side of the gap.
The intuition we want — continuity, neighbours, gradual transitions — is the manifold intuition from Lecture 6. So single-cell data are usually clustered with community detection on the kNN graph, which approximates the manifold. Because UMAP and clustering use the same graph, they usually agree: a clear cluster is a clear island on the UMAP. Still, cluster on the graph, not on UMAP coordinates.
4. Making the graph symmetric
A kNN graph is directed. Take one isolated point and a tight group of three points, with k = 2. The isolated point's two nearest neighbours are in the group, but for each point in the group, its two nearest neighbours are the other two group members. So edges go from the isolated point to the group, but none come back. Community detection methods need an undirected (symmetric) graph, so the kNN graph has to be symmetrized.
- Ignore direction. The simplest option: keep an edge if it exists in either direction.
- Shared nearest neighbours (SNN). Weight the edge between two cells by the overlap of their neighbour sets, measured by the Jaccard index |N_i \cap N_j| \,/\, |N_i \cup N_j|, where N_i is the neighbour set of cell i: size of the intersection divided by size of the union. Identical neighbour sets give weight 1, disjoint sets 0. Seurat uses this graph. A quirk: two points on opposite sides of a small group can have identical neighbour sets (the group) and get a strong edge, although they are not each other's neighbours.
- UMAP connectivities. scanpy's
sc.pp.neighborscomputes the graph used by UMAP and stores it asadata.obsp["connectivities"]. Each cell's distances to its neighbours are converted to edge weights with a per-cell scale (so that dense and sparse regions are treated alike, as in Lecture 6), and the two directions are combined into one symmetric weight. This is the default graph for clustering in scanpy; "connectivities" in scanpy and in papers using it almost always means this graph.
Graphs are stored as sparse cells × cells matrices, with nonzero entries for edges.
5. Modularity, resolution and the Leiden algorithm
A clustering is a labelling of the vertices. To choose between labellings we need an objective function that scores them. (k-means, for example, minimizes total squared distance to centroids.) Community detection uses modularity: a good partition has many edges within communities and few between them, compared with what a random graph with the same vertex degrees would give.
- A is the adjacency matrix, k_i the degree of vertex i, m the total number of edges, and \delta(c_i, c_j) = 1 if i and j are in the same community (0 otherwise).
- The term k_i k_j / (2m) is the expected number of edges between i and j in a random graph with the same degrees. So modularity rewards edges inside communities beyond what chance would give.
Resolution (\gamma). The same graph can be partitioned at different levels. Two separate components are clearly two communities, but a component made of two dense parts connected by a few edges can be one community or two. The resolution parameter \gamma sets how strongly edges between communities are penalized. Higher resolution gives more, smaller clusters; lower resolution gives fewer, larger ones.
Finding the partition. Scoring a given partition is easy, but finding the partition with maximum modularity is NP-hard. Heuristic algorithms are used instead:
- Louvain, the older one, can produce badly connected or even internally disconnected communities.
- Leiden fixes this and is the current default:
sc.tl.leiden(adata, resolution=1.0).
6. Choosing the resolution
There is no universal rule for the number of clusters. Formal criteria exist (elbow plots, silhouette scores, cluster stability), but in practice they rarely decide anything. Even after batch correction, some of the heterogeneity in the embedding interests you and some does not. Reviewers often ask "how did you choose the number of clusters?"; the honest answer is that you look for clusters that are stable and correspond to something real in the tissue.
- A clearly separated, stable cluster should be its own cluster.
- Whether to split a population into subclusters depends on knowledge and the question. CD14 and CD16 monocytes form two neighbouring groups, and they are kept separate because they are known populations with clear markers (CD14, FCGR3A). An unfamiliar subpopulation is worth separating if it may matter for your question (e.g., response to therapy). If not, merging it with its neighbour costs little.
Different populations may need different resolutions, for two reasons.
- Biological interest. If you study immune cells, heterogeneity among epithelial cells may not matter. Either cluster everything at high resolution and merge the epithelial clusters into one label, or cluster at low resolution and then subcluster only the cells of interest.
- Sampling. As with UMAP, the graph reflects how many cells there are, not only how different they are. A rare population has few cells, so each of its cells must take some of its k neighbours from other, similar populations. Rare, distinct cells therefore get absorbed into larger clusters and need a higher resolution to separate. Abundant populations, densely sampled, split easily and may need a lower one.
Annotation is partly a craft that comes with experience; the course project, annotating a dataset yourself, is meant to build it.
7. Annotating clusters with known markers
The simplest approach is supervised by your knowledge: color the cells by the expression of genes known to mark the cell types you expect in the tissue. For PBMCs:
- T cells: CD3E, CD3D (subunits of CD3). Within them, CD4 and CD8A / CD8B separate CD4 and CD8 T cells.
- NK cells: NKG7, GNLY, no CD3. NKG7 is also high in cytotoxic CD8 T cells.
- Monocytes: CD14 (classical), FCGR3A (encodes CD16; non-classical monocytes, and also CD16⁺ NK cells). LYZ is a strong monocyte marker.
- B cells: MS4A1 (encodes CD20).
- Dendritic cells: separate markers for conventional (cDC1, cDC2) and plasmacytoid DCs.
Annotate as deeply as your question requires. If your study is about monocytes, "T cells" is a perfectly good label for the T-cell clusters, however a reviewer might feel about it.
Also check for contaminants and artifacts: haemoglobin genes (e.g., HBB) for red blood cells, and the doublet score for clusters made of doublets.
Dot plots summarize marker expression across clusters: color shows mean expression in the cluster, dot size the fraction of cells expressing the gene.
8. Finding marker genes: AUC and differential expression
Sooner or later some cluster won't match any marker you know. Then you switch from imposing hypotheses to letting the data suggest them: find the cluster's marker genes, i.e., genes that distinguish it from other cells. There are two framings, which turn out to be nearly the same.
Markers as classifiers: ROC and AUC
Ask how well a single gene, used as a classifier, separates the cluster (label 1) from all other cells (label 0). Comparisons are always between two groups, most often one cluster vs the rest.
- Sort all cells by the gene's expression.
- Put a threshold somewhere and call every cell above it "in the cluster". Count:
- the true positive rate (TPR), the fraction of the cluster's cells above the threshold;
- the false positive rate (FPR), the fraction of other cells above it.
- Move the threshold from the top to the bottom and plot TPR against FPR. This is the ROC curve. It starts at (0, 0), where nothing is called positive, and ends at (1, 1), where everything is.
- The area under the curve (AUC) summarizes it.
Reading the AUC:
- AUC ≈ 1: a perfect positive marker. The cluster's cells all come after the other cells in the sorted order, and the curve hugs the top-left corner. LYZ for CD14 monocytes vs everything else gives about 0.99.
- AUC ≈ 0.5: no information. A housekeeping ribosomal gene behaves like this.
- AUC < 0.5: a negative marker: the gene is expressed everywhere except the cluster (MALAT1 in monocytes, for example). The AUC lies between 0 and 1, never below 0.
The AUC is also the probability that a randomly chosen cell from the cluster has higher expression than a randomly chosen other cell.
Markers as differentially expressed genes
The second framing tests each gene for differential expression between the cluster and the rest. Count models such as the negative binomial can be used, as in bulk, but simple tests are more common:
- the Wilcoxon rank-sum test, also called the Mann–Whitney U test (the unpaired test; the Wilcoxon signed-rank test is the paired one);
- the t-test, scanpy's default.
The rank-sum test is a good default.
The two framings are almost the same. The Mann–Whitney U statistic divided by the product of the group sizes is the AUC: \mathrm{AUC} = U / (n_1 n_2). Ranking genes by the Wilcoxon score therefore ranks them essentially as the AUC would. The AUC is easy to compute in Python (e.g., sklearn.metrics.roc_auc_score) but isn't reported by scanpy's marker function. The practical choice is simply sc.tl.rank_genes_groups(adata, "leiden", method="wilcoxon").
One-vs-rest has a limitation. The most useful fact about a T-cell subcluster is that it expresses CD3E. But CD3E is also expressed by half the dataset, so it is not a top marker for that subcluster vs the rest. A hierarchical strategy works better: find markers for a few large clusters first (CD3E comes out for T cells), then find markers between subclusters within each one. Some tools do this systematically. The web application of Pagoda2, for instance, clusters hierarchically and shows the differential expression between the two branches at each node.
9. Double dipping: why marker p-values can't be taken literally
AUC gives no p-value, so how good is a marker with AUC 0.8, or 0.6? It is tempting to use differential expression instead, because it gives p-values. These p-values are not valid.
The problem. Take a single blob of pure noise in two genes and split it with k-means, K = 2. The two halves will differ significantly in one gene or both, because the split was made along those genes. The difference is statistically real, but it means nothing biologically. Clustering used the expression data to define the groups, and the test then uses the same data to compare them. This is double dipping (circular analysis): whatever the data, it produces "significant" differences.
The test is valid when the grouping does not depend on the expression data, for example cells from patient 1 vs patient 2.
What to do in practice.
- Use marker p-values (like AUC values) only to rank genes, not as evidence.
- "These are CD8 T cells because CD8A has p = 10^{-50} in our differential expression" is not a valid argument. The argument is the known biology of the markers.
- Methods exist that split the counts into independent parts, one for clustering and one for testing (count splitting / data thinning), when a valid test is genuinely needed.
10. Comparing conditions: pseudobulk
After annotation, a common question is how a cell type differs between conditions: for example, CD8 T cells of healthy vs treated patients. Here the groups are defined by condition, not by expression, so double dipping is not the issue. A different one is.
A frequent mistake is to take all CD8 T cells from healthy and from treated patients and test them against each other as if every cell were an independent replicate. Most of the variation is between patients, not between cells of one patient. The biological replicates are the patients, and treating thousands of cells as replicates gives absurdly small p-values and many false discoveries (pseudoreplication).
Pseudobulk: for each patient and cell type, sum the raw counts over that patient's cells of that type. This gives one bulk-like profile per patient per cell type. Then test for differential expression between conditions across patients with bulk methods (DESeq2, edgeR, limma), adding batch to the model where needed (Lecture 7).
11. Automatic annotation: label transfer
You are rarely the first to profile a tissue. Often someone has already annotated a similar dataset carefully. The simplest way to use it is manual: read their paper, take their markers, and check them in your data. This is often the most reliable approach.
It can also be done automatically with label transfer:
- Bring your dataset (the query) and the annotated reference into a common space.
- For each query cell, look at its nearest reference cells and assign the most common label among them (a kNN classifier).
The integrated dataset itself is not kept; only the labels are.
How it differs from batch correction. In the simplest form, label transfer is batch correction followed by a classifier. In practice it is a separate setting, for two reasons.
- Speed. References are large, and re-integrating them with every new query is slow.
- A different assumption. The reference is assumed to contain all cell types present in the query. So the reference structure is kept fixed, and the query is fitted onto it, rather than both datasets being re-integrated on equal terms.
In PCA terms: with batch correction, both datasets get new components and new coordinates. With label transfer, the query cells are simply projected onto the reference's existing components.
Symphony (Kang et al., 2021) is a reference-mapping method built on Harmony. The reference has already been integrated with Harmony, and its cluster centroids are fixed. Query cells are assigned to these clusters and moved toward the fixed centroids, without iterating over the reference again, so mapping is fast. symphonypy is its Python implementation. Query cells can also be placed on the reference's UMAP, using the UMAP model fitted on the reference.
Don't trust transferred labels blindly.
- The result is only as good as the reference and its similarity to your data. A close, high-quality reference can be trusted more; a distant one can produce nonsense.
- A cell type absent from the reference cannot be found: its cells get the label of the most similar reference type. The same logic applies as in overcorrection.
- A practical workflow: plot the transferred labels next to your own clusters. Annotate each cluster by the label that dominates it, and if one of your clusters contains several reference labels (e.g., all monocytes merged), subcluster it.
12. Practical: annotating the PBMC dataset
The practical continues with the PBMC dataset from three donors (Lectures 6–7). The first steps are the same as before: QC, Scrublet run per batch (doublets form within a batch, not between batches), normalization, log transform, HVGs, scaling, PCA, Harmony, kNN graph, UMAP.
Clustering.
- Leiden with resolution 1 gives 18 clusters on this dataset; resolution 0.1 gives a handful; 1.5 gives 23.
- Check how each cluster is composed by batch. After Harmony, no cluster should be dominated by one donor.
Known markers on the UMAP.
- MS4A1: B cells, two clusters.
- CD3E: T cells.
- CD4: CD4 T cells, but also monocytes, which express CD4 at a low level.
- CD8A: CD8 T cells.
- A population with no or very little CD3E, CD4 or CD8A is NK cells; NKG7 lights them up, together with cytotoxic CD8 T cells.
- CD14: classical monocytes. FCGR3A: CD16 monocytes and CD16⁺ NK cells; the remaining NK cells are the CD56-bright subset.
- HBB: no red blood cell contamination here.
- Doublet score: no cluster is driven by doublets.
Markers for an unknown cluster. sc.tl.rank_genes_groups (one vs rest; use method="wilcoxon" rather than the default t-test) gives the top genes for cluster 17: TCF4, IRF8, JCHAIN. JCHAIN suggests plasma cells at first, but TCF4 and IRF8 point to plasmacytoid dendritic cells (pDCs), which express JCHAIN as well. Label transfer confirms pDCs. The same markers show that the two B-cell clusters are naive/memory B cells.
Label transfer with symphonypy.
- Load an annotated PBMC reference that comes with the package.
- Map the query onto it; the mapping uses log-normalized expression, stored in
adata.raw. - Check mapping quality metrics, such as how far query cells are from the reference.
- Transfer labels. The reference adds populations the first pass missed, such as haematopoietic stem cells and megakaryocytes, and otherwise agrees with the manual annotation.
- Optionally place the query on the reference UMAP.
The final step: assign a cell type to each cluster, combining known markers, data-driven markers and transferred labels, and plot the annotated UMAP. This is the core of the course project.
import scanpy as sc
# after QC, Scrublet (per batch), normalize_total, log1p, HVGs, scale, PCA
sc.external.pp.harmony_integrate(adata, key="donor") # -> obsm["X_pca_harmony"]
sc.pp.neighbors(adata, use_rep="X_pca_harmony")
sc.tl.umap(adata, min_dist=0.3)
sc.tl.leiden(adata, resolution=1.0)
sc.pl.umap(adata, color=["leiden", "donor", "doublet_score"])
sc.pl.umap(adata, color=["MS4A1", "CD3E", "CD4", "CD8A", "NKG7",
"CD14", "FCGR3A", "HBB"])
sc.tl.rank_genes_groups(adata, "leiden", method="wilcoxon")
sc.pl.rank_genes_groups_dotplot(adata, n_genes=3)
sc.get.rank_genes_groups_df(adata, group="17").head(10)
After annotation, the next tools depend on the question. A common one is comparing cell-type proportions between conditions. Proportions are compositional data: they sum to one, so if one cell type expands, the others shrink even if their absolute numbers don't change. Such data need dedicated methods from compositional data analysis.
13. Key points
- Annotation is usually a prerequisite for the real question (composition, states, comparisons), not the goal itself.
- Cell types vs states: states interconvert, types rarely do. Clusters are groups of cells differing mostly by noise, but extra biological variation is everywhere, so clustering is partly subjective.
- Single-cell data are clustered by community detection on the (symmetrized) kNN graph, which follows the manifold. k-means assumes compact blobs and a known K.
- Leiden maximizes modularity. Higher resolution gives more clusters. There is no formula for the right resolution, and rare populations may need higher resolution or subclustering.
- Annotate with known markers first, then use data-driven markers (AUC, Wilcoxon) for unknown clusters, ideally hierarchically.
- Marker p-values suffer from double dipping: use them for ranking only, never as evidence.
- When comparing conditions, patients are the replicates: aggregate counts into pseudobulk.
- Label transfer maps a query onto a fixed reference. It is fast and useful, but limited by the reference; check it against your own clusters.
Glossary
| Term | Meaning |
|---|---|
| Cell type / cell state | Populations that rarely / readily interconvert |
| Community detection | Clustering a graph into densely connected groups |
| SNN graph | Edge weight = Jaccard overlap of two cells' neighbour sets |
| Connectivities | scanpy's symmetric, weighted kNN graph from the UMAP algorithm |
| Modularity | Edges within communities beyond those expected by chance |
| Resolution (\gamma) | Modularity parameter; higher values give more clusters |
| Leiden / Louvain | Heuristic modularity-maximization algorithms |
| Marker gene | Gene distinguishing a cluster from other cells |
| ROC curve / AUC | TPR vs FPR across thresholds / area under it |
| Wilcoxon rank-sum (Mann–Whitney U) | Non-parametric test of whether one group tends to have higher values |
| Double dipping | Testing hypotheses on the same data used to define the groups |
| Pseudobulk | Counts summed per sample and cell type, analysed like bulk RNA-seq |
| Label transfer | Assigning labels to query cells from an annotated reference |
| Compositional data | Proportions that sum to one and so depend on each other |
Further reading
- Newman (2006). Modularity and community structure in networks. PNAS 103:8577–8582.
- Traag, Waltman & van Eck (2019). From Louvain to Leiden: guaranteeing well-connected communities. Sci. Rep. 9:5233.
- Squair et al. (2021). Confronting false discoveries in single-cell differential expression. Nat. Commun. 12:5692.
- Zimmerman, Espeland & Langefeld (2021). A practical solution to pseudoreplication bias in single-cell studies. Nat. Commun. 12:738.
- Neufeld et al. (2024). Inference after latent variable estimation for single-cell RNA sequencing data. Biostatistics 25:270–287.
- Kang et al. (2021). Efficient and precise single-cell reference atlas mapping with Symphony. Nat. Commun. 12:5890.
- Heumos et al. (2023). Best practices for single-cell analysis across modalities. Nat. Rev. Genet. 24:550–572.