Exercise: dimensionality reduction & clustering

Goal

By the end of this exercise you should be able to:

  • explain why we reduce with PCA before building a neighbour graph or a UMAP,
  • build a small k-nearest-neighbour (kNN) graph by hand from cell coordinates and Euclidean distances,
  • read off the communities (clusters) of a small graph by eye,
  • state precisely what a UMAP may and may not be used to conclude,
  • predict how the resolution parameter changes the number of clusters,
  • run and read the standard Seurat pipeline (RunPCA → FindNeighbors → FindClusters → RunUMAP) as a recipe.

This is an applied concept day. The pen-and-paper part is the kNN/graph reasoning; the R part is reading the standard pipeline and reproducing the neighbour step in base R. No cluster count today is “the right answer” — judging that is part of the skill.

Background

A cell is a point in gene-expression space (one axis per gene). Cells of the same type express similar genes, so they sit close together; the whole task is to find those close-together groups without being told the labels (unsupervised).

The standard pipeline, from the Dimensionality reduction & clustering lecture:

\[ \underbrace{X}_{\text{cells × genes}} \xrightarrow{\text{PCA}} \underbrace{Z}_{\text{cells × }\sim 30} \xrightarrow{\text{neighbours}} \underbrace{G_U,\ G_C}_{\text{neighbour graphs}} \xrightarrow{\begin{array}{c}\text{UMAP}\\\text{clustering}\end{array}} \text{2D map + labels} \]

  1. PCA compresses ~2000 genes to ~30 principal components — this denoises and speeds everything up. Distances are more meaningful in ~30 clean dimensions than in 2000 noisy ones. (Same method as Principal component analysis and PCA in R.)
  2. kNN graph: for each cell, connect it to its \(k\) nearest neighbours (typical \(k \approx 15\)) by Euclidean distance in PC space, \[ \text{dist}(\mathbf{x}_i, \mathbf{x}_j) = \lVert \mathbf{x}_i - \mathbf{x}_j \rVert = \sqrt{\sum_{p} (x_{ip} - x_{jp})^2}. \]
  3. UMAP builds a weighted neighbour graph from the PC representation and lays it out in 2D. It is non-linear and aims to preserve local neighbourhoods — its axes and inter-cluster distances are not quantitative.
  4. Clustering (Louvain / Leiden) finds densely connected communities in a neighbour graph; the resolution parameter controls the granularity. In the Seurat recipe below, clustering uses a shared-nearest-neighbour (SNN) graph from FindNeighbors, while RunUMAP(dims = ...) builds its own neighbour graph. They use the same PC representation, but need not use identical graphs. Cluster labels are not derived from the 2D layout.

Key discipline: local structure is trustworthy, global geometry is decorative.

By hand

Use this toy dataset throughout. Six cells have already been reduced to their top 2 principal components \((\text{PC}_1, \text{PC}_2)\):

Cell PC1 PC2
A 0 0
B 1 0
C 0 1
D 5 5
E 6 5
F 5 6

B1. Compute the Euclidean distance between: (a) A and B, (b) A and C, (c) B and C, (d) A and D, (e) D and E. Leave square roots where they are not whole numbers.

B2. For each of the six cells, list its two nearest neighbours (\(k = 2\)). Then draw the kNN graph (six nodes; an edge from each cell to each of its two nearest neighbours).

B3. How many connected groups does your graph split into? List which cells are in each. If a graph-based clustering algorithm ran on this graph, how many clusters would it return, and why?

B4. Conceptual — order of operations. A classmate proposes: “skip PCA, just build the kNN graph directly on all 2000 genes.” Give two reasons the pipeline runs PCA first.

B5. Conceptual — reading a UMAP. For each statement, say whether it is a legitimate reading of a UMAP or not, and why: (a) “Cells X and Y are in the same tight island, so they are similar.” (b) “Cluster 1 is twice as far from cluster 2 as from cluster 3, so it is twice as different from cluster 2.” (c) “The red island is much bigger than the blue one, so that cell type is more variable / more abundant.” (d) “There are five clearly separated islands, so there are probably several cell populations.” (e) “UMAP-1 is about 8 for these cells, which is biologically meaningful.”

