ViVAE and ViScore: new players in single cell dimensional reduction

In my previous posts I compared t-SNE and UMAP, and tried PHATE and PaCMAP. Every time, I ended up with the same unsatisfying conclusion: the plots look different, the main cell type relationships do not change much, and I pick the one that looks better.

The Saeys lab recently published a paper in Cell Systems that tackles both sides of this problem with two Python tools:

  • ViVAE: a new dimensional reduction method. It is a variational autoencoder (VAE) trained with an extra stochastic multidimensional scaling (MDS) loss, which pushes distances in the 2D embedding to resemble distances in the original space. Before training, the input is denoised by averaging each cell with its nearest neighbours (kNN smoothing).
  • ViScore: a set of metrics to evaluate any embedding.
    • Local structure preservation (SL) and global structure preservation (SG) both come from the RNX curve. The curve measures, for every neighbourhood size K, how many of the K nearest neighbours of a cell in high dimension are still among its K nearest neighbours in 2D, corrected for what a random embedding would give. SL weights small neighbourhoods (log scale) and SG weights all of them equally. Both range from -1 to 1, 0 is random and higher is better.
    • xNPE (extended Neighbourhood Proportion Error) works per labelled population. It asks whether the cells of a population are surrounded by the same mix of populations in 2D as in high dimension. 0 is perfect and lower is better.

If you are wondering what autoencoders are, you can check my previous post

In this post I will:

  1. Use the first dataset to see, step by step, how ViVAE and ViScore are called.
  2. Run the whole thing on the other two datasets with helper functions.
  3. Recompute t-SNE, UMAP and PaCMAP on exactly the same input, so ViScore can score all methods side by side.

Setup

Both tools are Python packages. I manage them with uv, creating the environment inside the post folder. To keep it light, I use the CPU-only build of PyTorch (about 200 MB instead of about 3 GB). The datasets are small, so a GPU is not needed.

 1cd content/post/2026-11-16-vivae-viscore
 2uv init --bare --python 3.11
 3uv python pin 3.11.14
 4# CPU-only PyTorch: add to pyproject.toml
 5#   [[tool.uv.index]]
 6#   name = "pytorch-cpu"
 7#   url = "https://download.pytorch.org/whl/cpu"
 8#   explicit = true
 9#
10#   [tool.uv.sources]
11#   torch = { index = "pytorch-cpu" }
12uv add torch
13uv add "vivae @ git+https://github.com/saeyslab/ViVAE.git" \
14       "viscore @ git+https://github.com/saeyslab/ViScore.git" numpy pandas
15uv add pacmap   # to recompute PaCMAP on the same PCs

The pyproject.toml and uv.lock files are in the post folder, so uv sync rebuilds exactly the same environment.

Then reticulate connects R to that environment. Three details I learnt the hard way:

  • VIVAE_CUDA must be set before importing vivae.
  • Inside R, PyTorch was 20 times slower with its default number of threads (they compete with R’s own threads). Setting a single thread fixed it.
  • I import the modules with convert = FALSE, so Python objects such as the kNN graph stay in Python. Otherwise R turns the integer indices into doubles and passes them back incorrectly.
 1Sys.setenv(VIVAE_CUDA = "0")
 2reticulate::use_virtualenv("./.venv", required = TRUE)
 3library(reticulate)
 4
 5torch   <- import("torch")
 6torch$set_num_threads(1L)
 7
 8np      <- import("numpy",   convert = FALSE)
 9vivae   <- import("vivae",   convert = FALSE)
10viscore <- import("viscore", convert = FALSE)
11pacmap  <- import("pacmap",  convert = FALSE)
12
13py_config()
## python:         /media/alfonso/data/loveDNAcode/content/post/2026-11-16-vivae-viscore/.venv/bin/python
## libpython:      /home/alfonso/.local/share/uv/python/cpython-3.11.14-linux-x86_64-gnu/lib/libpython3.11.so
## pythonhome:     /media/alfonso/data/loveDNAcode/content/post/2026-11-16-vivae-viscore/.venv:/media/alfonso/data/loveDNAcode/content/post/2026-11-16-vivae-viscore/.venv
## virtualenv:     /media/alfonso/data/loveDNAcode/content/post/2026-11-16-vivae-viscore/.venv/bin/activate_this.py
## version:        3.11.14 (main, Oct 10 2025, 12:48:11) [Clang 20.1.4 ]
## numpy:          /media/alfonso/data/loveDNAcode/content/post/2026-11-16-vivae-viscore/.venv/lib/python3.11/site-packages/numpy
## numpy_version:  2.4.6
## torch:          /media/alfonso/data/loveDNAcode/content/post/2026-11-16-vivae-viscore/.venv/lib/python3.11/site-packages/torch
## 
## NOTE: Python version was forced by use_python() function
 1library(Seurat)
 2library(SingleCellExperiment)
 3library(scater)
 4library(scran)
 5library(scRNAseq)
 6library(dplyr)
 7library(tidyr)
 8library(ggplot2)
 9library(patchwork)
