Skip to content

Bayesian regression with predictive checks

A Bayesian regression combines a likelihood with assumptions about plausible parameter values. Its result is a posterior distribution, so an estimated slope comes with a distribution of uncertainty rather than only one fitted value. That distribution still depends on the model, its priors, and the observations that reached the calculation.

This lesson uses an original simulation with independent observations and a linear mean. Both variables use arbitrary units. The known intercept, slope, and residual standard deviation let us examine a model whose generating mechanism is explicit; they do not describe a biological experiment.

Download the measurements and simulation parameters. Place both files in an inputs folder. The example uses Python with PyMC 5.26.1 and ArviZ 0.22.0. The linear regression lesson introduces the intercept, slope, and residuals used here.

The likelihood assumes independent, normally distributed residuals with one standard deviation. The predictor is measured without error in this simulation. Repeated samples from the same donor would require a model that represents their dependence.

import json
import logging
from pathlib import Path
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc as pm
logging.getLogger("pymc").setLevel(logging.ERROR)
output = Path("outputs")
output.mkdir(exist_ok=True)
data = pd.read_csv("inputs/bayesian_measurements.csv")
assert list(data.columns) == ["sample", "predictor", "response"]
assert data["sample"].is_unique and not data.isna().any().any()
x = data.predictor.to_numpy()
y = data.response.to_numpy()
assert np.isfinite(x).all() and np.isfinite(y).all()
truth = json.loads(Path("inputs/simulation_truth.json").read_text())
print("Independent observations:", len(data))
print("Generating intercept:", truth["intercept"])
print("Generating slope:", truth["slope"])
print("Generating residual SD:", truth["residual_sd"])
Independent observations: 80
Generating intercept: 0.4
Generating slope: 1.2
Generating residual SD: 0.8

For each observation, the expected response is intercept + slope * predictor. The slope therefore measures response units per predictor unit. We place zero-centered Normal priors on the intercept and slope, and a HalfNormal prior on the positive residual standard deviation.

Examine the prior before interpreting a posterior

Section titled “Examine the prior before interpreting a posterior”

The helper declares the same likelihood for both prior choices used later. The baseline prior gives the slope a standard deviation of 1.5. This is a statement on the current measurement scale, not a universal default for concentrations, counts, or logarithms.

def make_model(predictor, response, slope_scale):
"""Declare the regression for one slope prior.
Args:
predictor: One-dimensional measured predictor values.
response: Independent response measurements at those values.
slope_scale: Positive standard deviation of the Normal slope prior.
Returns:
A PyMC model with an independent Normal likelihood.
"""
with pm.Model(coords={"observation": np.arange(len(response))}) as model:
intercept = pm.Normal("intercept", mu=0, sigma=1.5)
slope = pm.Normal("slope", mu=0, sigma=slope_scale)
sigma = pm.HalfNormal("sigma", sigma=1)
mean = pm.Deterministic(
"mean", intercept + slope * predictor, dims="observation"
)
pm.Normal("response", mu=mean, sigma=sigma, observed=response,
dims="observation")
return model
baseline_model = make_model(x, y, slope_scale=1.5)
with baseline_model:
prior = pm.sample_prior_predictive(draws=1000, random_seed=4101)
prior_values = prior.prior_predictive["response"].values.reshape(-1, len(x))
prior_means = prior.prior["mean"].values.reshape(-1, len(x))

These draws predict measurements without conditioning on the observed response. Their intervals appear beside the posterior intervals below. For a real assay, compare them with known units and plausible measurement ranges before examining the treatment estimate. A prior that predicts impossible values needs a scientific correction, not a favorable posterior plot.

NUTS explores the posterior with four chains. Adaptation draws tune the sampler; the retained draws provide the summaries. target_accept controls an adaptation target, not the probability that a scientific conclusion is correct.