B6. Conceptual — resolution. You cluster the same graph at resolution \(0.2\), then at \(0.8\), then at \(2.0\). Give the expected order of these three runs by number of clusters (fewest to most), and explain the trend. Is that order guaranteed for every run of a heuristic clustering algorithm? Is there a “correct” number of clusters? What should you check a cluster against before believing it?

Explore

Do the by-hand part first. This demo runs a small but complete UMAP on toy data: 300 cells in 20 dimensions (think of them as 20 PCs). It builds the kNN graph with n_neighbors \(= k\), gives each edge a weight, and then moves the points: every edge acts as a spring that pulls two neighbours together, and randomly chosen pairs of cells push each other apart. The step size shrinks until the layout stops at epoch 500. There is no formula from the 20 coordinates to \((x, y)\); each cell’s position is optimised directly. The PCA panel on the left is the opposite: one fixed linear map, which would place a new cell without re-running anything.

Controls: Run / Pause, +10 epochs, Reset (same start again), New random start (next seed), the n_neighbors and min_dist sliders (changing them rebuilds and restarts), the start layout (random scatter, or “spectral”: eigenvectors of the graph, as in the eigen unit), and show kNN springs. Click a cell to mark its \(k\) high-dimensional neighbours in both panels. Everything uses fixed seeds, so the numbers below are reproducible.

E1. With 4 clusters and the default settings (\(k = 15\), min_dist \(= 0.1\), random start, seed 1), press Run and wait for epoch 500. Compare with the legend. Group D is the widest group in high-D: is it the largest island? Which island is largest? Group B sits next to A in high-D and D is far from everything: does the UMAP show that?

E2. Switch to Branching path (coloured by pseudotime). Run it at \(k = 15\). Then set n_neighbors to 5 and Run again, and then to 50. How does the picture change? Which setting would make you believe there are several separate cell populations?

E3. Back on 4 clusters at \(k = 15\): run it, note where the islands are, then press New random start and run again. Is it the “same” map? What is the same and what is not? Does the spectral start fix this here?

E4. Choose Pure noise. Run it at \(k = 15\), then at \(k = 3\), and try a new random start. What does UMAP draw? What do the PCA percentages say? What does this tell you about using a UMAP as evidence of structure?

E1. No. The island sizes follow the number of cells, not their spread. Measured with the demo’s code (seed 1, \(k = 15\)), the root-mean-square radius of each group is:

Group Cells Radius in 20-D Radius in the UMAP
A 150 4.4 1.05
B 30 1.4 0.32
C 80 2.7 0.66
D 40 6.3 0.41

D is about 4.7 times wider than B in high-D but only about 1.3 times wider in the UMAP. The order of island sizes, A > C > D > B, is the order of cell counts. Each cell’s distances are rescaled by its own \(\rho_i\) and \(\sigma_i\), so a tight group and a wide group look alike to the springs. The repulsion then gives every cell roughly the same room, so a group with more cells takes up more area.

The gaps are not kept either. In 20-D the centre of B is 9.1 from A and D is 44.8 from A, about five times further. In the UMAP (seed 1) they come out at 12.5 and 14.4. At \(k = 15\) no kNN edge links two different groups (the graph has four separate pieces), so only the repulsion acts between islands and their placement is arbitrary. The PCA panel, a linear map, does show D far away (but B overlaps A there, because the A–B difference is not in PC1 or PC2).

E2. At \(k = 15\) you see the curved path and its two branches, with the colours (pseudotime) changing smoothly along it, perhaps with a few small gaps. At \(k = 5\) the same data break into separate pieces (9 pieces with seed 1, counting a gap of more than 1 UMAP unit as a break). Each cell then only feels its 5 closest neighbours, so small gaps in the sampling become cuts, and the pieces look like distinct clusters. At \(k = 50\) the layout is one connected piece with the branch point clearly visible. The \(k = 5\) picture is the misleading one: it suggests several populations where there is one continuous differentiation path. Small \(k\) shows very local detail; large \(k\) keeps more of the large-scale shape.

