Tutorials › Statistical Methods for Single-Cell RNA Sequencing › Selecting Latent Dimension Without Overfitting

Latent Variable Models for Single-Cell Data · Tutorial 673 of 700

Selecting Latent Dimension Without Overfitting

Compare candidate VAE latent dimensions using held-out evidence and complementary diagnostics, and learn why the smallest training loss is not a reliable selection rule.

Advanced 13 min read

What You'll Learn

  • Separate training fit from predictive performance on held-out cells.
  • Compare held-out likelihood estimates and reconstruction measures on a common scale.
  • Use per-coordinate KL contributions as a diagnostic of latent usage, not as a count of biological factors.
  • Assess whether downstream neighborhoods or cluster assignments persist across seeds.
  • Choose a dimension by weighing predictive fit, stability, and model simplicity.
  • Recognize when a lower training loss reflects extra flexibility rather than better generalization.

Why Latent Dimension Needs a Selection Rule

A count VAE maps each cell to a latent vector with a chosen number of coordinates, \(K\). Increasing \(K\) gives the model more capacity to represent variation, but that variation need not be reproducible or useful. A model can fit its training cells more closely while predicting new cells no better, or even worse. The selection problem is therefore not “Which dimension gives the smallest training loss?” It is “Which dimension gives adequate predictive fit and stable downstream results without unnecessary complexity?”

For a candidate dimension \(K\), write the generative model as \(p_\theta(x\mid z,c)\), with latent variable \(z\), observed cell counts \(x\), and any conditioning variables \(c\) included in the model. The encoder supplies an approximate posterior \(q_\phi(z\mid x,c)\). The evidence lower bound (ELBO) for a cell is the expected log likelihood minus the Kullback–Leibler divergence from the approximate posterior to the prior. The earlier material on evidence lower bounds and count VAEs supplies this objective; here the focus is how to compare candidate dimensions.

Definition: Latent-dimension selection is the choice of \(K\) among prespecified candidate dimensions using evidence about generalization and the intended downstream use. No single diagnostic establishes that a dimension is biologically “true.” A defensible choice weighs held-out predictive performance, reconstruction, latent usage, stability, and model parsimony.

Set Up a Fair Comparison

Compare models on the same count data, genes, conditioning variables, and data splits. Use the same observation model and broadly comparable encoder and decoder design; otherwise, a metric difference may reflect a changed model specification rather than \(K\). Train each candidate from multiple random initializations when feasible, since optimization variability can be substantial. Keep a final test set untouched until the candidate and evaluation procedure have been chosen.

The split should match the intended generalization target. A random split of cells can assess prediction for additional cells drawn from represented samples. If the intended use is prediction for new donors or samples, hold out entire donors or samples instead; random cell splitting may otherwise put closely related cells in both training and validation sets. Fit data-dependent preprocessing, such as feature selection, using training data only. Apply the resulting choices unchanged to validation and test data.

For count data, the likelihood comparison must use the same genes and account consistently for library size and any modeled covariates. Report predictive scores per cell, and, where useful, per observed count or gene, so that totals are not confused with changes in the number of observations. Do not compare a score based on one gene set or count representation with a score based on another as though the values were directly comparable.

Held-Out Likelihood and Reconstruction

The marginal likelihood for a held-out cell is \(p_\theta(x\mid c)=\int p_\theta(x\mid z,c)p(z\mid c)\,dz\). It measures how well the model assigns probability to the observed counts after accounting for latent uncertainty. This integral is usually unavailable in closed form. A practical comparison can use an importance-sampling estimate based on the encoder distribution. For draws \(z^{(m)}\) from \(q_\phi(z\mid x,c)\), define the importance weight \(w_m=p_\theta(x,z^{(m)}\mid c)/q_\phi(z^{(m)}\mid x,c)\), where \(p_\theta(x,z\mid c)=p_\theta(x\mid z,c)p(z\mid c)\). Then estimate the log marginal likelihood by:

$$ \widehat{\log p_\theta(x\mid c)} = \log\left(\frac{1}{M}\sum_{m=1}^{M} w_m\right). $$

Use the same estimation procedure and number of importance samples \(M\) across candidate dimensions, and check that the estimate is stable as \(M\) increases. The finite-\(M\) log estimate is not an exact likelihood value; its accuracy can depend on the quality of the proposal distribution. The ELBO is a lower bound on the log marginal likelihood, not an unbiased estimate of it. ELBO comparisons can still be informative when calculated consistently, but a difference may partly reflect a change in the tightness of the variational bound.

Reconstruction measures offer a complementary view. For example, held-out negative log likelihood or a count deviance can summarize how closely predictions match observed counts. State exactly which reconstruction measure is used and whether smaller or larger is better. Reconstruction measures alone can reward fitting idiosyncrasies, so they should not replace held-out predictive evaluation. Training reconstruction is especially unsuitable as the sole selection criterion: additional capacity can improve it even when generalization does not.