with baseline_model:
posterior = pm.sample(
draws=2000, tune=1000, chains=4, cores=2, random_seed=4102,
target_accept=0.9, progressbar=False, nuts_sampler="pymc"
)
diagnostics = az.summary(
posterior, var_names=["intercept", "slope", "sigma"],
kind="diagnostics", round_to=4
)
divergences = int(posterior.sample_stats.diverging.sum())
diagnostics.to_csv(output / "baseline_diagnostics.csv")
print(diagnostics[["mcse_mean", "ess_bulk", "ess_tail", "r_hat"]].to_string())
print("Divergences:", divergences)
assert divergences == 0
assert diagnostics.r_hat.max() < 1.01
assert diagnostics.ess_bulk.min() > 400
assert diagnostics.ess_tail.min() > 400
mcse_mean ess_bulk ess_tail r_hat
intercept 0.0009 7850.4136 5599.4320 1.0005
slope 0.0011 6946.5998 5451.2696 1.0001
sigma 0.0007 7786.8699 5747.2978 1.0009
Divergences: 0

R-hat compares within-chain and between-chain variation. Bulk and tail effective sample sizes describe how much independent information the correlated draws provide for central and tail summaries. Monte Carlo standard error describes numerical uncertainty in a posterior estimate; it is different from the posterior standard deviation of the parameter itself.

A divergent transition can indicate that the sampler misses part of the posterior. Inspect the parameterization and model before interpreting its intervals. R-hat near one and zero divergences support the numerical calculation, but neither tests whether a Normal likelihood describes the measurements.

trace_axes = az.plot_trace(
posterior, var_names=["intercept", "slope", "sigma"],
compact=False, figsize=(10, 7)
)
trace_figure = trace_axes.ravel()[0].figure
trace_figure.tight_layout()
trace_figure.savefig(output / "bayesian_trace.png", dpi=160)
plt.close(trace_figure)

Posterior density plots and four chain traces show the intercept, slope, and residual standard deviation.

The interval below contains the central 95 percent of the retained slope draws. It is an equal-tailed credible interval conditional on this likelihood, prior, and dataset. It is not a confidence interval from repeated sampling of new datasets.

baseline_slope = posterior.posterior["slope"].values.ravel()
lower, median, upper = np.quantile(baseline_slope, [0.025, 0.5, 0.975])
print(f"Posterior median slope: {median:.3f}")
print(f"Central 95% credible interval: [{lower:.3f}, {upper:.3f}]")
print(f"Posterior fraction above zero: {(baseline_slope > 0).mean():.4f}")
Posterior median slope: 1.020
Central 95% credible interval: [0.846, 1.191]
Posterior fraction above zero: 1.0000

The fraction above zero approximates a posterior probability under the specified model. If every retained draw is positive, the printed fraction is one; a finite sample of draws cannot establish that the posterior probability is exactly one.

The generating slope is 1.2, slightly above this interval. A simulation can produce such a sample even when the fitted likelihood matches its generator.

The mean curve describes the expected response at a predictor value. A new measurement varies around that curve, so its predictive interval must also include residual variation. The two ribbons keep those quantities separate.

with baseline_model:
predictive = pm.sample_posterior_predictive(
posterior, var_names=["response"], random_seed=4103,
progressbar=False
)
posterior_values = predictive.posterior_predictive["response"].values
posterior_values = posterior_values.reshape(-1, len(x))
posterior_means = posterior.posterior["mean"].values.reshape(-1, len(x))
figure, axes = plt.subplots(1, 2, figsize=(10, 4.4), sharey=True)
for axis, values, means, title in zip(
axes, [prior_values, posterior_values],
[prior_means, posterior_means],
["Prior predictions", "Posterior predictions"]
):
value_band = np.quantile(values, [0.025, 0.975], axis=0)
mean_band = np.quantile(means, [0.025, 0.975], axis=0)
axis.fill_between(x, *value_band, color="#dce8f1",
label="95% new measurement interval")
axis.fill_between(x, *mean_band, color="#86abc5",
label="95% mean interval")
axis.plot(x, np.median(means, axis=0), color="#245577")
axis.scatter(x, y, color="#aa5d2a", s=14, label="Invented observations")
axis.set(title=title, xlabel="Predictor, arbitrary units")
axis.spines[["top", "right"]].set_visible(False)
axes[0].set_ylabel("Response, arbitrary units")
axes[1].legend(fontsize=8, loc="upper left")
figure.tight_layout()
figure.savefig(output / "bayesian_predictions.png", dpi=160)
plt.close(figure)
replicated_means = posterior_values.mean(axis=1)
replicated_sds = posterior_values.std(axis=1, ddof=1)
for label, observed, replicated in [
("Mean", y.mean(), replicated_means),
("Standard deviation", y.std(ddof=1), replicated_sds),
]:
bounds = np.quantile(replicated, [0.025, 0.975])
print(f"{label}: observed {observed:.3f}; replicated 95% range "
f"[{bounds[0]:.3f}, {bounds[1]:.3f}]")
Mean: observed 0.369; replicated 95% range [0.153, 0.586]
Standard deviation: observed 1.133; replicated 95% range [0.952, 1.342]

