Tutorials › Statistical Methods for Single-Cell RNA Sequencing › Choosing the Number of Topics

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

Choosing the Number of Topics

Use comparable held-out scores alongside redundancy and coherence diagnostics to choose a topic count without treating predictive improvement as the only goal.

Advanced 12 min read

What You'll Learn

  • Define held-out predictive scores for topic-model count data and compare them on the same scale.
  • Distinguish document-completion prediction from prediction for entirely new cells.
  • Calculate gene-pair NPMI coherence and handle undefined or excluded pairs explicitly.
  • Use topic similarity as a diagnostic for potentially redundant topics.
  • Make a transparent topic-count choice when predictive fit improves but topics become redundant.

Why Topic Count Is a Modeling Choice

A topic model represents each cell as a mixture of gene programs, while each program assigns weights to genes. Choosing the number of topics, \(K\), therefore determines how many programs the model can use to describe variation in the count matrix. Too few topics can force distinct patterns into the same program; too many can split one coherent pattern into near-duplicates or fit details that do not predict well beyond the data used for fitting.

No single statistic identifies a universally correct \(K\). Held-out predictive fit asks how well a fitted model predicts counts not used to estimate it. Coherence asks whether genes grouped in a topic tend to co-occur in cells. Redundancy asks whether different topics appear to represent nearly the same gene pattern. These address different properties, so selection should compare them rather than collapse them uncritically into one score.

Definition: A topic count is the fixed number \(K\) of gene programs represented by a fitted topic model. Held-out predictive fit is the model's predictive probability, or a corresponding log score, for observations reserved from fitting. Topic coherence summarizes whether genes assigned high weight within a topic tend to co-occur. Topic redundancy describes substantial similarity between distinct topics.

Constructing a Fair Predictive Comparison

For count data, a useful evaluation is document completion: divide each cell's observed counts into context counts used to infer that cell's topic mixture, and target counts reserved for scoring. The topic distributions are fitted using training cells. For a held-out cell, the model uses its context counts to learn about its mixture, then evaluates the conditional predictive probability of its target counts. This assesses whether the topics learned in training can predict additional counts in a cell with partial information.

Let \(x_c\) denote context counts and \(y_c\) target counts for held-out cell \(c\). The predictive score for \(K\) topics can be written as a sum of conditional log probabilities. If there are \(M\) target count units across the held-out cells, report the score per target count unit so comparisons remain interpretable across splits:

$$ S_K = \frac{1}{M}\sum_c \log p(y_c \mid x_c,\text{training data},K). $$

A larger (less negative) \(S_K\) is better under this log-score convention. The conditional probability generally averages over uncertainty in the held-out cell's topic mixture given its context counts; using the target counts to infer the mixture before scoring those same target counts would give an overly optimistic evaluation. In practice, the probability may be approximated by an inference procedure, so the approximation method and computation should be kept comparable across candidate values of \(K\).

A fair comparison uses the same training cells, held-out cells, gene set, context/target split, and scoring convention for every \(K\). If the goal is prediction for new biological samples, the split should respect that goal: holding out cells from samples already represented in training mainly evaluates prediction within those samples, not generalization to unseen samples. Counts, library-size handling, and preprocessing must also be defined consistently.

Worked Example: Comparing Held-Out Log Scores

Suppose two hypothetical models are evaluated on the same document-completion split, with \(M=10{,}000\) held-out target count units. Their total conditional log scores, using natural logarithms, are \(-14{,}500\) for \(K=4\) and \(-13{,}800\) for \(K=6\).

The per-count scores are

$$ S_4 = \frac{-14{,}500}{10{,}000}=-1.45,\qquad S_6 = \frac{-13{,}800}{10{,}000}=-1.38. $$

Thus, \(K=6\) improves the held-out score by \(-1.38-(-1.45)=0.07\) nats per target count unit. If expressed as perplexity, defined here as \(\exp(-S_K)\), the values are approximately \(\exp(1.45)=4.263\) and \(\exp(1.38)=3.975\), respectively; lower perplexity corresponds to the higher log score. This is evidence that \(K=6\) predicts this held-out split better, not proof that it gives the most useful or biologically distinct programs.

Coherence and Redundancy as Complementary Diagnostics