Worked Example: When Lower Training Loss Misleads

Suppose three count VAEs are fit to the same hypothetical training set, with \(K=4\), \(K=8\), or \(K=16\). All use the same split, count likelihood, and decoder design. The table gives average training negative log likelihood (lower is better), estimated held-out log likelihood per cell (higher is better), and held-out reconstruction deviance per cell (lower is better).

Dimension \(K\)Training negative log likelihoodHeld-out log likelihood per cellHeld-out deviance per cell
434-1.9231
830-1.8428
1624-1.8629

The training score favors \(K=16\): its negative log likelihood is \(24\), compared with \(30\) for \(K=8\). But on held-out cells, \(K=8\) has the highest estimated log likelihood, \(-1.84\) per cell, and the lowest deviance, \(28\). The \(K=16\) model does not improve either held-out measure over \(K=8\). The training improvement therefore does not establish a predictive benefit from the extra coordinates.

Suppose repeated fits give standard errors of \(0.025\) and \(0.040\) for the held-out log-likelihood estimates at \(K=8\) and \(K=16\), respectively. The observed difference is \((-1.84)-(-1.86)=0.02\) log-likelihood units per cell, small relative to those uncertainties. It would be unwarranted to claim a clear predictive advantage for either dimension from this comparison alone. If stability is also comparable, \(K=8\) is a reasonable parsimonious choice; if the intended downstream results are materially more stable at \(K=16\), that evidence should enter the decision. The example illustrates why the training minimum is not the selection rule.

KL Usage: A Diagnostic, Not a Biological Count

For a diagonal Gaussian encoder and a standard normal prior, the KL contribution for coordinate \(j\) in a cell is:

$$ \mathrm{KL}\!\left(q_\phi(z_j\mid x,c)\,\|\,N(0,1)\right) = \frac{1}{2}\left(\mu_j^2+\sigma_j^2-\log(\sigma_j^2)-1\right). $$

Averaging this quantity over cells gives a per-coordinate summary of how much the approximate posterior for that coordinate differs from its prior. A coordinate with a very small average contribution is often described as weakly used under this fitted model. Summing contributions gives the total KL penalty, in nats per cell. These summaries depend on the prior, parameterization, and fitted solution. In particular, KL usage does not count biological processes, and a low value for one coordinate does not prove that the corresponding variation is irrelevant.

Worked Example: Reading Per-Coordinate KL Contributions

Consider a hypothetical \(K=4\) model with average KL contributions across validation cells of \(0.31\), \(0.14\), \(0.018\), and \(0.006\) nats per cell. The total average KL is:

$$ 0.31+0.14+0.018+0.006=0.474\ \text{nats per cell}. $$

The final coordinate contributes only \(0.006\) nats per cell on average, compared with \(0.31\) for the first. This is evidence that the fourth coordinate is close to its prior for many cells under this fit. It is not sufficient reason, by itself, to reduce \(K\) from four to three: the coordinate could matter for a subgroup, results may vary across seeds, or the learned representation may redistribute information when refit at a smaller dimension.

For a concrete calculation, suppose that for one cell and one coordinate the encoder has \(\mu_j=0.8\) and \(\sigma_j^2=0.5\). Its KL contribution is:

$$ \frac{1}{2}\left(0.8^2+0.5-\log(0.5)-1\right) = \frac{1}{2}(0.64+0.5+0.6931-1) \approx 0.4166\ \text{nats}. $$

This is one cell-coordinate contribution, not the dataset average in the table. The relevant selection diagnostic is the distribution of contributions across cells and repeated fits, considered alongside held-out performance and downstream stability. A coordinate with low average KL but substantial, reproducible usage in a defined subset deserves closer inspection rather than automatic removal.

Downstream Stability and a Selection Workflow

A dimension can produce a good average predictive score but unstable results across random seeds. Assess stability for the downstream task that motivates fitting the VAE, without treating stability as proof of biological validity. For example, compare nearest-neighbor sets or cluster assignments across repeated fits. Because latent coordinates can rotate or permute without changing the model’s substantive fit, direct coordinate-by-coordinate comparisons may be misleading. Comparing neighborhood structure or assignments avoids requiring identical coordinate axes.

For two fits, a simple neighborhood comparison for cell \(i\) is the Jaccard similarity, the size of the intersection of its neighbor sets divided by the size of their union. Average this over cells and pairs of fits. For cluster assignments, an adjusted Rand index can summarize agreement while adjusting for agreement expected by chance. These are stability summaries, not universal pass/fail thresholds: their meaning depends on the number of neighbors or clusters and on the downstream question.

Worked Example: Comparing Neighborhood Stability

