Exercise: introduction to R-STAN
Goal
By the end of this exercise you should be able to:
- name the three essential Stan blocks (
data,parameters,model) and say what each is for, - read a Stan model and identify the prior and the likelihood,
- match an R data list to a model’s
datablock, - write a small complete Stan model for a new biological problem by hand,
- run a model from R with
rstan(in principle — the code is illustrative), and summarise the draws, - read a
print(fit)table: the posterior mean, a credible interval, and theRhat/n_effdiagnostics, - recognise when a fit should not be trusted.
Background
A Bayesian model combines a prior with a likelihood to give a posterior:
\[p(\theta \mid y) \;\propto\; p(y \mid \theta)\,p(\theta).\]
Stan describes such models in three blocks and then samples the posterior:
data— the knowns you pass in from R (counts, sample sizes, predictors), each with a type (int,real) and optional constraints (<lower=0>).parameters— the unknowns you want to learn; the posterior is a distribution over these.model—~(“distributed as”) statements giving the prior on each parameter and the likelihood of the data.
The running example from the lecture — 13 of 20 cells express a marker — is:
// gene_marker.stan
data {
int<lower=0> N; // cells assayed
int<lower=0> y; // cells expressing the marker
}
parameters {
real<lower=0, upper=1> theta; // fraction expressing
}
model {
theta ~ beta(2, 2); // prior
y ~ binomial(N, theta); // likelihood
}You run it from R by passing a named list whose keys match the data block, then summarise the returned draws:
library(rstan)
stan_data <- list(N = 20, y = 13)
fit <- stan(file = "gene_marker.stan", data = stan_data,
chains = 4, iter = 2000, seed = 1)
print(fit, pars = "theta")The output is thousands of samples of theta. The posterior mean is mean(draws); a 95% credible interval is the 2.5% and 97.5% quantiles of the draws. Always check Rhat (\(\approx 1\), want \(< 1.01\)) and n_eff (bigger is better) before reading the means.
By hand
B1. For each scenario, state what goes in the data block and what goes in the parameters block. (Types and names, not full code.)
- You count reads mapping to a gene in one RNA-seq sample and want the underlying expression rate \(\lambda\).
- You measure a continuous phenotype in \(n\) mice and want its mean \(\mu\) and standard deviation \(\sigma\).
B2. In the gene_marker.stan model above, point to the exact line that is the prior and the exact line that is the likelihood. In one sentence each, say what they encode.
B3. A colleague passes this data list to the gene_marker.stan model:
stan_data <- list(n = 20, successes = 13)Stan errors. Why? Give the corrected list.
B4. Fill in the three blanks so this becomes a valid model for a single Poisson count \(y\) with rate \(\lambda\) (a gene’s read count with an unknown expression rate):
data {
int<lower=0> y; // observed read count
}
parameters {
real<______> lambda; // (1) constraint: a rate cannot be negative
}
model {
lambda ~ ______; // (2) a prior on lambda (name any reasonable one)
y ~ ______; // (3) the likelihood for a Poisson count
}B5. You fit a model and print(fit) shows:
mean se_mean sd 2.5% 50% 97.5% n_eff Rhat
lambda 8.10 0.02 0.55 7.05 8.08 9.22 980 1.00
- What is the posterior mean of \(\lambda\)?
- Write down a 95% credible interval and state, in words, what it means.
- Is this fit trustworthy? Which two numbers did you check?
B6. A different fit reports Rhat = 1.18 and n_eff = 32 for its key parameter, even though the posterior mean “looks reasonable”. Should you report the posterior mean? What would you do instead?
B7. (concept) The lecture said MCMC returns draws rather than a formula for the posterior. If you have 4000 draws of \(\theta\) stored in a vector draws, write (in words or R) how you would obtain: (a) the posterior mean, (b) the 95% credible interval, (c) the posterior probability that \(\theta > 0.5\).
Explore
Stan’s sampler is a black box; this demo opens a simple version of it. The posterior here has two parameters: intercept \(a\) (expression at age 50) and slope \(b\) (change per 10 years) of a small regression of gene expression on age, the example of the next Bayesian unit. The orange ellipses and curves show the true posterior, which you would not know in a real problem. The sampler is random-walk Metropolis: from the current point, propose a random jump of about “step size”; if the posterior is higher there, move; if it is lower, move only with probability (new posterior / old posterior); otherwise stay and record the current point again. Stan uses a smarter sampler (HMC/NUTS), but its output is read the same way: chains, warm-up, trace plots, Rhat.
E1. Press Step about ten times and watch the four chains. What happens when a jump is rejected (red cross)? Why must the sampler record the old point again instead of simply trying another jump?
E2. Load “tiny steps (0.02)” and press Run. What is the acceptance rate? Do the four chains meet before the warm-up ends? Read R-hat and compare the histograms with the orange curves. Why is a very high acceptance rate not a good sign?
E3. Load “huge steps (3)” and run it. What is the acceptance rate now, and what do the trace plots look like? Relate this to a low n_eff.
E4. Load “good steps (0.4)” and run it. Describe the traces after warm-up, the acceptance rate and R-hat. Then drag one start point (big circle) to the edge of the plot, even farther from the posterior, and run again: which part of the run absorbs the long walk in, and why is it discarded?
E1. A rejected chain does not move: the trace stays flat for that iteration and the same \((a, b)\) is stored again. Repeating the point is what makes the draws proportional to the posterior: high-posterior points are hard to leave, so they are recorded many times, while low-posterior points are left quickly. If rejected jumps were simply retried, every visited point would count once and the histogram would no longer match the posterior.
E2. About 90% of the jumps are accepted, but each is tiny, so the chains crawl. After 1000 iterations they are still on their way in from the corners and have not met; R-hat for \(a\) is about 3.6 (far above 1.01, “chains disagree”), and the histograms are lumpy and too wide compared with the orange curves. Nearly every jump is accepted because nearly every jump is too small to change the posterior much; the chain explores very slowly.
E3. Only about 1% of the jumps are accepted: almost every proposal lands far out in the tails, where the posterior is tiny. The traces are flat staircases, each chain often sitting on the same value for a hundred iterations or more, and the post-warm-up draws contain only about a dozen distinct values. Thousands of draws carry the information of a handful of independent ones, which is exactly what a low n_eff reports; R-hat (about 1.4) also flags the problem.
E4. About 30% of the jumps are accepted. After warm-up the traces of the four chains overlap like “fuzzy caterpillars” around the same level, the histograms follow the orange curves, and R-hat is about 1.00–1.01 (“chains agree”). A start far away just makes the walk in longer; that walk happens during the warm-up, drawn faint on the left and shaded on the traces. Those iterations reflect where the chain started, not the posterior, which is why they are thrown away. (If a chain still has not arrived by the end of warm-up, R-hat will show it.)
In R
All code below is illustrative — treat it as something you reason about, not something that must execute here (no Stan is installed at render time). In a real session you would run it.
Run the marker model and summarise the draws
library(rstan)
stan_data <- list(N = 20, y = 13) # keys match the data block
fit <- stan(file = "gene_marker.stan", data = stan_data,
chains = 4, iter = 2000, seed = 1)
print(fit, pars = "theta") # mean, quantiles, n_eff, RhatPull the draws out and compute summaries yourself
draws <- as.data.frame(fit)$theta # a vector of ~4000 posterior draws
mean(draws) # posterior mean
quantile(draws, c(0.025, 0.975)) # 95% credible interval
mean(draws > 0.5) # posterior P(theta > 0.5)The point: once you hold the draws, every posterior summary is ordinary descriptive statistics.
A Poisson count model (the B4 answer, assembled)
// gene_count.stan
data {
int<lower=0> y; // observed read count
}
parameters {
real<lower=0> lambda; // expression rate (non-negative)
}
model {
lambda ~ normal(10, 5); // a weakly-informative prior
y ~ poisson(lambda); // likelihood for a count
}fit2 <- stan(file = "gene_count.stan", data = list(y = 8),
chains = 4, iter = 2000, seed = 1)
print(fit2, pars = "lambda")The brms shortcut (for a regression)
library(brms)
# cells: a data frame with a 0/1 column `expressed` and a `treatment` column
fit3 <- brm(expressed ~ treatment, data = cells,
family = bernoulli(), # 0/1 -> logistic regression
prior = prior(normal(0, 1), class = "b"),
chains = 4, iter = 2000, seed = 1)
summary(fit3) # same Rhat / credible-interval outputTasks
R1. Using the “pull the draws out” block, explain what each of the three summary lines returns for the marker model, and why mean(draws > 0.5) is a probability.
R2. Modify the gene_marker.stan model to use a flat prior theta ~ beta(1, 1) instead of beta(2, 2). Would you expect the posterior mean to move toward or away from the raw ratio \(13/20 = 0.65\)? Explain in one sentence. (You do not need to run it.)
R3. For the Poisson model, write the R call that fits it to an observed count of y = 15, then the two lines that extract the draws of lambda and report a 95% credible interval.
Hints
Ask: is this number something I measured and will type into R? If yes it is data. Is it something I do not know and want the posterior over? If yes it is a parameter. Counts and sample sizes are data; rates, means, fractions, and standard deviations are usually parameters.
The prior is the ~ statement whose left side is a parameter (it constrains the unknown before seeing data). The likelihood is the ~ statement whose left side is the data (it says how the observed numbers arise from the parameter).
The keys of the R list must be character-for-character the identifiers in the data block. The model declares N and y; anything else (n, successes) is a different name and Stan will not find it. See stan().
A rate is continuous and non-negative, so real<lower=0>. Any sensible prior works, e.g. normal(10, 5) (weakly informative) — Stan respects the <lower=0> constraint. The likelihood for a single count is poisson(lambda). The Poisson is the natural first distribution for counts (from the distributions block).
The mean column is the posterior mean. The 2.5% and 97.5% columns bracket the central 95% of the draws — that is the credible interval, and it is a direct probability statement about the parameter. Judge trust from Rhat (want \(\approx 1\), definitely \(< 1.01\)) and n_eff (want at least a few hundred).
Posterior mean = mean(draws). A 95% credible interval = quantile(draws, c(0.025, 0.975)). A posterior probability like \(P(\theta>0.5)\) = the fraction of draws above 0.5 = mean(draws > 0.5) (an average of TRUE/FALSE, which R treats as 1/0).
Solutions
B1. (a) RNA-seq rate. Data: the observed read count, int<lower=0> y; (and, if you had several observations, an int<lower=0> N; for how many). Parameters: the rate, real<lower=0> lambda;. The count is measured; the rate is unknown. (b) Mouse phenotype. Data: the sample size and the measurements, int<lower=0> n; and vector[n] y;. Parameters: the mean and spread, real mu; and real<lower=0> sigma; (a standard deviation is non-negative). The measurements are known; \(\mu\) and \(\sigma\) are what we infer.
B2. - Prior: theta ~ beta(2, 2); — it encodes the belief, before seeing the data, that \(\theta\) is probably near 0.5 (a gentle hump on \([0,1]\)). - Likelihood: y ~ binomial(N, theta); — it says the observed count \(y\) out of \(N\) arises as a Binomial draw with success probability \(\theta\), linking the data to the unknown.
The tell: the prior’s left side (theta) is a parameter; the likelihood’s left side (y) is data.
B3. The data block declares the identifiers N and y, but the list supplies n and successes. Stan looks for N and y, cannot find them, and errors (and it also receives two variables it does not recognise). Names must match exactly. Corrected:
stan_data <- list(N = 20, y = 13)B4. The three blanks:
parameters {
real<lower=0> lambda; // (1) a rate is non-negative
}
model {
lambda ~ normal(10, 5); // (2) any reasonable prior; normal(10,5) is weakly informative
y ~ poisson(lambda); // (3) Poisson likelihood for a count
}<lower=0>, (2) any sensible prior such asnormal(10, 5)— Stan keepslambdanon-negative because of the constraint, so a normal prior is fine here — and (3)poisson(lambda).
B5. (a) The posterior mean of \(\lambda\) is 8.10. (b) A 95% credible interval is \([7.05,\ 9.22]\) (the 2.5% and 97.5% columns). In words: given the data and prior, there is a 95% posterior probability that \(\lambda\) lies between 7.05 and 9.22. (c) Yes — Rhat = 1.00 (the chains agree, so the sampler converged) and n_eff = 980 (comfortably large, so the summaries are not noisy). These are the two numbers to check before reading the mean.
B6. No — do not report the posterior mean. Rhat = 1.18 is far above 1, meaning the chains did not converge to the same distribution, so the draws are not a reliable sample of the posterior; a “reasonable-looking” mean from an unconverged sampler is meaningless. n_eff = 32 is very low, confirming poor mixing. What to do: run longer (increase iter/warmup), run more chains, reconsider the priors or the model parameterisation, and only report results once Rhat < 1.01 and n_eff is adequate.
B7. With draws holding the 4000 posterior samples of \(\theta\): (a) Posterior mean: mean(draws). (b) 95% credible interval: quantile(draws, c(0.025, 0.975)) — the 2.5% and 97.5% empirical quantiles. (c) Posterior probability \(\theta > 0.5\): the fraction of draws exceeding 0.5, mean(draws > 0.5) (the mean of a TRUE/FALSE vector is the proportion of TRUEs).
R1. mean(draws) is the posterior mean of \(\theta\) (a point summary of the cloud of draws). quantile(draws, c(0.025, 0.975)) returns the values below which 2.5% and 97.5% of the draws fall — the 95% credible interval. mean(draws > 0.5) compares every draw to 0.5, giving a vector of TRUE/FALSE; averaging that vector (TRUE = 1, FALSE = 0) gives the proportion of draws above 0.5, which estimates the posterior probability \(P(\theta > 0.5)\) — a probability precisely because the draws are distributed as the posterior.
R2. With beta(1, 1) (the flat/uniform prior), the posterior is Beta(14,8), with mean \(14/22 \approx 0.636\). This is closer to the raw ratio \(13/20 = 0.65\) than the Beta(15,9) posterior mean \(15/24 = 0.625\) under beta(2, 2). The posterior mean therefore shows less shrinkage toward 0.5, although it is still not exactly the raw ratio. With a flat prior the posterior density is proportional to the likelihood; its mean need not equal the likelihood maximum.
R3.
fit_pois <- stan(file = "gene_count.stan", data = list(y = 15),
chains = 4, iter = 2000, seed = 1)
lambda_draws <- as.data.frame(fit_pois)$lambda
quantile(lambda_draws, c(0.025, 0.975)) # 95% credible interval for lambdaThe first call fits the Poisson model to the observed count 15; the next two lines pull the lambda draws out and report the 2.5%/97.5% quantiles as a 95% credible interval.
Where this leads
- Bayesian regression: the
brmsformula interface scales the three-block idea to real models — logistic regression for 0/1 outcomes, Poisson and negative binomial regression for (overdispersed) counts, and hierarchical models that share information across genes or samples. - Count models (distributions block): swapping the likelihood line for
poissonorneg_binomialturns this same skeleton into a model for RNA-seq counts — the honest treatment of overdispersion you met when comparing Poisson and negative binomial. - Posterior predictive checks: beyond summarising parameters, the draws let you simulate new data from the fitted model and check it against the real data — the standard way to ask “does this model actually fit?” (a later Bayesian topic).