10library(plotly)

Helper functions

As in my CellDEEP post, I define all helpers first. In the blood section I call the ViVAE and ViScore functions one by one, then use these helpers for the other datasets.

The preprocessing is exactly the same as in the t-SNE vs UMAP post, so the plots are comparable:

  • scran normalization
  • top 2000 highly variable genes
  • 50 PCs
  1# R matrix -> float32 numpy array (what PyTorch expects)
  2to_np <- function(x) np$asarray(as.matrix(x), dtype = "float32")
  3
  4# scran normalization + HVGs + PCA, as in the t-SNE vs UMAP post
  5prepSCE <- function(sce) {
  6  sce <- sce[rowSums(counts(sce)) > 0, ]
  7  clusters <- quickCluster(sce, BPPARAM = BiocParallel::MulticoreParam(8))
  8  sce <- computeSumFactors(sce, cluster = clusters, min.mean = 0.1,
  9                           BPPARAM = BiocParallel::MulticoreParam(8))
 10  sce <- logNormCounts(sce, BPPARAM = BiocParallel::MulticoreParam(8))
 11  top.HVGs <- getTopHVGs(modelGeneVar(sce), n = 2000)
 12  set.seed(1234)
 13  runPCA(sce, subset_row = top.HVGs, ncomponents = 50)
 14}
 15
 16# ViVAE: optional kNN denoising, then train the model and embed
 17runViVAE <- function(pca, smooth = TRUE, k_knn = 100L, k_smooth = 50L,
 18                     n_epochs = 100L, lam_mds = 100, seed = 42L, latent_dim = 2L) {
 19  x <- to_np(pca)
 20  if (smooth) {
 21    knn <- vivae$make_knn(x = x, k = k_knn, random_state = seed, verbose = FALSE)
 22    x <- vivae$smooth(x = x, knn = knn, k = k_smooth, coef = 1, n_iter = 1L)
 23  }
 24  model <- vivae$ViVAE(input_dim = ncol(pca), latent_dim = latent_dim, random_state = seed)
 25  elapsed <- system.time(
 26    model$fit(X = x, n_epochs = n_epochs, lam_mds = lam_mds, verbose = FALSE)
 27  )[["elapsed"]]
 28  emb <- py_to_r(model$transform(x))
 29  dimnames(emb) <- list(rownames(pca), paste0("ViVAE_", seq_len(latent_dim)))
 30  attr(emb, "elapsed") <- elapsed
 31  emb
 32}
 33
 34# t-SNE, UMAP and PaCMAP on the same 50 PCs, with the defaults of my previous posts
 35runOtherDR <- function(sce, seed = 1234) {
 36  pca <- reducedDim(sce, "PCA")
 37  set.seed(seed)
 38  t_tsne <- system.time(tsne <- calculateTSNE(sce, dimred = "PCA", perplexity = 50))
 39  set.seed(seed)
 40  t_umap <- system.time(umap <- calculateUMAP(sce, dimred = "PCA"))   # n_neighbors = 15, min_dist = 0.01
 41  t_pac  <- system.time(
 42    pac <- py_to_r(pacmap$PaCMAP(n_components = 2L, random_state = 42L)$fit_transform(to_np(pca)))
 43  )
 44  dimnames(pac) <- list(rownames(pca), c("PaCMAP_1", "PaCMAP_2"))
 45  list(TSNE = tsne, UMAP = umap, PaCMAP = pac,
 46       times = c(`t-SNE` = t_tsne[["elapsed"]], UMAP = t_umap[["elapsed"]],
 47                 PaCMAP = t_pac[["elapsed"]]))
 48}
 49
 50# the embeddings scored in every dataset
 51embList <- function(sce) {
 52  list(
 53    "ViVAE"             = reducedDim(sce, "ViVAE"),
 54    "ViVAE (no smooth)" = reducedDim(sce, "ViVAE_noSmooth"),
 55    "t-SNE"             = reducedDim(sce, "TSNE"),
 56    "UMAP"              = reducedDim(sce, "UMAP"),
 57    "PaCMAP"            = reducedDim(sce, "PaCMAP"),
 58    "PCA (PC1-2)"       = reducedDim(sce, "PCA")[, 1:2]
 59  )
 60}
 61
 62# ViScore: Sl/Sg + RNX curve and per-population xNPE for a named list of embeddings
 63scoreEmb <- function(hd, ld_list, labels, k = 50L) {
 64  hd_np  <- to_np(hd)
 65  annot  <- np$array(as.character(labels))
 66  knn_hd <- viscore$make_knn(x = hd_np, k = k, verbose = FALSE)
 67  res <- lapply(names(ld_list), function(m) {
 68    s <- py_to_r(viscore$score(hd = hd_np, ld = to_np(ld_list[[m]])))
 69    x <- py_to_r(viscore$xnpe(hd = hd_np, ld = to_np(ld_list[[m]]),
 70                              annot = annot, knn = knn_hd))
 71    list(
 72      sp   = data.frame(embedding = m, Sl = s$Sl, Sg = s$Sg),
 73      rnx  = data.frame(embedding = m, K = seq_along(s$RNX), RNX = as.numeric(s$RNX)),
 74      xnpe = data.frame(embedding = m, population = names(x), xNPE = unlist(x))
 75    )
 76  })
 77  list(sp   = bind_rows(lapply(res, `[[`, "sp")),
 78       rnx  = bind_rows(lapply(res, `[[`, "rnx")),
 79       xnpe = bind_rows(lapply(res, `[[`, "xnpe")))
 80}
 81
 82# plots
 83plotEmb <- function(sce, dimred, celltype, title = dimred) {
 84  plotReducedDim(sce, dimred = dimred, colour_by = celltype) +
 85    ggtitle(title) + theme_bw()
 86}
 87
 88plotRNX <- function(rnx) {
 89  ggplot(rnx, aes(K, RNX, colour = embedding)) +
 90    geom_line(linewidth = 0.8) +
 91    scale_x_log10() +
 92    labs(x = "Neighbourhood size K (log scale)", y = expression(R[NX](K)),
 93         colour = NULL) +
 94    theme_bw() + theme(legend.position = "bottom")
 95}
 96
 97plotXNPE <- function(xnpe) {
 98  ggplot(xnpe, aes(xNPE, reorder(population, xNPE), fill = embedding)) +
 99    geom_col(position = position_dodge(width = 0.8), width = 0.75) +
100    labs(x = "xNPE (lower is better)", y = NULL, fill = NULL) +
101    theme_bw() + theme(legend.position = "bottom")
102}
103
104# 2x2 panel: t-SNE, UMAP, PaCMAP and ViVAE with the same colours
105plotPanel <- function(sce, celltype) {
106  (plotEmb(sce, "TSNE", celltype, "t-SNE") + plotEmb(sce, "UMAP", celltype, "UMAP") +
107   plotEmb(sce, "PaCMAP", celltype, "PaCMAP") + plotEmb(sce, "ViVAE", celltype, "ViVAE")) +
108    plot_layout(ncol = 2, guides = "collect")
109}
110
111# whole workflow for one (already preprocessed) dataset
112runAll <- function(sce, celltype) {
113  pca <- reducedDim(sce, "PCA")
114  reducedDim(sce, "ViVAE")          <- runViVAE(pca, smooth = TRUE)
115  reducedDim(sce, "ViVAE_noSmooth") <- runViVAE(pca, smooth = FALSE)
116  dr <- runOtherDR(sce)
117  reducedDim(sce, "TSNE")   <- dr$TSNE
118  reducedDim(sce, "UMAP")   <- dr$UMAP
119  reducedDim(sce, "PaCMAP") <- dr$PaCMAP
120  scores <- scoreEmb(pca, embList(sce), sce[[celltype]])
121  times <- c(ViVAE = attr(reducedDim(sce, "ViVAE"), "elapsed"), dr$times)
122  list(sce = sce, scores = scores, times = times)
123}
124
125# cache key: cached chunks that call the helpers rerun when any helper changes
126helpers_hash <- digest::digest(lapply(
127  list(prepSCE, runViVAE, runOtherDR, embList, scoreEmb, runAll), deparse))

