sergey isaev

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:

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.

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.

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.

Q = \frac{1}{2m}\sum_{i,j}\left[A_{ij} - \gamma\,\frac{k_i k_j}{2m}\right]\delta(c_i, c_j)

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:

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.

Different populations may need different resolutions, for two reasons.

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:

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.

  1. Sort all cells by the gene's expression.
  2. 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.
  3. 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.
  4. The area under the curve (AUC) summarizes it.

Reading the AUC:

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 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.

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:

  1. Bring your dataset (the query) and the annotated reference into a common space.
  2. 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.

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.

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.

Known markers on the UMAP.

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.

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

Glossary

Term Meaning
Cell type / cell statePopulations that rarely / readily interconvert
Community detectionClustering a graph into densely connected groups
SNN graphEdge weight = Jaccard overlap of two cells' neighbour sets
Connectivitiesscanpy's symmetric, weighted kNN graph from the UMAP algorithm
ModularityEdges within communities beyond those expected by chance
Resolution (\gamma)Modularity parameter; higher values give more clusters
Leiden / LouvainHeuristic modularity-maximization algorithms
Marker geneGene distinguishing a cluster from other cells
ROC curve / AUCTPR 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 dippingTesting hypotheses on the same data used to define the groups
PseudobulkCounts summed per sample and cell type, analysed like bulk RNA-seq
Label transferAssigning labels to query cells from an annotated reference
Compositional dataProportions that sum to one and so depend on each other

Further reading