Further reading: not part of the course. This material is not included in the course, but it is relevant if you want to learn more about the topic.

A worked Bayesian case study

Further reading — A worked biological case

Quantitative biology and integrative omics

About this lecture

Every earlier unit in this block built one piece of a Bayesian model. Today we assemble all of them on a single, realistic biological dataset and take it end to end.

  • Turn a biological question into a generative model: error model + covariates + hierarchy + priors.
  • Recognise why count data across patients and treatments needs a negative-binomial error model, not a Gaussian.
  • Read a fitted posterior: point estimate, credible interval, and a direct probability statement about a treatment effect.
  • Check the model with posterior predictive checks — the Bayesian version of “does my model actually reproduce my data?”
  • See the whole workflow as STATIC R code (via brms, which compiles to Stan). Nothing is executed here — this is the map, not the drive.

The biological question

A small immunology trial. For each blood sample we count activated T cells (a discrete count) by flow cytometry or from single-cell data.

  • 12 patients, each sampled under placebo and under drug (paired design).
  • Question: does the drug change the number of activated T cells, and by how much?
  • Nuisance structure we must respect: patients differ in baseline immune activity (age matters), samples differ in how many total cells were assayed (exposure), and repeated samples from one patient are not independent.

A naive t.test(count ~ treatment) ignores all three. We will build a model that handles them together.

What the data look like

One row per sample. Counts are small, integer, and right-skewed — the hallmark of biological count data.

head(dat)
#>   patient treatment   age  count  n_cells   log_exp
#> 1     P01   placebo    34     18    50218    10.824
#> 2     P01      drug    34     41    48903    10.797
#> 3     P02   placebo    51      7    39044    10.572
#> 4     P02      drug    51     12    52771    10.874
#> 5     P03   placebo    29     55    61233    11.022
#> 6     P03      drug    29     96    60918    11.017

str(dat)
#> 'data.frame': 24 obs. of 6 variables:
#>  $ patient  : Factor w/ 12 levels "P01",...
#>  $ treatment: Factor w/ 2 levels "placebo","drug"
#>  $ age      : num  34 51 29 ...
#>  $ count    : int  18 41 7 12 55 96 ...
#>  $ n_cells  : int  50218 48903 ...
#>  $ log_exp  : num  10.82 10.80 ...   # = log(n_cells), the exposure offset

Counts need a count model, not a Gaussian

A lm(count ~ treatment) assumes the response is continuous, symmetric, and constant-variance. Counts violate all three:

  • counts are non-negative integers — a Gaussian puts probability on -3.7 cells;
  • their spread grows with the mean — big-count samples are noisier in absolute terms;
  • they are often overdispersed: variance > mean, more than Poisson allows.

We met these facts in the count-distributions unit (Poisson and the negative binomial). The fix is to choose an error model that generates counts, and let the mean depend on covariates through a log link.

Building block 1 — the error model

Model each count with a negative binomial, the overdispersed cousin of the Poisson:

y_i \sim \text{NegBinomial}(\mu_i, \phi), \qquad \operatorname{Var}(y_i) = \mu_i + \frac{\mu_i^2}{\phi}.

  • \mu_i is the expected count; \phi (the shape / dispersion) controls the extra spread.
  • As \phi \to \infty the extra term vanishes and we recover the Poisson (\operatorname{Var}=\mu).
  • Small \phi = strong overdispersion: biological heterogeneity between samples beyond pure counting noise.

Letting the data estimate \phi means we test whether Poisson would have been enough, rather than assuming it.

Building block 2 — covariates and exposure

Let the log of the mean be a linear predictor — the same additive structure as a linear model, on the log scale:

\log \mu_i = \underbrace{\log(\text{n\_cells}_i)}_{\text{offset (exposure)}} + \alpha + \beta_{\text{drug}}\,x_i + \beta_{\text{age}}\,(\text{age}_i - \overline{\text{age}})

  • The offset (coefficient fixed at 1) turns counts into rates per cell assayed — the standard fix for library size / sequencing depth.
  • x_i = 1 for drug, 0 for placebo, so \beta_{\text{drug}} is the drug effect on the log scale.
  • e^{\beta_{\text{drug}}} is a rate ratio: a multiplicative fold-change in activated T cells. Centring age makes \alpha interpretable at the mean age.