Blood (cellxgene TSP1): step by step

This is our good old friend, the blood dataset from the cellxgene database. The filtering is the same as in the t-SNE vs UMAP and PaCMAP posts.

 1seurat <- readRDS(file.path(rds.path, '582149d8-2a8f-44cf-9605-337b8ca8d518.rds'))
 2
 3keep.cells <- seurat[[]] %>%
 4  tibble::rownames_to_column('Cell') %>%
 5  filter(assay == "10x 3' v3", donor_id == 'TSP1') %>%
 6  group_by(cell_type) %>%
 7  mutate(tot = n()) %>%
 8  filter(tot >= 20)
 9
10blood <- as.SingleCellExperiment(subset(seurat, cells = keep.cells$Cell))
11rm(seurat); invisible(gc())
12reducedDims(blood) <- NULL
13blood$cell_type <- factor(blood$cell_type)
14
15blood <- prepSCE(blood)
16blood
## class: SingleCellExperiment 
## dim: 36413 4215 
## metadata(0):
## assays(2): counts logcounts
## rownames(36413): ENSG00000000003 ENSG00000000419 ... ENSG00000290165
##   ENSG00000290166
## rowData names(0):
## colnames(4215): TSP1_Blood_NA_10X3primev31_1_3_AAACCCAAGAATAGTC
##   TSP1_Blood_NA_10X3primev31_1_3_AAACCCAAGCAACAGC ...
##   TSP1_Blood_NA_10X3primev31_1_2_TTTGGTTAGAGATCGC
##   TSP1_Blood_NA_10X3primev31_1_2_TTTGGTTTCGCCAGTG
## colData names(55): donor_id tissue_in_publication ... ident sizeFactor
## reducedDimNames(1): PCA
## mainExpName: RNA
## altExpNames(0):
1table(blood$cell_type)
## 
##                     erythrocyte                          B cell 
##                             100                             386 
##                        monocyte             natural killer cell 
##                            1330                              71 
## CD4-positive, alpha-beta T cell CD8-positive, alpha-beta T cell 
##                            1128                             442 
##                        basophil                      neutrophil 
##                              32                             468 
##              classical monocyte          non-classical monocyte 
##                              77                             151 
##           intermediate monocyte 
##                              30

