Fitting equations (regression)

Week 4 — Fitting equations (regression)

Quantitative biology and integrative omics

About this lecture

In the linear algebra block you fitted a straight line by least squares: one best line, one number per coefficient. Today we ask a different question — how sure are we? — and answer it by fitting the same line the Bayesian way.

  • The model is unchanged: y = a + b\,x + \text{noise}. What changes is the answer: each coefficient becomes a distribution, not a single number.
  • Put priors on the intercept a, slope b, and noise scale \sigma; combine with the data (likelihood) to get the posterior.
  • Two interactive demos carry the ideas: many plausible lines and inside the sampler.
  • Read a slope as “there is a 96% chance it is positive” instead of a bare point estimate and a p-value.
  • Predict a new observation with uncertainty — a credible band, not just a line.
  • Biology: does a gene’s expression rise with donor age? With only a handful of samples, honest uncertainty matters more than a single best-fit slope.

Problem: is the upward slope real, or just noise?

We measure expression of an ageing-associated gene (normalised RNA-seq, log scale) in blood from a small cohort of donors, and plot it against age.

  • The cloud slopes gently upward: older donors tend to have higher expression.
  • But there are only 12 donors, and the points are scattered. Is the upward slope real, or could a flat line fit almost as well?
  • A single best-fit line cannot answer that. We need the range of slopes the data are compatible with.

The biological questions are really questions about uncertainty: Is the slope different from zero? By how much, plausibly? What expression should we expect for a new 70-year-old, and how tightly?

The model: a line plus noise

We assume each donor’s expression y is a straight-line function of age x plus random scatter:

y = a + b\,x + \varepsilon, \qquad \varepsilon \sim \mathcal{N}(0,\ \sigma^2)

Read in words: the noise \varepsilon is bell-shaped (Normal), centred on 0, with spread \sigma. Points fall on both sides of the line, mostly close to it.

Three unknowns to learn from the data:

  • a — the intercept (expression at x=0, or at a centred reference age),
  • b — the slope (change in expression per year of age); this is the biology we care about,
  • \sigma — the noise scale: how far points scatter around the line (donor-to-donor variability, measurement error).

This is the same model as ordinary linear regression. The Bayesian and least-squares approaches differ only in what they report about a, b, \sigma.

Least squares: one best line

From the linear algebra block: the least-squares line is the line with the smallest total squared miss — add up the squared vertical distances from each point to the line, and pick the line that makes this total as small as possible. In R this is one call:

fit_ls <- lm(expr ~ age, data = donors)
coef(fit_ls)      # (Intercept)  age   -> point estimates of a and b
confint(fit_ls)   # 95% confidence intervals

This gives one number for a and one for b (plus a confidence interval and a p-value). It is fast, familiar, and often enough. But:

  • The confidence interval’s 95% refers to the procedure over hypothetical repeated experiments, not to this slope.
  • There is no direct probability statement such as “there is a 96% probability the slope is positive.”
  • Prior knowledge (ageing genes change slowly) is awkward to include, and with few data points the single line can look deceptively precise.

The Bayesian version returns a full distribution for each parameter, so probability statements and honest prediction bands come for free.

The Bayesian shift: parameters as distributions

Frequentist: a, b, \sigma are fixed unknown numbers; the data are random.

Bayesian: we describe our uncertainty about a, b, \sigma with probability distributions, and update them using data via Bayes’ theorem (from the prior/likelihood/posterior unit):

\underbrace{p(\theta \mid \text{data})}_{\text{posterior}} \ \propto\ \underbrace{p(\text{data} \mid \theta)}_{\text{likelihood}} \times \underbrace{p(\theta)}_{\text{prior}}

Here \theta = (a, b, \sigma). The output is the posterior: a distribution over all three parameters at once that says which combinations are plausible given the data.

A weak prior rules out only absurd values