A common coherence measure uses normalized pointwise mutual information (NPMI) for pairs among a topic's top-weighted genes. Define \(p(g)\) as the fraction of cells in a chosen reference set in which gene \(g\) is detected, and \(p(g,h)\) as the fraction in which both genes are detected. For a pair with \(0<p(g,h)<1\), define

$$ \operatorname{NPMI}(g,h) = \frac{\log\!\left(\frac{p(g,h)}{p(g)p(h)}\right)} {-\log p(g,h)}. $$

For pairs in this defined range, NPMI is between \(-1\) and \(1\). Positive values indicate co-detection more often than expected under independence, zero is the independence benchmark, and negative values indicate less co-detection than expected. These interpretations apply to the detection events in the selected reference cells; they do not establish a regulatory relationship or a causal interaction.

The boundary cases require explicit handling. If \(p(g,h)=0\), the logarithm is undefined; if \(p(g,h)=1\), the denominator is zero and, because both marginal probabilities are then 1, the numerator is also zero. A reproducible convention is to exclude both types of pairs from the NPMI average and report how many eligible pairs remain. Do not assign them an ordinary NPMI value. If no eligible pairs remain, the topic's average NPMI is undefined rather than zero. Results can also depend on the number of top genes chosen and on the reference cells, so those choices should be fixed across candidate topic counts.

Redundancy can be assessed by comparing topic gene-weight vectors. For example, cosine similarity between two nonzero weight vectors \(w_k\) and \(w_l\) is their dot product divided by the product of their Euclidean lengths. Values close to 1 indicate similar directions in gene-weight space. Similarity is a diagnostic, not a hypothesis test: a threshold such as 0.85 is a practical flag chosen for a particular analysis, not a universal boundary between distinct and redundant biology.

Worked Example: Calculating a Gene-Pair NPMI

In a hypothetical reference set of 1,000 cells, gene \(g\) is detected in 200 cells, gene \(h\) in 150 cells, and both are detected in 60 cells. Thus \(p(g)=0.20\), \(p(h)=0.15\), and \(p(g,h)=0.06\). The pair is eligible because \(0<0.06<1\).

Under independence, the expected joint detection probability would be \(0.20(0.15)=0.03\). Therefore,

$$ \operatorname{NPMI}(g,h) = \frac{\log(0.06/0.03)}{-\log(0.06)} = \frac{\log 2}{-\log(0.06)} \approx \frac{0.6931}{2.8134} =0.2464. $$

The positive value indicates more co-detection than the independence benchmark in this reference set. If instead all 1,000 cells detected both genes, then \(p(g,h)=1\) and the formula would have a zero denominator; that pair must be excluded under the stated convention, not reported as an NPMI of zero or one.

A Selection Rule With Multiple Criteria

The choice should be made using a declared comparison rule, not by searching for a single magically decisive number. One practical approach is to identify a range of topic counts whose predictive scores are close to the best score, then prefer a simpler model within that range if its topics are at least as coherent and less redundant. “Close” should be defined in advance in the scale being used—for example, a tolerance in nats per held-out count unit—and treated as a practical decision threshold, not a significance test.

The reasoning behind held-out scoring is straightforward. Fitting can adapt a model to training observations, so a training score alone does not measure how well the fitted model predicts unused observations. A held-out score evaluates predictions on data not used to estimate the topic distributions. Its average estimates predictive performance for observations generated under a comparable sampling and preprocessing scheme. The score does not directly reward interpretability, and it can favor added topics when they improve prediction, even if the new topics are difficult to distinguish from existing ones.

1
Set the evaluation design.
Fix the gene set, cell-level split, context/target construction, and scoring procedure before comparing \(K\).
2
Compare predictive scores.
Calculate held-out log score per target count unit for each candidate \(K\). Check that all scores use the same observations and scale.
3
Inspect coherence and redundancy.
Summarize coherence with a fixed rule for top genes and eligible pairs, and compare topic-weight vectors using a stated similarity diagnostic.
4
Choose and explain a trade-off.
Use a declared predictive tolerance and favor the smaller, clearer model when additional topics bring little predictive benefit and substantial redundancy.

Worked Example: Predictive Improvement With Redundant Topics

Consider a hypothetical analysis with the following per-target-count held-out scores, mean topic coherence summaries, and numbers of redundant topic pairs. Redundancy is flagged here when cosine similarity exceeds a preselected threshold of 0.85. Coherence is the average eligible NPMI over each topic's selected gene pairs, then averaged across topics.