ViVAE, step by step

ViVAE does not take the expression matrix directly. Like t-SNE or UMAP, it takes the PCA coordinates.

1pca <- reducedDim(blood, "PCA")
2pca_np <- to_np(pca)
3dim(pca)
## [1] 4215   50

1. kNN graph. make_knn() builds an approximate k-nearest-neighbour graph with PyNNDescent. It returns two matrices with one row per cell: the indices of the neighbours, and their distances. The first column is the cell itself.

1knn <- vivae$make_knn(x = pca_np, k = 100L, random_state = 42L, verbose = FALSE)
2knn_r <- py_to_r(knn)
3knn_r[[1]][1:3, 1:6]   # neighbour indices (0-based, Python)
##      [,1] [,2] [,3] [,4] [,5] [,6]
## [1,]    0 2821 3335 2136 3963 3122
## [2,]    1 4032  798  989 3160 2915
## [3,]    2 3592 3357 2142  689 2761
1round(knn_r[[2]][1:3, 1:6], 2)   # distances
##      [,1]  [,2]  [,3]  [,4]  [,5]  [,6]
## [1,]    0 26.91 28.73 30.03 30.22 30.23
## [2,]    0  7.24  7.41  7.50  7.50  7.52
## [3,]    0 31.65 34.55 35.70 37.73 37.74

2. Denoising. smooth() moves each cell towards the average of its k nearest neighbours. With coef = 1 each cell is replaced by that average, as in the ViVAE scRNA-seq tutorial. It is the same idea as the kNN smoothing used before RNA velocity or imputation methods.

 1pca_smooth_np <- vivae$smooth(x = pca_np, knn = knn, k = 50L, coef = 1, n_iter = 1L)
 2pca_smooth <- py_to_r(pca_smooth_np)
 3
 4df <- bind_rows(
 5  data.frame(PC1 = pca[, 1], PC2 = pca[, 2], cell_type = blood$cell_type, input = "PCA"),
 6  data.frame(PC1 = pca_smooth[, 1], PC2 = pca_smooth[, 2], cell_type = blood$cell_type,
 7             input = "PCA after kNN smoothing")
 8)
 9ggplot(df, aes(PC1, PC2, colour = cell_type)) +