A prior encodes what is plausible for each parameter before seeing this dataset. Weakly-informative priors are a good default — wide enough not to force a conclusion, tight enough to rule out the absurd.

  • Intercept a: a broad bell curve — expression at the mean age could be a wide range of values.
  • Slope b: a bell curve centred at 0 (no assumed direction) but on a biologically sane scale — ageing genes change slowly per year (roughly within ±0.2 per year), so large slopes are implausible.
  • Noise \sigma: must be positive, so a prior that lives only above 0 and puts most weight on small-to-moderate scatter.

In R you write these as normal(0, 5), normal(0, 0.1) and exponential(1) (next slides).

A centred prior on b is honest, not a thumb on the scale: it lets the data move the slope, but resists over-reacting to a few noisy points.

Points far from a line make that line less believable

The likelihood asks: if this candidate line were the truth, how probable would the points we actually saw be?

  • Each point gets a bell curve centred on the line’s prediction at that age. A point close to the line sits near the top of its bell (probable); a point far away sits out in the tail (improbable).
  • Donors are independent, so the probabilities of all points multiply together into one number for the whole line.
  • So points far from the line make that line less believable. The line with the smallest total squared miss — the least-squares line — is the most believable one.

The least-squares and Bayesian fits share this same likelihood; they differ only by the prior, and by keeping the whole distribution instead of only its peak.

Try it: many plausible lines

MCMC samples the posterior as many plausible lines

Multiply prior and likelihood and normalise — the result is the posterior over (a, b, \sigma): how plausible each combination is, given the data.

  • For a straight line with Gaussian noise and general priors there is no simple formula for the full posterior, so we sample from it with MCMC (Markov-chain Monte Carlo).
  • MCMC returns thousands of draws, each one a plausible (a, b, \sigma) — a cloud of draws. Each draw is one plausible line, like the 50 lines in the demo.
  • The spread of the draws is the uncertainty. Summaries (mean, 95% interval) are just descriptions of that cloud.

Fitting it in R with brms

brms writes and runs the MCMC for you from an lm-style formula.

library(brms)

fit <- brm(
  expr ~ age,                       # same formula as lm()
  data   = donors,
  family = gaussian(),              # line + Gaussian noise
  prior  = c(
    prior(normal(0, 5),    class = "Intercept"),
    prior(normal(0, 0.1),  class = "b"),        # slope
    prior(exponential(1),  class = "sigma")     # noise scale
  ),
  chains = 4, iter = 2000, seed = 1
)

The formula expr ~ age is identical to what you would pass to lm(). The extra arguments declare the priors and how much to sample.

Always check the sampling

Before trusting anything, confirm the MCMC actually converged.

summary(fit)          # look at Rhat and ESS for every parameter
plot(fit)             # trace plots: chains should overlap like "fuzzy caterpillars"
  • Rhat should be \approx 1.00 for every parameter (chains agree). Values \gtrsim 1.01 signal trouble.
  • ESS (effective sample size) should be comfortably large (hundreds+).
  • Trace plots should look like stationary noise with the chains fully overlapping.

If these fail, the numbers are unreliable — re-run with more iterations or reconsider the model, don’t interpret.

Try it: inside the sampler

Reading the posterior: coefficients are distributions

posterior_summary(fit)     # mean, SE, and 95% credible interval per parameter
Parameter Estimate 95% credible interval
Intercept a (at age 0) 4.71 [2.93, 6.49]
slope b (per year) 0.030 [−0.003, 0.064]
\sigma 0.91 [0.59, 1.45]
  • Each row is a summary of that parameter’s marginal posterior — the shape of the whole distribution, boiled down.
  • The slope’s 95% credible interval [-0.003, 0.064] means: given the data and priors, there is a 95% probability the true per-year change lies in this range.
  • That is the plain-English reading people wrongly attach to a frequentist CI — here it is actually correct.

Interpreting a coefficient as a probability

Because the slope is a full distribution of draws, we can ask direct biological questions by counting draws:

draws <- as_draws_df(fit)