E3. It is the same in the way that matters locally and different globally. With both seeds, the same four islands appear and each contains only its own group: 100% of each cell’s 10 nearest 2D neighbours share its group. But the arrangement changes. With seed 1, B lies nearest A (12.5, versus 29.9 to C); with seed 2, B lies nearest C (9.1, versus 17.9 to A). Inside the islands, only about 40% of each cell’s 10 nearest 2D neighbours are the same in the two runs. The spectral start does not fix this here, because the four groups are not connected in the graph at all, so the eigenvectors cannot say how they relate. This is why a paper should report the seed and the parameters, and why only the local grouping should be read off.

E4. UMAP still draws something: at \(k = 15\) a round, evenly filled disc, and at \(k = 3\) a lumpier shape with small clumps and strands. None of it is real, because all 300 cells come from one round Gaussian blob. The texture also moves when you change the seed: for the noise data only 42% (\(k = 15\)) to 61% (\(k = 3\)) of each cell’s 10 nearest 2D neighbours are the same between seed 1 and seed 2, against 88% for the branching path at \(k = 15\). The PCA panel gives a hint: PC1 and PC2 explain only 8% and 7% of the variance, so no direction dominates. So a UMAP alone is not evidence of structure; check it against the PCA variance, marker genes and replicate samples.

Further reading: Wattenberg, Viégas & Johnson, “How to Use t-SNE Effectively” (Distill, 2016), shows the same effects for t-SNE, which also optimises each point’s position directly. Google PAIR’s “Understanding UMAP” compares UMAP and t-SNE on toy data.

Explore: clustering the graph

The same three toy datasets, now clustered with Leiden (or Louvain, for comparison). The clustering runs on the weighted kNN graph (the graph UMAP uses, as in scanpy). The picture is a UMAP layout, computed once per dataset and used only for drawing. Leiden looks for the partition with the highest modularity \(Q\): more edge weight inside clusters than expected by chance, where the “expected” part is multiplied by the resolution \(\gamma\). A larger \(\gamma\) makes large clusters more costly, so you get more and smaller clusters.

Controls: the dataset, Leiden or Louvain, the resolution \(\gamma\) (log scale, 0.1 to 3), n_neighbors \(k\) (rebuilds the graph), show graph edges, New seed (Leiden and Louvain visit the cells in random order) and Reset. Next phase runs the algorithm one phase at a time: local move (each cell joins the neighbouring cluster that raises \(Q\) most), refine (Leiden only: each cluster is split into well-connected sub-clusters), aggregate (each sub-cluster becomes one node, drawn as a big circle, with edges as thick as their summed weight), and so on until nothing changes. On the right: the number of clusters, \(Q\), the cluster sizes, whether each cluster is connected in the graph (a cluster in separate pieces is outlined), and for the datasets with true groups, a table of true group × cluster with the adjusted Rand index (ARI: 1 = the same grouping, about 0 = no better than random labels).

C1. With 4 clusters (\(k = 15\), seed 1), drag \(\gamma\) from 0.10 to 3.00. How many clusters do you get at \(\gamma\) = 0.10, 1.00, 2.00 and 3.00, and what is the ARI? Which true group is split first, and which are never split? Why do you never get fewer than four clusters here (tick show graph edges)? At \(\gamma = 1\), press New seed a few times.

C2. Switch to Branching path (\(k = 15\)). How many clusters at \(\gamma\) = 0.10, 1.00 and 3.00? Are the cluster boundaries at places where the path is thin or interrupted? Then keep \(\gamma = 1\) and set \(k\) to 5 and to 50. What does this say about clusters on a continuous differentiation path?

C3. Choose Pure noise (\(k = 15\)). Note the number of clusters and \(Q\) at \(\gamma\) = 0.10, 0.50, 1.00 and 3.00. Compare \(Q\) at \(\gamma = 1\) with the two other datasets. Is a high modularity evidence of distinct cell types?