10  geom_point(size = 0.4) +
11  facet_wrap(~input) +
12  guides(colour = guide_legend(override.aes = list(size = 3))) +
13  theme_bw()

The cells are pulled together: every cell type gets tighter, while the global layout does not change.

3. Model. The default architecture has a few small hidden layers (32, 64, 128 and 32 units) and a 2D latent space.

1model <- vivae$ViVAE(input_dim = ncol(pca), latent_dim = 2L, random_state = 42L)
2model
## ViVAE(input_dim=50, latent_dim=2, device=cpu)

4. Training. fit() combines three losses:

  • reconstruction (the decoder must recover the input)
  • KL divergence (the variational part)
  • the MDS loss with weight lam_mds. The authors recommend 100 for scRNA-seq and 10 for cytometry.

I use 100 epochs, as in the tutorial.

1fit_time <- system.time(
2  model$fit(X = pca_smooth_np, n_epochs = 100L, lam_mds = 100, verbose = FALSE)
3)
4fit_time
##    user  system elapsed 
##  26.547  78.435  13.345

5. Embedding. transform() passes the cells through the trained encoder.

1emb <- py_to_r(model$transform(pca_smooth_np))
2dimnames(emb) <- list(colnames(blood), c("ViVAE_1", "ViVAE_2"))
3reducedDim(blood, "ViVAE") <- emb
1plotEmb(blood, "ViVAE", "cell_type")

To see what the denoising adds, here is the same model trained on the raw PCA coordinates. I now use the runViVAE() helper, which wraps steps 1 to 5.

1reducedDim(blood, "ViVAE_noSmooth") <- runViVAE(pca, smooth = FALSE)
1plotEmb(blood, "ViVAE_noSmooth", "cell_type", "ViVAE without kNN smoothing")

Comparison with t-SNE, UMAP and PaCMAP

To score the other methods with ViScore I need their coordinates, so I recompute them with the same settings as in my previous posts (t-SNE vs UMAP and PaCMAP):

  • t-SNE with perplexity 50
  • UMAP with the defaults (15 neighbours, min_dist 0.01)
  • PaCMAP with the defaults

All of them take the same 50 PCs as ViVAE, so the comparison is fair. This differs slightly from my previous posts: there, runTSNE() used its default input (the top 500 genes of the log-normalized counts), and PaCMAP ran on the scaled highly variable genes through SeuratWrappers.

runOtherDR() returns plain R matrices, so this chunk can be cached safely.

1blood_dr <- runOtherDR(blood)
1reducedDim(blood, "TSNE")   <- blood_dr$TSNE
2reducedDim(blood, "UMAP")   <- blood_dr$UMAP
3reducedDim(blood, "PaCMAP") <- blood_dr$PaCMAP
1plotPanel(blood, "cell_type")

ViScore, step by step

score() takes the high-dimensional data (here the 50 PCs, the same input all methods saw) and the embedding. It returns SL, SG and the full RNX curve. Computing RNX exactly needs all pairwise distances, so ViScore uses a vantage-point tree approximation to keep it fast.

1s <- py_to_r(viscore$score(hd = pca_np, ld = to_np(reducedDim(blood, "ViVAE"))))
2s$Sl
## [1] 0.4401102
1s$Sg
## [1] 0.755919
1length(s$RNX)   # one value per neighbourhood size K = 1 ... n-2
## [1] 4213

A single number means little on its own, so I compare six embeddings:

  • ViVAE, with and without smoothing
  • t-SNE, UMAP and PaCMAP
  • the first two PCs, the simplest possible 2D embedding, as a baseline

The paper runs the same kind of benchmark on many more datasets and methods.

xnpe() needs the cell labels and a kNN graph of the high-dimensional data. scoreEmb() builds one with viscore$make_knn() (k = 50, because the smallest populations have about 20 cells), then runs score() and xnpe() for every embedding.