mean(draws$b_age > 0)          # P(slope > 0 | data)  e.g. 0.96
quantile(draws$b_age, c(0.025, 0.975))   # 95% credible interval
  • mean(draws$b_age > 0) is just the fraction of posterior draws with a positive slope — a genuine probability that the gene’s expression increases with age.
  • No null hypothesis, no p-value: a probability you can report and act on.
  • Want the chance the effect exceeds a biologically meaningful size? mean(draws$b_age > 0.01).

This is the payoff: coefficients you can reason about probabilistically.

A new donor’s range is wider than the average line’s

For a new donor aged 70, “predict the expression” is really two questions:

  • Where is the average line? Uncertainty in a and b only → a credible interval for the mean expression at age 70. Narrow.
  • Where will one new donor land? Adds the noise \sigma on top → a wider prediction interval for a single observation.
newdata <- data.frame(age = 70)

# uncertainty in the regression line (mean response)
fitted(fit, newdata = newdata)          # estimate + 95% credible interval

# uncertainty for a brand-new individual (adds sigma)
predict(fit, newdata = newdata)         # estimate + 95% prediction interval

conditional_effects(fit)                # mean band across all ages

Confusing these two is a classic error: the second band is always wider because it includes donor-to-donor scatter, not just uncertainty about the line.

Try it: two kinds of band

With flat priors, Bayes peaks at the least-squares line

Aspect Least squares (lm) Bayesian (brms)
Output per coefficient one number + CI full posterior distribution
Slope reading estimate + p-value P(b>0\mid\text{data}) directly
Interval meaning long-run procedure probability about this parameter
Prior knowledge hard to include built in as the prior
Small samples can look over-precise prior regularises honestly
Prediction interval formulae posterior-predictive draws
Cost / speed instant MCMC, slower; needs diagnostics
When the priors are flat — posterior peak = least-squares fit

Same line, same likelihood — Bayes keeps the whole distribution where least squares keeps only its peak.

Summary

Idea Key fact
Model y = a + b\,x + \varepsilon, \varepsilon\sim\mathcal N(0,\sigma^2) — same as ordinary regression
Bayesian shift parameters a,b,\sigma get distributions, not single numbers
Bayes’ theorem posterior \propto likelihood \times prior
Prior weakly-informative; slope centred at 0 = sceptical, regularising
Likelihood points far from a line make it less believable; the most believable line is the least-squares line
Posterior sampled by MCMC; draws = a cloud of plausible (a,b,\sigma)
Coefficient reading P(b>0\mid\text{data}) = fraction of draws with b>0
Credible interval direct probability the parameter lies in the range
Prediction mean band (narrow) vs individual band (wider, adds \sigma)
Diagnostics check Rhat \approx 1 and trace plots before interpreting

Builds on: least-squares fitting (Least squares as projection, week 3); prior / likelihood / posterior (Bayes’ theorem). Generalises to: other kinds of data, e.g. counts, by swapping family = gaussian() for a count family (Error models, next unit).

Optional: the maths behind the fit

Least squares in matrix form. Stack the data into a design matrix X (a column of 1s for a, a column of ages for b). The least-squares coefficients solve the normal equations: \hat{\boldsymbol\beta} = (X^\top X)^{-1} X^\top \mathbf{y}.

Likelihood. Each donor contributes a Normal density, p(y_i \mid a, b, \sigma) = \mathcal{N}(y_i \mid a + b\,x_i,\ \sigma^2); independence makes the full likelihood the product \prod_{i=1}^{n} \mathcal{N}(y_i \mid a + b\,x_i,\ \sigma^2). For fixed \sigma this is proportional to \exp\!\big(-\text{SSR}/2\sigma^2\big) with \text{SSR}=\sum_i (y_i - a - b x_i)^2, so maximising the likelihood is minimising the sum of squared residuals.

Posterior. p(a, b, \sigma \mid \text{data}) \propto \left[\prod_{i} \mathcal{N}(y_i \mid a + b x_i,\ \sigma^2)\right] p(a)\,p(b)\,p(\sigma), with priors a \sim \mathcal{N}(0, 5), b \sim \mathcal{N}(0, 0.1), \sigma \sim \text{Exponential}(1).