C4. Choose Branching path, Leiden and press Reset (\(\gamma = 1\), \(k = 15\), seed 1). Press Next phase and note the readout after each of the first three steps (local move, refine, aggregate), and after the next local move. Then press Finish. Finally, choose Pure noise, Louvain, \(k = 11\), \(\gamma = 1.58\) and press New seed three times (seed 4). Is every cluster connected? Switch to Leiden with the same settings.

C1. The numbers from the demo (Leiden, \(k = 15\), seed 1):

\(\gamma\) Clusters ARI What happens
0.10 4 1.00 exactly the four true groups (also up to \(\gamma = 0.71\))
1.00 5 0.73 A is split into 99 + 51 cells
2.00 9 0.47 A is split into 6 clusters
3.00 20 0.22 A into 13 clusters, C into 5

A, the largest group, is split first: the “expected by chance” part of \(Q\) grows with the square of a cluster’s total edge weight, so the largest cluster is the first one where splitting pays off. B (30 cells) and D (40 cells) stay whole even at \(\gamma = 3\). You never get fewer than four clusters because at \(k = 15\) the graph has four separate pieces: no edge joins two different groups. Putting two pieces with no edges between them into one cluster adds nothing to the “inside” part of \(Q\) and only increases the penalty, so \(Q\) always drops. With a new seed at \(\gamma = 1\), seeds 2, 3 and 4 give the four true groups (\(Q = 0.643\)) and seed 1 gives five (\(Q = 0.648\)): the two answers are almost equally good, and the random order decides. This is why the seed should be reported.

C2. At \(k = 15\): 4 clusters at \(\gamma = 0.10\), 11 at \(\gamma = 1.00\) and 19 at \(\gamma = 3.00\). The path is one connected piece with about the same density everywhere, so the boundaries are not at natural gaps: Leiden cuts the path into segments of roughly equal size (at \(\gamma = 1\): 17 to 35 cells each), and the cuts move when \(\gamma\) changes. The ARI against stem / branch 1 / branch 2 is only 0.27 at \(\gamma = 1\). At \(\gamma = 1\), \(k = 5\) gives 16 clusters and \(k = 50\) gives 9: \(k\) changes the graph, so it changes the clusters too. (With the edges shown, a few long edges cross the picture: they join cells that are neighbours in the graph but were drawn far apart by UMAP, which again shows that the layout is only a drawing.) On a continuum, clusters are an arbitrary discretisation, not separate cell types; trajectory methods are the better tool there.

C3. At \(k = 15\):

\(\gamma\) Clusters \(Q\)
0.10 1 0.900
0.50 2 0.520
1.00 9 0.396
3.00 33 0.263

Pure noise gives 9 “clusters” at \(\gamma = 1\), all connected, and the bar strip looks like a real result. \(Q\) cannot be compared across \(\gamma\): with one single cluster \(Q = 1 - \gamma\) by construction, which is why it is 0.900 at \(\gamma = 0.1\). At \(\gamma = 1\) the four clusters give \(Q = 0.648\), noise \(Q = 0.396\), and the branching path, which has no discrete groups at all, the highest value: \(Q = 0.825\). So a high modularity is not evidence of distinct cell types; a clustering algorithm always returns clusters. Check them with marker genes and replicates.

C4. Branching path, Leiden, \(\gamma = 1\), \(k = 15\), seed 1:

Step Phase Readout
0 start every cell is its own cluster
1 local move 370 moves, 22 clusters, \(Q = 0.758\)
2 refine the 22 clusters split into 60 well-connected sub-clusters
3 aggregate 300 cells become 60 nodes (big circles), starting in the 22 clusters
4 local move 9 moves of whole nodes, 15 clusters, \(Q = 0.809\)

Finish ends after 30 steps with 11 clusters and \(Q = 0.825\), the same result as the live clustering. On the aggregated graph, local moving shifts whole sub-clusters at once, which raises \(Q\) from 0.758 to 0.809 in 9 moves. After a full pass the algorithm starts again on the cells from the current clusters and stops when a pass changes nothing.