1blood_scores <- scoreEmb(pca, embList(blood), blood$cell_type)
1knitr::kable(blood_scores$sp, digits = 3,
2             col.names = c("Embedding", "Local SP (Sl)", "Global SP (Sg)"))
Embedding Local SP (Sl) Global SP (Sg)
ViVAE 0.440 0.756
ViVAE (no smooth) 0.418 0.768
t-SNE 0.471 0.418
UMAP 0.474 0.617
PaCMAP 0.442 0.657
PCA (PC1-2) 0.336 0.748
1plotRNX(blood_scores$rnx)

The RNX curve shows where each embedding is good. The left side is the closest neighbours (local structure), the right side is large neighbourhoods (global structure).

1plotXNPE(blood_scores$xnpe)

Liver

Same HCA liver dataset as in the previous posts, retrieved with the scRNAseq package. Now everything is a single call to runAll().

Loading and preprocessing go in their own cached chunk, so changing a method later does not download and normalize the data again.

1sce.liver <- prepSCE(fetchDataset("he-organs-2020", "2023-12-21", "liver"))
1liver <- runAll(sce.liver, "Cell_type_in_merged_data")
1plotPanel(liver$sce, "Cell_type_in_merged_data")
1knitr::kable(liver$scores$sp, digits = 3,
2             col.names = c("Embedding", "Local SP (Sl)", "Global SP (Sg)"))
Embedding Local SP (Sl) Global SP (Sg)
ViVAE 0.341 0.538
ViVAE (no smooth) 0.305 0.562
t-SNE 0.429 0.463
UMAP 0.389 0.489
PaCMAP 0.368 0.556
PCA (PC1-2) 0.223 0.538
1plotRNX(liver$scores$rnx) + plotXNPE(liver$scores$xnpe)

Bone marrow

1sce.marrow <- prepSCE(fetchDataset("he-organs-2020", "2023-12-21", "marrow"))
1marrow <- runAll(sce.marrow, "Cell_type_in_merged_data")
1plotPanel(marrow$sce, "Cell_type_in_merged_data")
1knitr::kable(marrow$scores$sp, digits = 3,
2             col.names = c("Embedding", "Local SP (Sl)", "Global SP (Sg)"))
Embedding Local SP (Sl) Global SP (Sg)
ViVAE 0.330 0.667
ViVAE (no smooth) 0.291 0.633
t-SNE 0.406 0.553
UMAP 0.352 0.585
PaCMAP 0.333 0.582
PCA (PC1-2) 0.261 0.632
1plotRNX(marrow$scores$rnx) + plotXNPE(marrow$scores$xnpe)

Summary across datasets

 1sp_all <- bind_rows(
 2  mutate(blood_scores$sp,   dataset = "Blood"),
 3  mutate(liver$scores$sp,   dataset = "Liver"),
 4  mutate(marrow$scores$sp,  dataset = "Bone marrow")
 5)
 6
 7ggplot(sp_all, aes(Sl, Sg, colour = embedding, shape = dataset)) +
 8  geom_point(size = 4) +
 9  labs(x = "Local structure preservation (Sl)",
10       y = "Global structure preservation (Sg)", colour = NULL, shape = NULL) +
11  theme_bw()
1sp_all %>%
2  pivot_longer(c(Sl, Sg), names_to = "metric") %>%
3  pivot_wider(names_from = embedding, values_from = value) %>%
4  arrange(metric, dataset) %>%
5  knitr::kable(digits = 3)
dataset metric ViVAE ViVAE (no smooth) t-SNE UMAP PaCMAP PCA (PC1-2)
Blood Sg 0.756 0.768 0.418 0.617 0.657 0.748
Bone marrow Sg 0.667 0.633 0.553 0.585 0.582 0.632
Liver Sg 0.538 0.562 0.463 0.489 0.556 0.538
Blood Sl 0.440 0.418 0.471 0.474 0.442 0.336
Bone marrow Sl 0.330 0.291 0.406 0.352 0.333 0.261
Liver Sl 0.341 0.305 0.429 0.389 0.368 0.223
 1xnpe_all <- bind_rows(
 2  mutate(blood_scores$xnpe,  dataset = "Blood"),
 3  mutate(liver$scores$xnpe,  dataset = "Liver"),
 4  mutate(marrow$scores$xnpe, dataset = "Bone marrow")
 5)
 6xnpe_all %>%
 7  group_by(dataset, embedding) %>%
 8  summarise(`mean xNPE` = mean(xNPE), .groups = "drop") %>%
 9  pivot_wider(names_from = embedding, values_from = `mean xNPE`) %>%