Building block 3 — hierarchy

Two samples from the same patient share that patient’s biology. Give each patient a random intercept:

\log \mu_i = \dots + u_{\text{patient}[i]}, \qquad u_p \sim \text{Normal}(0,\ \sigma_{\text{patient}}).

  • u_p shifts a patient up or down; \sigma_{\text{patient}} is the between-patient spread (the biological replicate variance).
  • The remaining scatter within a patient is technical / residual — captured by \phi.
  • Hierarchy gives partial pooling: noisy patients are shrunk toward the group, borrowing strength across the cohort.

This is the hierarchical-models unit (biological vs technical replicates) applied to our cohort.

Try it: shrinking the patients

A Gaussian sketch on the log scale: a patient with c activated cells counted has a raw log-rate with noise variance \approx 1/c, so its weight is w_p = c/(c + 1/\sigma_{\text{patient}}^2).

Building block 4 — priors

Bayesian fitting needs a prior on every parameter. We use weakly informative priors on the log scale:

priors <- c(
  prior(normal(0, 2),   class = "Intercept"),  # baseline log-rate, broad
  prior(normal(0, 1),   class = "b"),           # each effect: fold-changes mostly within ~e^2
  prior(exponential(1), class = "sd"),          # between-patient SD, positive, modest
  prior(gamma(0.01, 0.01), class = "shape")     # NB dispersion phi, very diffuse
)
  • normal(0, 1) on a log-scale coefficient says: effects near zero are most plausible, but a rate ratio of e^{\pm 2}\approx 0.14–7.4 is easily allowed. Sceptical, not restrictive.
  • Priors here play the role that regularisation will play in the penalized-models block: they tame the fit without dictating the answer.

The full model is a recipe for generating each count

The generative story, read top to bottom — how a count is born:

\begin{aligned} y_i &\sim \text{NegBinomial}(\mu_i,\ \phi) &&\text{(error model)}\\ \log \mu_i &= \log(\text{n\_cells}_i) + \alpha + \beta_{\text{drug}} x_i + \beta_{\text{age}}\,\widetilde{\text{age}}_i + u_{\text{patient}[i]} &&\text{(covariates + hierarchy)}\\ u_p &\sim \text{Normal}(0,\ \sigma_{\text{patient}}) &&\text{(between-patient)}\\ \alpha \sim \text{N}(0,2),\ \ \beta &\sim \text{N}(0,1),\ \ \sigma_{\text{patient}} \sim \text{Exp}(1),\ \ \phi \sim \text{Gamma}(0.01,0.01) &&\text{(priors)} \end{aligned}

Bayes’ theorem ties it together: \;p(\text{parameters}\mid\text{data}) \propto \underbrace{p(\text{data}\mid\text{parameters})}_{\text{likelihood (NB)}}\;\underbrace{p(\text{parameters})}_{\text{priors}}.

Fitting it in R

One brms call expresses the entire model; it writes and compiles a Stan program under the hood (the R-STAN unit).

library(brms)

# Centre age before using it in the formula; this makes the intercept the
# baseline log-rate at the average age.
dat$age_c <- dat$age - mean(dat$age)

fit <- brm(
  count ~ treatment + age_c + offset(log_exp) + (1 | patient),
  data    = dat,
  family  = negbinomial(),        # log link + dispersion phi
  prior   = priors,               # from the previous slide
  chains  = 4, iter = 2000, warmup = 1000,
  cores   = 4, seed = 1
)
  • treatment + age_c are the fixed effects; offset(log_exp) is the exposure term.
  • (1 | patient) is the per-patient random intercept — the hierarchy.
  • 4 chains of MCMC explore the posterior; warmup samples are discarded.

Check that the sampler worked before reading results

Before interpreting anything, check that the MCMC actually converged. Diagnostics come before conclusions.