Pure noise, Louvain, \(k = 11\), \(\gamma = 1.58\), seed 4 gives 17 clusters with \(Q = 0.367\), and cluster 11 (17 cells) is not connected: it consists of a piece of 15 cells and a piece of 2 cells with no edge between them. Louvain moves cells one at a time and never checks whether the cluster they leave behind is still in one piece. Leiden with the same settings gives 17 clusters, all connected, with a slightly higher \(Q = 0.369\). Its refinement step only lets a cluster grow from well-connected parts, which guarantees connected clusters. On these toy data such Louvain cases are rare (this was the only one we found for seeds 1 to 5, \(k\) from 3 to 12 and a grid of \(\gamma\) values on the three datasets), but Traag and colleagues found them in real networks too, which is one reason Leiden replaced Louvain as the default.

Further reading: Traag, Waltman & van Eck, “From Louvain to Leiden: guaranteeing well-connected communities” (Sci Rep 9:5233, 2019), introduces the Leiden algorithm and shows how Louvain can produce disconnected communities.

In R

Read the standard pipeline as a recipe (no packages are installed here — nothing runs), then reproduce the neighbour step yourself in base R.

The standard Seurat pipeline

library(Seurat)
# `seu` is the QC-ed, normalized object from the preprocessing unit

seu <- ScaleData(seu)
seu <- RunPCA(seu, npcs = 50)
ElbowPlot(seu)                       # how many PCs to keep? (scree/elbow)

seu <- FindNeighbors(seu, dims = 1:30, k.param = 15)  # neighbours and SNN graph in PC space
seu <- FindClusters(seu, resolution = 0.5)            # Leiden/Louvain communities
seu <- RunUMAP(seu, dims = 1:30)                      # its own neighbour graph and 2D layout

DimPlot(seu, reduction = "umap", label = TRUE)        # UMAP coloured by cluster

Note the two calls that share dims = 1:30: FindNeighbors and RunUMAP both start from the same top-30 PCs. FindClusters uses the SNN graph from FindNeighbors — not the UMAP. RunUMAP(dims = 1:30) independently builds its own graph, with default n.neighbors = 30, whereas FindNeighbors here uses k.param = 15; changing one neighbour setting does not change the other.

Reproduce the kNN step in base R

# the six toy cells, already reduced to 2 PCs
Z <- rbind(
  A = c(0, 0), B = c(1, 0), C = c(0, 1),
  D = c(5, 5), E = c(6, 5), F = c(5, 6))

D2 <- as.matrix(dist(Z))     # all pairwise Euclidean distances
round(D2, 2)

# two nearest neighbours of each cell (column 1 of each sort is the cell itself)
apply(D2, 1, function(col) names(sort(col))[2:3])

Tasks

R1. Type in the Z matrix and run as.matrix(dist(Z)). Confirm the distances match your hand answers from B1.

R2. Run the apply(...) line. Confirm the two-nearest-neighbour lists match your B2 answers, and that each cell’s neighbours are its own group-mates.

R3. Change \(k\) from 2 to 3 conceptually: with only three cells per group, what happens when a cell must pick a third neighbour? Predict whether the two groups stay separate, then reason about it (you may modify the [2:3] index to [2:4] to check).

R4. In the Seurat block, which single line would you edit to (a) keep more principal components, (b) get more clusters, (c) change how many neighbours each cell connects to? Name the argument in each case.

Hints

The distance between the points \((a, b)\) and \((c, d)\) is \(\sqrt{(a-c)^2 + (b-d)^2}\) — the Pythagorean length of the difference vector. For A\((0,0)\) and B\((1,0)\) that is \(\sqrt{1^2+0^2}=1\). In R this is one call to dist.

For each cell, compute its distance to the other five and keep the two smallest. The three “origin” cells (A, B, C) are all within distance \(\le \sqrt{2}\approx1.41\) of each other, while any origin-to-far distance is \(\ge\sqrt{41}\approx6.40\) — so a cell’s nearest neighbours are always in its own group.

A connected group is a set of nodes you can reach from one another by following edges. If no edge ever links an origin cell to a far cell, the graph falls into two separate pieces. Graph-based clustering (Leiden / Louvain) returns one cluster per such densely connected community.