10  knitr::kable(digits = 3)
dataset PCA (PC1-2) PaCMAP UMAP ViVAE ViVAE (no smooth) t-SNE
Blood 0.179 0.058 0.070 0.065 0.050 0.067
Bone marrow 0.212 0.076 0.082 0.084 0.099 0.080
Liver 0.226 0.092 0.079 0.157 0.301 0.085

Running time

Seconds per method (ViVAE training on CPU with a single thread and 100 epochs, without the kNN smoothing step):

1timeRow <- function(dataset, cells, times) {
2  data.frame(dataset = dataset, cells = cells, as.list(times), check.names = FALSE)
3}
4bind_rows(
5  timeRow("Blood", ncol(blood), c(ViVAE = fit_time[["elapsed"]], blood_dr$times)),
6  timeRow("Liver", ncol(liver$sce), liver$times),
7  timeRow("Bone marrow", ncol(marrow$sce), marrow$times)
8) %>%
9  knitr::kable(digits = 1)
dataset cells ViVAE t-SNE UMAP PaCMAP
Blood 4215 13.3 10.6 4.9 1.0
Liver 2839 9.8 7.5 3.9 0.7
Bone marrow 3230 9.8 9.0 4.3 0.8

Conclusions

  • The main cell type relationships do not change. In all three datasets, t-SNE, UMAP, PaCMAP and ViVAE draw the same picture: lymphoid vs myeloid, isolated erythrocytes and neutrophils, and the T/NK continuum. What changes is how clusters are placed relative to each other.
  • There is a clear local-global trade-off, and every method sits at a different point on it.
    • t-SNE preserves local structure best (highest SL in all three datasets, 0.41–0.47) but global structure worst (SG 0.42–0.55). Its RNX curve is the highest for small neighbourhoods and collapses for neighbourhoods above a few hundred cells: the clusters are right, their relative positions are not.
    • ViVAE is the mirror image. Its SG is the best or close to the best (0.54–0.76), at the level of the first two PCs, while its SL (0.33–0.44) is the lowest of the non-linear methods. This is what the MDS loss is designed for.
    • UMAP and PaCMAP sit in between. UMAP keeps a bit more local structure than PaCMAP in all three datasets, and PaCMAP more global structure in blood and liver (they tie in marrow).
  • The PCA baseline is surprisingly good globally and poor locally. PC1-2 had the lowest SL everywhere, but its SG beats t-SNE, UMAP and PaCMAP in blood and marrow.
  • Cell type neighbourhoods (xNPE) are similar for all non-linear methods (mean xNPE about 0.05–0.09), and 2 to 3 times better than PC1-2. The exception is liver, where ViVAE (0.16, and 0.30 without smoothing) is clearly worse than the others. For rare populations with a handful of cells, xNPE jumps to extreme values, so I would not over-interpret single bars.
  • The cell types used by xNPE are not a ground truth. They are the published annotations, inferred by the original authors from the same scRNA-seq data (clustering plus marker genes), so xNPE measures agreement with that annotation rather than with biology.
    • xNPE uses the same labels in high dimension and in 2D, so a wrong label goes unnoticed: two real cell types merged under one label cannot be told apart, and noisy labels make the score uninformative. xNPE can only be as fine as the annotation.
    • There is a possible circularity: annotations are usually built from a kNN graph in PCA space and refined by looking at a UMAP, which may favour methods that preserve the kNN graph (UMAP, t-SNE) over ViVAE. Part of ViVAE’s worse xNPE in liver could come from this.
    • SL and SG do not use labels, so the local-global trade-off above is not affected.
    • A real ground truth needs information from outside the transcriptome, such as simulated data, sorted populations or cell line mixtures, or an independent modality like CITE-seq surface proteins. None of these datasets has it.
  • kNN smoothing helps ViVAE’s local structure (SL up by 0.02–0.04 in every dataset), which makes a lot of sense, and its xNPE in liver and marrow.
  • All methods are fast at this size. PaCMAP took about a second, UMAP about 5 s, t-SNE about 10 s and ViVAE training about 10–15 s for 3,000–4,000 cells.