Topics \(K\)Held-out score (nats/count)Mean coherenceRedundant pairs
3-1.520.180
4-1.450.240
5-1.420.231
6-1.410.202

The best predictive score is \(-1.41\) at \(K=6\). Suppose the analysis plan defined a practical tolerance of 0.04 nats per target count unit from the best score. The score difference for \(K=4\) is \(-1.41-(-1.45)=0.04\), so \(K=4\) is within that tolerance. \(K=3\) is not: its difference is \(-1.41-(-1.52)=0.11\). Although \(K=5\) improves on \(K=4\) by 0.03, it introduces a redundant pair, and \(K=6\) improves by just 0.01 over \(K=5\) while having two redundant pairs and lower mean coherence.

If inspection confirms that the pair at \(K=5\) has cosine similarity 0.91 and largely overlapping high-weight genes, the evidence supports choosing \(K=4\) under this declared rule: it is within the predictive tolerance, has the highest coherence summary in the table, and has no flagged redundant pairs. This does not prove that four is the uniquely true number of biological programs. It makes a transparent compromise between predictive fit and topic distinctness for this analysis.

Assumptions, Diagnostics, and Alternatives

The comparison is meaningful only if candidate models are evaluated on genuinely comparable data and with a consistent likelihood and inference procedure. The cells used for evaluation should represent the prediction target, and the held-out counts must not have been used to fit the topic distributions. Since stochastic inference and finite evaluation samples can make scores vary, small score differences should not be interpreted as decisive without checking that they are practically meaningful and not driven by a few cells or genes.

Several diagnostics help detect a misleading selection. Confirm that each \(K\) was scored on the same target counts and with the same normalization or exposure treatment. Examine whether conclusions change substantially under reasonable alternative held-out splits or choices of top genes. Record the number of NPMI pairs excluded because \(p(g,h)=0\) or \(p(g,h)=1\); a mean based on very few eligible pairs is less informative. Inspect highly similar topic pairs directly, since a similarity threshold can flag overlap but cannot decide whether two programs are scientifically distinct.

Document completion is not the only predictive design. One may instead hold out whole cells and evaluate their predictive probability under the model without using their counts to infer their cell-specific mixture. That design targets new-cell prediction but can be more demanding and differs from completion, so scores from the two designs should not be compared as if they were the same quantity. Training likelihood is a weaker selection tool: it usually improves as flexibility is added and therefore does not by itself reveal whether added topics generalize. Coherence alone is also insufficient; common, broadly detected genes can co-occur for reasons unrelated to a specific program, while rare genes may produce unstable pair frequencies.

Common pitfall: “The model with the largest \(K\) has the best held-out score, so it must be the best topic model.” A better held-out score supports better prediction under the chosen evaluation design, not necessarily more distinct or interpretable programs. Compare the size of the predictive gain with coherence and redundancy, and state the trade-off behind the selected \(K\).

Check Your Understanding

Answer each question, then compare with the solutions below.

  1. Two models have held-out scores of \(-1.60\) and \(-1.54\) nats per target count unit on the same split. Which has better predictive fit, and by how much?
  2. Why should target counts not be used to infer a cell's topic mixture and then scored as if they were unused?
  3. For \(p(g)=0.10\), \(p(h)=0.20\), and \(p(g,h)=0.04\), calculate the NPMI to three significant figures.
  4. What should be done if a gene pair has \(p(g,h)=1\) under the NPMI definition used here?
  5. A larger \(K\) slightly improves held-out score but adds highly similar topics and has lower coherence. Give one defensible basis for choosing the smaller \(K\).

Solutions. (1) The score \(-1.54\) is better because it is larger; the improvement is \(-1.54-(-1.60)=0.06\) nats per target count unit. (2) That would let the observations being scored inform the fitted cell mixture, making the predictive assessment optimistic rather than a genuine prediction of held-out counts. (3) The independence joint probability is \(0.10(0.20)=0.02\), so \(\operatorname{NPMI}=\log(0.04/0.02)/[-\log(0.04)]=0.6931/3.2189\approx0.215\). The pair is eligible because \(0<0.04<1\). (4) Exclude it and report the exclusion convention; the formula is undefined because both numerator and denominator are zero. (5) If the smaller model is within a predeclared practical tolerance of the best predictive score, choosing it can be justified by its greater distinctness and coherence. This is a transparent trade-off, not proof that the smaller model is the uniquely correct one.

Clinical Biostats