Suppose two hypothetical fits with the same dimension are compared using three nearest neighbors for four validation cells. For cell A the neighbor sets are \(\{B,C,D\}\) and \(\{B,C,E\}\), giving Jaccard similarity \(2/4=0.50\). For cell B they are \(\{A,C,D\}\) in both fits, giving \(3/3=1.00\). For cell C the sets are \(\{A,B,D\}\) and \(\{A,B,E\}\), giving \(2/4=0.50\). For cell D they are \(\{A,B,C\}\) in both fits, giving \(3/3=1.00\).

The mean similarity is \((0.50+1.00+0.50+1.00)/4=0.75\). This indicates that, for these four cells and this neighbor definition, the average overlap across the two fits is \(75\%\) by the Jaccard measure. It does not establish that the shared neighbors are biologically meaningful. Repeat the comparison across several seeds and, ideally, compare candidate dimensions using the same cells and downstream settings.

A practical workflow is to define candidate dimensions and the target of generalization in advance; fit each candidate with repeated seeds; compare held-out predictive scores and reconstruction using the same evaluation procedure; inspect KL usage across cells and seeds; and assess stability for the planned downstream analysis. Then choose a dimension with strong enough held-out performance and adequate stability, preferring a simpler candidate when larger dimensions offer no material, reproducible improvement. If candidate scores are close, report the ambiguity rather than presenting a precise dimension as uniquely determined.

Assumptions, Diagnostics, and Limits

These comparisons are informative only if the evaluation matches the model and scientific target. Inspect whether count inputs, genes, library-size handling, and covariates are consistent across candidates. Check training convergence and replicate fits: a poorly optimized high-dimensional model may appear inferior for computational reasons, while a single lucky initialization may appear superior. For importance-sampling scores, check sensitivity to the number of draws; for all metrics, quantify variation across held-out cells and training seeds. If the validation set is small or cells are strongly grouped by donor, nominal precision based on treating every cell as independent can be misleading; use splits and uncertainty summaries that respect the sampling structure.

A held-out score can also be optimized repeatedly by trying many architectures, splits, or dimensions against the same validation set. That makes the reported validation performance optimistic for the selected model. Use validation data to make the selection and reserve a test set for a final evaluation, or use an appropriate nested evaluation strategy when the full modeling procedure itself is being assessed. Held-out performance measures prediction under the chosen split and data distribution; it does not certify causal meaning, biological truth, or generalization to populations unlike those represented.

No metric dominates in every application. Held-out likelihood evaluates probabilistic prediction but can be sensitive to likelihood specification and estimator quality. Reconstruction focuses on observed counts but can favor overly detailed fits. KL usage indicates how the fitted approximate posterior uses coordinates but is prior- and solution-dependent. Downstream stability detects sensitivity to fitting choices but stable results can still be systematically wrong. These diagnostics are most useful together, with the intended analysis determining which trade-offs matter.

  • Pitfall: choosing the smallest training loss. More latent capacity can improve fit to training cells. Correct this by comparing held-out performance and checking whether gains persist across seeds.
  • Pitfall: calling every low-KL coordinate useless. An average can hide subgroup usage, and refitting at a smaller \(K\) can reorganize the representation. Inspect per-cell and repeated-fit summaries.
  • Pitfall: treating a stable embedding as validated biology. Stability describes reproducibility under the chosen procedure, not truth. Check predictive fit and the scientific assumptions separately.
  • Pitfall: comparing scores from different data or estimators. Changes in genes, preprocessing, splits, or likelihood estimation can explain score differences. Hold these fixed for a fair comparison.
Key takeaway: Select latent dimension by balancing held-out predictive fit, reconstruction, KL usage, and downstream stability under a fair evaluation design. Lower training loss alone is not evidence that a larger latent space generalizes better.

Check Your Understanding

Answer each question, then compare with the brief solutions.

  1. A candidate model has lower training negative log likelihood but worse held-out log likelihood than a smaller model. Which is better supported for prediction, and why?
  2. For one coordinate with \(\mu_j=0\) and \(\sigma_j^2=1\), calculate its KL contribution under a standard normal prior.
  3. Two neighborhood sets each contain three cells and share two cells. What is their Jaccard similarity?
  4. Why might randomly splitting cells be unsuitable when the intended target is prediction for new donors?
  5. What does a low average KL contribution establish, and what does it not establish?

Solutions. (1) The smaller model is better supported for prediction by the stated evidence because its held-out log likelihood is better; the training improvement alone does not show generalization. (2) The contribution is \(\frac{1}{2}(0^2+1-\log 1-1)=0\) nats. (3) The union has \(3+3-2=4\) cells, so the Jaccard similarity is \(2/4=0.50\). (4) Cells from the same donor may occur in both splits, so the validation set does not assess generalization to unseen donors. (5) It indicates that the approximate posterior for that coordinate is close to the prior on average under that fitted model; it does not prove the coordinate is biologically irrelevant or unused in every subgroup.

Clinical Biostats