Hierarchical models

Week 4 — Hierarchical models

Quantitative biology and integrative omics

About this lecture

Your data almost never arrive as one flat list of independent numbers. They come grouped: several cells per animal, several reads per cell, several time points per patient. Today we learn to model that structure instead of pretending it isn’t there.

  • Biological vs technical replicates — and why confusing them (pseudoreplication) is one of the most common mistakes in the literature.
  • Three ways to handle grouped data: pool everything, pool nothing, or the middle road — partial pooling.
  • Shrinkage: group estimates are pulled toward the overall mean, more so when a group is small or noisy.
  • Random effects: a patient level and a measurement level; the same idea in lme4 and Bayesian brms/Stan syntax.
  • Why hierarchy gives you the right uncertainty, not just the right average.

Problem: Repeated samples from one patient are not independent

You measure a blood biomarker to compare treated vs control patients. But you don’t get one number per patient — you draw several samples per patient, and each sample is assayed.

  • 6 patients, roughly 5 measurements each → about 30 numbers.
  • The 5 measurements from one patient are more similar to each other than to another patient’s: same physiology, same day, same tube.

How many independent data points do you really have — 30, or 6?

The honest answer is somewhere between, and today’s model is exactly what puts a number on “somewhere between”.

Only biological replicates add to your sample size

Before any statistics, ask of every number: what is being repeated?

  • Biological replicate — an independent biological unit: a different patient, animal, or independently grown culture. Captures biological variation between units.
  • Technical replicate — the same biological unit measured again: the same blood sample split and assayed twice, the same library sequenced twice. Captures measurement / assay noise only.

Averaging two technical replicates makes your measurement of one unit more precise. It does not give you a second unit.

Note

The number that limits your ability to generalise to new patients is the number of biological replicates, not the total count of measurements.

Pseudoreplication makes results look too certain

Pseudoreplication = analysing technical replicates (or repeated measures within a unit) as if they were independent biological replicates.

Consequences:

  • The effective sample size is overstated (you claim 30 when you have nearer 6).
  • Standard errors come out too small, confidence intervals too narrow.
  • p-values are too optimistic → inflated false-positive rate.

A classic tell in a paper: “n = 240 cells from 3 animals, p < 0.001.” The relevant n for a between-animal claim is 3.

Partial pooling sits between pooling all and none

Say each patient has their own true mean and you want to estimate it.

  1. Complete pooling — ignore patients; one grand mean \mu for everyone. Throws away real between-patient variation.
  2. No pooling — a separate, independent mean for each patient, estimated from that patient’s data alone. Noisy for patients with few measurements; can’t borrow strength.
  3. Partial pooling — each patient’s estimate is a compromise between the patient’s own mean and the grand mean. The hierarchical model.

Partial pooling is the “have your cake and eat it”: patient-specific, but stabilised by the group.

Small groups are pulled most toward the mean

The partial-pooling estimate for a patient is a weighted average of its own mean and the grand mean:

\text{estimate} \;=\; w \cdot \text{own mean} \;+\; (1-w) \cdot \text{grand mean}

The weight w (between 0 and 1) says how much the patient’s own data is worth compared with the crowd:

w \;=\; \frac{n/\sigma^2}{\,n/\sigma^2 + 1/\tau^2\,}

  • n/\sigma^2 — worth of the patient’s own data: more measurements (n), less noise (\sigma^2) → worth more.
  • 1/\tau^2 — worth of the crowd: the more alike patients are (small spread \tau^2) → worth more.

Example: n = 4, \sigma^2 = 8, \tau^2 = 2 gives w = 0.5/(0.5+0.5) = 0.5; own mean 10, grand mean 6 → estimate 8.

The pull toward the grand mean is shrinkage: strongest when a patient has few measurements or patients are truly alike (\tau^2 small).

Shrinkage pulls noisy estimates toward the mean

Picture each patient’s raw mean on the left and its shrunken estimate on the right:

  • Points move toward the grand mean, never past it.
  • Patients with few / noisy measurements move the most.
  • Patients with many measurements barely move — they’ve earned their position.

This is regularisation: extreme group estimates, which are often extreme only by chance, are reined in. lfcShrink in Bulk RNA-seq with DESeq2 did the same to fold changes: low-count genes moved most towards 0.

Try it: how much to shrink

Patient offsets share one spread, learned from the data

Each measurement = overall mean + patient level + measurement level:

  • Overall mean — one number for everyone (a fixed effect).
  • Patient level — how far this patient sits from the overall mean (a random effect). Patients scatter with spread \tau (between patients).
  • Measurement level — noise around the patient’s own value, with spread \sigma (within a patient).

The move that makes it hierarchical: the patient offsets are not free numbers — they come from one shared spread \tau, which is estimated from the data.

The ICC tells how much the grouping matters