Take away

  • ViScore is, for me, the most useful part. It works with any embedding, so it finally gives a number to the “which plot is better” discussion from my previous posts.
  • Choose the method by the question. t-SNE is best for evaluating within-cluster structure and cluster separation (local structure), while ViVAE or PaCMAP are safer for evaluating the overall arrangement of clusters, including how neighbouring and distant clusters relate to each other (global structure).
  • ViVAE is a reasonable alternative when global structure matters.
  • The kNN smoothing changes the look of the ViVAE plot a lot. Try with and without it before deciding.
  • As always, use the plots to visualize and keep the downstream analyses (clustering, trajectories, differential expression) on the PCA space.
  • Running Python tools from R through reticulate plus uv is painless, once you know about the thread setting and convert = FALSE.

Further reading

Bonus: ViVAE in 3D

The 2D plot is not a limitation of ViVAE. The size of the latent space is just the latent_dim argument, and the MDS loss works the same in any number of dimensions. Here is the blood dataset in 3D, using the same helper with latent_dim = 3L:

1reducedDim(blood, "ViVAE_3D") <- runViVAE(pca, smooth = TRUE, latent_dim = 3L)

As in my slingshot post, I use plotly for an interactive plot (drag to rotate, scroll to zoom).

1df3d <- data.frame(reducedDim(blood, "ViVAE_3D"), cell_type = blood$cell_type)
2
3plot_ly(df3d, x = ~ViVAE_1, y = ~ViVAE_2, z = ~ViVAE_3,
4        color = ~cell_type, type = "scatter3d", mode = "markers",
5        marker = list(size = 2)) %>%
6  layout(scene = list(xaxis = list(title = "ViVAE 1"),
7                      yaxis = list(title = "ViVAE 2"),
8                      zaxis = list(title = "ViVAE 3")))

Does the extra dimension preserve more structure? ViScore does not care about the number of dimensions of the embedding, so we can compare the 2D and 3D versions directly.

1blood_scores_3d <- scoreEmb(pca, list(
2  "ViVAE 2D" = reducedDim(blood, "ViVAE"),
3  "ViVAE 3D" = reducedDim(blood, "ViVAE_3D")
4), blood$cell_type)
1knitr::kable(blood_scores_3d$sp, digits = 3,
2             col.names = c("Embedding", "Local SP (Sl)", "Global SP (Sg)"))
Embedding Local SP (Sl) Global SP (Sg)
ViVAE 2D 0.440 0.756
ViVAE 3D 0.471 0.773
1plotRNX(blood_scores_3d$rnx)

The third dimension helps, but only a little. SL goes from 0.44 to 0.47 and SG from 0.76 to 0.77. The RNX curve of the 3D embedding sits just above the 2D one at almost every neighbourhood size, with the largest gain among the closest neighbours (K < 20). In other words, squeezing the data into 2D costs ViVAE little. The 3D plot is nice for exploring the data interactively, but it cannot go into a paper figure, and its rotation is arbitrary, so I would keep the 2D version as the default.

Bonus: Animated GIF

Bone marrow with UMAP, PaCMAP and ViVAE.

 1library(magick)
 2
 3# one PNG per method, same style and colours
 4pngs <- c(UMAP = "UMAP.marrow.png", PaCMAP = "PaCMAP.marrow.png", ViVAE = "ViVAE.marrow.png")
 5for (m in names(pngs)) {
 6  ggsave(pngs[[m]],
 7         plot = plotEmb(marrow$sce, m, "Cell_type_in_merged_data", NULL),
 8         height = 5.86, width = 8.89)
 9}
10
11# same size for every frame, plus a white header strip with the method name
12add_header <- function(img, title) {
13  img <- img %>% image_scale("800x530") %>% image_background("white") %>% image_extent("800x530")
14  header <- image_blank(800, 50, "white") %>%
15    image_annotate(title, size = 30, weight = 700, gravity = "center")
16  image_append(c(header, img), stack = TRUE)
17}
18
19frames <- do.call(c, lapply(names(pngs), function(m) add_header(image_read(pngs[[m]]), m)))
20
21image_write(image_animate(frames, fps = 0.5), "UMAP_PaCMAP_ViVAE.gif")
UMAP, PaCMAP and ViVAE of the bone marrow dataset
comments powered by Disqus