Think about (i) noise: single-cell counts are noisy, and distances in 2000 noisy dimensions are dominated by scatter, whereas the top PCs concentrate the real signal; (ii) speed/stability: computing neighbours in 30 dimensions for thousands of cells is far cheaper and more stable than in 2000. This is the denoising role of PCA from Choosing components & pitfalls.

The rule from the lecture: local grouping is trustworthy; axes, inter-cluster distances, and island sizes are not. Same island means similar cells (OK). Anything that reads a number off the axes, or treats the gap between islands or the area of an island as quantitative, is not legitimate.

Higher resolution generally favours more, smaller clusters; lower resolution generally favours fewer, larger clusters. Heuristic solutions need not have monotonic cluster counts or form nested partitions. There is no true number of clusters — the right granularity depends on the biological question. Validate a cluster against known marker genes, not against which picture looks tidiest (previewing cell-type annotation).

dist(Z) returns pairwise Euclidean distances; wrap it in as.matrix to get a full labelled matrix. For each row, sort puts the cell itself first (distance 0), so its nearest neighbours are entries 2:3. To take three neighbours instead of two, index 2:4.

Solutions

B1. Using \(\sqrt{(\Delta \text{PC}_1)^2 + (\Delta \text{PC}_2)^2}\):

    1. A\((0,0)\)–B\((1,0)\): \(\sqrt{1^2+0^2} = 1\).
    1. A\((0,0)\)–C\((0,1)\): \(\sqrt{0^2+1^2} = 1\).
    1. B\((1,0)\)–C\((0,1)\): \(\sqrt{(1)^2+(1)^2} = \sqrt{2} \approx 1.41\).
    1. A\((0,0)\)–D\((5,5)\): \(\sqrt{5^2+5^2} = \sqrt{50} \approx 7.07\).
    1. D\((5,5)\)–E\((6,5)\): \(\sqrt{1^2+0^2} = 1\).

The within-group distances (\(1\) and \(\sqrt2\)) are tiny next to the between-group distance (\(\sqrt{50}\)).

B2. By symmetry the far group (D, E, F) mirrors the near group (A, B, C). Distances: within each group the two “axis” cells are at distance \(1\) from the corner and \(\sqrt2\) from each other. Two nearest neighbours (\(k=2\)):

  • A → B \((1)\), C \((1)\) → \(\{B, C\}\)
  • B → A \((1)\), C \((\sqrt2)\) → \(\{A, C\}\)
  • C → A \((1)\), B \((\sqrt2)\) → \(\{A, B\}\)
  • D → E \((1)\), F \((1)\) → \(\{E, F\}\)
  • E → D \((1)\), F \((\sqrt2)\) → \(\{D, F\}\)
  • F → D \((1)\), E \((\sqrt2)\) → \(\{D, E\}\)

The graph: A–B, A–C, B–C form a triangle; D–E, D–F, E–F form a second triangle. No edge ever crosses between the two triangles.

B3. The graph splits into two connected groups: \(\{A, B, C\}\) and \(\{D, E, F\}\). No path of edges links one triangle to the other. A graph-based clustering algorithm (Leiden/Louvain) would return 2 clusters, because each triangle is a community densely connected within itself and disconnected from the other — exactly the “two cell populations” answer we wanted.

B4. Any two of:

  • Denoising. Single-cell counts are noisy; in 2000 gene-dimensions the Euclidean distance is dominated by random scatter, so neighbours computed there are unreliable. The top ~30 PCs concentrate the coordinated (biological) variation and discard per-gene noise, so distances — and hence neighbours — are more meaningful.
  • Speed and stability. Finding nearest neighbours for thousands of cells is far cheaper and numerically more stable in ~30 dimensions than in 2000; the whole downstream pipeline (kNN, UMAP, clustering) runs faster and more reproducibly.
  • (Also acceptable: PCA removes redundancy — co-regulated genes are highly correlated, so 2000 genes carry far fewer than 2000 independent directions.)