The two variances answer “how correlated are two measurements from the same patient?”

\text{ICC} \;=\; \frac{\tau^2}{\tau^2 + \sigma^2}

  • ICC near 1 — patients differ a lot, measurements within a patient are tight. Grouping matters enormously; your effective sample size is close to the number of patients.
  • ICC near 0 — patients are basically interchangeable; grouping barely matters and complete pooling is nearly fine.

The intraclass correlation is the single number that tells you how much your hierarchy matters.

Try it: counting cells vs counting patients

1000 simulated studies where treatment does nothing: how often does each analysis cry “significant”?

In R: the model formula

The grouping is written with (1 | patient) — read it as “let the intercept vary by patient.”

Frequentist multilevel fit with lme4:

library(lme4)

# random intercept per patient, plus a treatment fixed effect
set.seed(1)
d <- data.frame(patient = factor(rep(seq_len(40), each = 4)),
                treatment = rep(c("control", "control", "treated", "treated"), 40))
patient_effect <- rnorm(40, sd = sqrt(2))
d$biomarker <- 6 + 1.5 * (d$treatment == "treated") +
  patient_effect[as.integer(d$patient)] + rnorm(nrow(d), sd = sqrt(8))
fit <- lmer(biomarker ~ treatment + (1 | patient), data = d)

summary(fit)     # fixed effects + variance of the random intercept (tau^2) and residual (sigma^2)
ranef(fit)       # the shrunken per-patient offsets
  • treatment — a fixed effect (the population-level question).
  • (1 | patient) — a random intercept: one offset per patient, all from one shared spread \tau.

A random effect is a prior learned from the data

The same formula, now fully Bayesian — priors on every parameter, a posterior for each:

library(brms)

fit <- brm(biomarker ~ treatment + (1 | patient),
           data = d,
           family = gaussian())      # brms writes and runs the Stan model for you

summary(fit)                          # posterior means + credible intervals

The hierarchy is Bayesian at heart: “patient offsets scatter with spread \tau” is a prior on the patient offsets. It is an adaptive prior: its width \tau is not fixed in advance but learned from the data, and \tau gets a (vaguer) prior of its own, a hyperprior.

Reading it off correctly

Whichever engine you use, the workflow is the same:

  • Report the fixed effect (e.g. treatment difference) with its interval — this is your scientific answer.
  • Report the variance components: \hat\tau (between patients) and \hat\sigma (within patients); their ratio gives the ICC.
  • Use the shrunken per-group estimates (ranef / posterior) when you need patient-level values, never the raw per-patient means.

A one-line sanity check: if \hat\tau \approx 0 the data say patients are alike (near complete pooling); if \hat\tau \gg \hat\sigma grouping dominates.

Pitfalls and good practice

  • Too few groups. You cannot estimate \tau from 2–3 patients; the between-group variance is barely identified. Rule of thumb: aim for more groups, not just more measurements per group.
  • Crossed vs nested grouping. Cells within patients within hospitals nest; but batch and patient may cross. Write the grouping to match the design.
  • Don’t model the treatment as random if it’s the effect you care about and has few, deliberately chosen levels — that’s a fixed effect.
  • Balance isn’t required. Unequal numbers of measurements per patient are fine and handled automatically — that’s a strength over averaging.

Optional: the maths behind random effects

For measurement j in patient i:

y_{ij} \;=\; \mu \;+\; b_i \;+\; \varepsilon_{ij}, \qquad b_i \sim \mathcal N(0,\tau^2), \quad \varepsilon_{ij} \sim \mathcal N(0,\sigma^2)

  • \mu — overall mean (fixed effect); b_i — patient level (random effect); \varepsilon_{ij} — measurement level.
  • b_i \sim \mathcal N(0,\tau^2) is the prior on the patient offsets; the weight w of partial pooling follows from it.
  • A flat model treats all N measurements as independent, so its standard error shrinks like 1/\sqrt{N}; with clustering, N cells are worth only about N / (1 + (m-1)\,\text{ICC}) independent samples, for m cells per patient.

Summary

Concept Key fact
Biological replicate independent unit; sets your power to generalise
Technical replicate same unit remeasured; reduces measurement noise only
Pseudoreplication counting technical reps as biological → false confidence
Complete / no / partial pooling ignore groups / separate per group / compromise
Shrinkage group estimates pulled toward the grand mean, most for small groups
Random effect a patient’s offset from the overall mean, drawn from a shared spread \tau
Two variances \sigma^2 within, \tau^2 between; \text{ICC}=\tau^2/(\tau^2+\sigma^2)
Correct uncertainty error bars reflect number of groups, not measurements (demo: 41% vs 6% false alarms)
R lmer(y ~ x + (1\|group)); Bayesian brm(...) — same formula
Bayesian view a random effect is an adaptive prior on group means