summary(fit)
#> Group-Level Effects (patient):  sd(Intercept)  ...
#> Population-Level Effects:
#>                 Estimate  Est.Error  l-95% CI  u-95% CI  Rhat  Bulk_ESS  Tail_ESS
#> Intercept        -7.31      0.14      -7.59     -7.04    1.00     2600      2900
#> treatmentdrug     0.47      0.09       0.29      0.65    1.00     4100      3200
#> age_c            -0.012     0.010     -0.031     0.008   1.00     3500      3000
  • Rhat \approx 1.00 (want < 1.01): the chains agree — they mixed.
  • ESS in the thousands: enough effectively-independent draws to trust the summaries.
  • Also check 0 divergent transitions (a Stan-specific warning); divergences mean the geometry was too hard and the fit is untrustworthy.

Reading the posterior

The treatment coefficient lives on the log scale; exponentiate for the biological quantity — a rate ratio.

post <- as_draws_df(fit)

# Rate ratio for the drug: multiplicative fold-change in activated T cells
exp(quantile(post$b_treatmentdrug, c(0.025, 0.5, 0.975)))
#>     2.5%      50%    97.5%
#>    1.34     1.60     1.92

# Direct probability the drug increases the count
mean(post$b_treatmentdrug > 0)
#> [1] 0.9998
  • Point estimate: the drug multiplies activated T cells by \approx 1.6.
  • 95% credible interval [1.34,\ 1.92]: a plausible range for the true effect — a statement about the parameter, unlike a confidence interval.
  • P(\beta_{\text{drug}} > 0 \mid \text{data}) \approx 0.9998: an answer to the actual question, no null hypothesis needed.

Check the model: does it simulate data like ours?

A converged sampler only means we fitted the model we wrote. Is that model any good? Posterior predictive checking asks: if the model is right, would it generate data that look like ours?

y^{\text{rep}} \sim p(y^{\text{rep}} \mid \text{data}) = \int p(y^{\text{rep}}\mid\theta)\,p(\theta\mid\text{data})\,d\theta

  • Draw parameters from the posterior, then simulate new datasets y^{\text{rep}} from the error model.
  • Compare those simulated datasets to the real data. Systematic mismatch = the model is missing something.

This is the Bayesian analogue of residual plots — but it checks the whole generative story, counts and all.

Model checking — what to plot

# Overlay: distribution of observed counts vs many simulated datasets
pp_check(fit, ndraws = 100)

# Targeted checks on summary statistics the model must reproduce
pp_check(fit, type = "stat", stat = "mean")
pp_check(fit, type = "stat", stat = "max")                 # is the tail right?
pp_check(fit, type = "stat", stat = function(y) mean(y == 0))  # zero-inflation?
  • Density overlay: the observed count histogram should sit inside the cloud of simulated ones.
  • Test statistics: if the observed max or proportion of zeros falls in the tail of the simulated distribution, the error model is wrong — e.g. real data are more overdispersed or zero-inflated than a negative binomial allows.
  • A failed check sends you back to the model (a different error model, an extra covariate), not to the data.

Bayes makes uncertainty and assumptions explicit

Same data, two philosophies — and this block chose the Bayesian one for concrete reasons.

Question Frequentist tool Bayesian answer here
Effect size coefficient \pm SE from a GLM full posterior for \beta_{\text{drug}}
Uncertainty 95% confidence interval 95% credible interval (a real probability)
“Is there an effect?” p-value vs a null P(\beta_{\text{drug}}>0\mid\text{data}) directly
Patient structure random effects via glmer hierarchy with partial pooling
Prior knowledge none (or ad-hoc) encoded, and dominated by data when data are plentiful
Model check residual diagnostics posterior predictive checks

Neither is “correct”; the Bayesian workflow makes the uncertainty and the assumptions explicit, which suits small, structured biological datasets.

Summary

Step What we did
Question drug effect on activated T-cell counts, paired across 12 patients
Error model negative binomial — counts, mean-variance link, overdispersion \phi
Covariates log link; offset for exposure; e^{\beta} = rate ratio
Hierarchy per-patient random intercept → partial pooling of replicates
Priors weakly informative on the log scale (regularisation, not dictation)
Fit one brms formula → Stan → MCMC (the R-STAN engine)
Trust it Rhat, ESS, divergences before interpreting
Read it posterior, credible interval, P(\text{effect}>0\mid\text{data})
Check it posterior predictive checks on distribution, max, zeros

You now have the full arc: question → generative model → fit → posterior → check. That arc, not any one formula, is the deliverable of this block.