B5.

    1. Legitimate. Same tight island = neighbours in the graph = similar expression. Local structure is what UMAP preserves.
    1. Not legitimate. Inter-cluster distances in a UMAP are not quantitative — a bigger gap does not mean “more different”. You cannot compare gaps.
    1. Not legitimate. Island size / spread reflects the layout algorithm’s crowding control, not biological variability or cell count. To compare abundance, count the cells; to compare variability, look in PC or expression space.
    1. Legitimate. Several clearly separated islands is reasonable evidence of several populations — a qualitative, local reading. (It still needs confirmation by marker genes.)
    1. Not legitimate. The UMAP axes have no interpretation; never report or reason from an axis value.

B6. Expected fewest to most clusters: resolution \(0.2\) < \(0.8\) < \(2.0\). Raising resolution generally favours finer communities and lowering it favours coarser ones, but this order is not guaranteed: heuristic solutions can have nonmonotonic cluster counts, and partitions at different resolutions need not be nested. There is no correct number of clusters — the right granularity depends on the biological question (broad lineages vs fine subtypes), and pushing resolution too high eventually splits noise into fake “types”. Before believing a cluster, check it against known marker genes (does it express a coherent, recognisable programme?), not against which resolution produced the tidiest picture. This is the handoff to cell-type annotation.

R1. as.matrix(dist(Z)) gives (rounded):

     A    B    C    D    E    F
A 0.00 1.00 1.00 7.07 7.81 7.81
B 1.00 0.00 1.41 6.40 7.07 7.21
C 1.00 1.41 0.00 6.40 7.21 7.07
D 7.07 6.40 6.40 0.00 1.00 1.00
E 7.81 7.07 7.21 1.00 0.00 1.41
F 7.81 7.21 7.07 1.00 1.41 0.00

The A–B, A–C entries are \(1\), B–C is \(1.41=\sqrt2\), A–D is \(7.07=\sqrt{50}\), D–E is \(1\) — matching B1 exactly.

R2. apply(D2, 1, function(col) names(sort(col))[2:3]) returns, for each column (cell), its two nearest neighbours:

     A   B   C   D   E   F
[1,] "B" "A" "A" "E" "D" "D"
[2,] "C" "C" "B" "F" "F" "E"

Every cell’s two neighbours are its own group-mates — identical to the hand answer in B2. (sort puts the cell itself, distance 0, first, so we take entries 2:3.)

R3. With \(k=3\) each cell must add a third neighbour, but there are only two other cells in its own group. The third-nearest cell is therefore in the other group — so an edge now crosses between the triangles, and the graph becomes connected. Taking [2:4] shows, e.g., A’s third neighbour is a D/E/F cell. Lesson: with tiny groups, a large \(k\) forces cross-group edges and can merge genuinely separate clusters — \(k\) (like resolution) is a parameter that trades off how finely you resolve structure. (On real data with thousands of cells this is rarely a problem, since each group has far more than \(k\) members.)

R4.

    1. keep more PCs → change npcs in RunPCA (and widen dims = 1:30 in FindNeighbors/RunUMAP to use them).
    1. generally more clusters → raise resolution in FindClusters (the count is not guaranteed to increase on every run).
    1. more/fewer neighbours for the clustering graph → change k.param in FindNeighbors; for UMAP’s independently constructed graph, change n.neighbors in RunUMAP.

Where this leads

  • Cell-type annotation: the anonymous clusters (0, 1, 2, …) become named cell types by checking marker genes — the biological validation that today’s caveats keep pointing to.
  • Cell-cycle analysis: proliferating cells vary strongly along the cell cycle, which can dominate a UMAP and split a real cell type by phase. That unit returns to PCA to identify and regress out the cell-cycle signal — a direct reuse of the eigen-decomposition machinery.
  • Trajectory / pseudotime methods (beyond this course) build on the same kNN graph to order cells along differentiation paths, rather than cutting it into discrete clusters.
  • Variational autoencoders (next unit) (a nonlinear, generative latent space): unlike UMAP, a VAE can also map a latent point back to a whole expression profile and generate new cells.