Prior and posterior panels compare the observations with pointwise intervals for the mean and for a new measurement. The new measurement interval is wider.

These are pointwise intervals at the observed predictor values. The posterior checks reuse the fitted observations, so they do not measure predictive performance on a new dataset. A curved residual pattern or unusual tails can require a different likelihood even when the overall mean and spread agree.

A slope prior with standard deviation 0.2 strongly concentrates around zero on this scale. The next fit changes only that prior. It does not choose between priors by selecting the result closest to the simulated truth.

skeptical_model = make_model(x, y, slope_scale=0.2)
with skeptical_model:
skeptical = pm.sample(
draws=2000, tune=1000, chains=4, cores=2, random_seed=4104,
target_accept=0.9, progressbar=False, nuts_sampler="pymc"
)
skeptical_diagnostics = az.summary(
skeptical, var_names=["intercept", "slope", "sigma"],
kind="diagnostics", round_to=4
)
assert int(skeptical.sample_stats.diverging.sum()) == 0
assert skeptical_diagnostics.r_hat.max() < 1.01
assert skeptical_diagnostics.ess_bulk.min() > 400
assert skeptical_diagnostics.ess_tail.min() > 400
skeptical_diagnostics.to_csv(output / "skeptical_diagnostics.csv")
comparison = []
fits = [("Baseline", posterior), ("Concentrated near zero", skeptical)]
for label, fit in fits:
draws = fit.posterior["slope"].values.ravel()
interval = np.quantile(draws, [0.025, 0.5, 0.975])
comparison.append([label, *interval])
comparison = pd.DataFrame(
comparison, columns=["prior", "lower", "median", "upper"]
)
comparison.to_csv(output / "prior_comparison.csv", index=False)
print(comparison.to_string(index=False, float_format="%.3f"))
prior lower median upper
Baseline 0.846 1.020 1.191
Concentrated near zero 0.676 0.851 1.018

The second prior pulls the slope toward zero. In a real analysis, the decision must come from measurement scale, previous evidence, and the intended model. Report consequential prior sensitivity with the result rather than hiding the alternative fit.

for label, fit in [("baseline", posterior), ("skeptical", skeptical)]:
np.savez(
output / f"{label}_draws.npz",
intercept=fit.posterior["intercept"].values,
slope=fit.posterior["slope"].values,
sigma=fit.posterior["sigma"].values,
)

Abril-Pla and colleagues, 2023 describe PyMC and its tools for Bayesian inference in Python.

Kumar and colleagues, 2019 describe ArviZ and its summaries and diagnostic plots for Bayesian models.

The PyMC predictive check guide explains how simulated measurements expose prior assumptions and posterior model behavior. Its distinction between a mean curve and individual measurements is useful when interpreting the two ribbons here.

The ArviZ summary documentation defines effective sample sizes, Monte Carlo errors, and R-hat. Read it before deciding how many posterior draws a reported quantity needs.

The PyMC sampling documentation explains adaptation, chains, and NUTS settings. More draws address numerical precision; they do not repair an incorrect likelihood or an unsupported prior.