Skip to content

BBayesian · bayes.model

Bayesian regression model (Stan)

How do predictors relate to an outcome, with a full posterior for every effect — including grouped rows?

A Bayesian generalized linear (mixed) model fitted with Stan: Gaussian, robust Student-t, logistic, binomial, Poisson, negative binomial or ordinal outcomes, with optional varying intercepts and slopes for up to two grouping factors. NUTS (Hamiltonian Monte Carlo) draws from the posterior by default; Pathfinder, ADVI and a Laplace approximation are faster approximations. Every effect gets a posterior mean, credible interval and the probability that it is above zero, with the sampler's own checks (R-hat, effective sample sizes, divergences, E-BFMI), leave-one-out cross-validation (PSIS-LOO with Pareto k̂), Bayesian R² and posterior predictive checks. Default priors are rstanarm's weakly informative priors, shown in the result. Python and R run the same compiled Stan program on the same data file, so their draws are identical.

Experimental Python and R agree to 6 decimals Also called Bayesian regression, Bayesian GLM, Bayesian mixed model…

A real result

Example “Gaussian mtcars”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Bayesian gaussian (normal) model (Stan)Recorded · Python and R agreeRecorded 2026-11-25 · 70 values compared
R

Bayesian gaussian (normal) model of mpg (n = 32), NUTS (Hamiltonian Monte Carlo). Posterior: wt has median -5.31 (95% credible interval -7.06 to -3.90); P(> 0) = 0.00. Largest R-hat 1.007, 0 divergent transitions. PSIS-LOO elpd = -84.4 (SE 4.2).

wt (posterior median)
−5.307
95% credible interval
[−7.063, −3.900]
P(effect > 0)
0
Largest R-hat
1.007
elpd (PSIS-LOO)
−84.435
Bayesian R² (median)
0.7320

Assumptions

  • Sampler converged (R-hat, ESS) — Largest R-hat 1.007 (want ≤ 1.01); smallest bulk ESS 366 and tail ESS 285 (want ≥ 400).
  • No divergent transitions — No divergent transitions.
  • Trajectories within the tree depth — No draw hit the maximum tree depth.
  • Energy (E-BFMI ≥ 0.3) — Smallest E-BFMI across chains 1.04 (below 0.3 means the sampler explores the tails poorly).
  • Leave-one-out is reliable (Pareto k̂) — 1 of 32 rows have k̂ above 0.64 (largest 0.68); those rows are influential and their LOO estimate is unreliable.
  • Replicated data look like the observed data — Posterior predictive p-values are between 0.01 and 0.99.
  • Priors stated — Results depend on the priors in the Priors table; rerun with wider priors to see how much.

Posterior summary

ParameterMeanSD95% lowerMedian95% upperR-hatBulk ESSTail ESSP(> 0)
(Intercept)37.2382.90232.02037.09943.2391.002386.17386.131
wt−5.3300.7759−7.063−5.307−3.9001.001366.46355.330
am_f: manual−0.00111.439−2.7080.01622.8311.007377.95380.370.5067
sigma3.2180.45942.5153.1614.2351.001481.46284.881

Priors

ParameterPriorNote
(Intercept)Normal(20.09, 15.07)at the predictors' means
wtNormal(0, 15.4)autoscaled
am_f: manualNormal(0, 30.2)autoscaled
sigmaExponential(0.1659)residual SD

Sampler by chain

ChainDivergentMax tree depth hitsE-BFMIStep sizeMean acceptance
1001.0380.61230.9092
2001.1290.47110.9136

Leave-one-out cross-validation (PSIS-LOO)

QuantityEstimateSE
elpd_loo (expected log predictive density)−84.4354.209
p_loo (effective number of parameters)4.0141.203
LOOIC (−2 × elpd_loo)168.878.419

Posterior predictive checks

StatisticObservedReplicated (mean)P(rep ≥ obs)
Mean20.09120.0810.4967
Standard deviation6.0276.1490.5567
Maximum33.90031.9110.1867
Minimum10.4005.9470.0450
  • Outcome model: Gaussian (normal).
  • Credible intervals are equal-tailed posterior quantiles; P(> 0) is the share of draws above zero.
  • Bayesian results are not p-values and are not entered in the multiple-testing ledger.
Python

Bayesian gaussian (normal) model of mpg (n = 32), NUTS (Hamiltonian Monte Carlo). Posterior: wt has median -5.31 (95% credible interval -7.06 to -3.9); P(> 0) = 0.00. Largest R-hat 1.007, 0 divergent transitions. PSIS-LOO elpd = -84.4 (SE 4.2).

wt (posterior median)
−5.307
95% credible interval
[−7.063, −3.900]
P(effect > 0)
0
Largest R-hat
1.007
elpd (PSIS-LOO)
−84.435
Bayesian R² (median)
0.7320

Assumptions

  • Sampler converged (R-hat, ESS) — Largest R-hat 1.007 (want ≤ 1.01); smallest bulk ESS 366 and tail ESS 285 (want ≥ 400).
  • No divergent transitions — No divergent transitions.
  • Trajectories within the tree depth — No draw hit the maximum tree depth.
  • Energy (E-BFMI ≥ 0.3) — Smallest E-BFMI across chains 1.04 (below 0.3 means the sampler explores the tails poorly).
  • Leave-one-out is reliable (Pareto k̂) — 1 of 32 rows have k̂ above 0.64 (largest 0.68); those rows are influential and their LOO estimate is unreliable.
  • Replicated data look like the observed data — Posterior predictive p-values are between 0.01 and 0.99.
  • Priors stated — Results depend on the priors in the Priors table; rerun with wider priors to see how much.

Posterior summary

ParameterMeanSD95% lowerMedian95% upperR-hatBulk ESSTail ESSP(> 0)
(Intercept)37.2382.90232.02037.09943.2391.002386.17386.131
wt−5.3300.7759−7.063−5.307−3.9001.001366.46355.330
am_f: manual−0.00111.439−2.7080.01622.8311.007377.95380.370.5067
sigma3.2180.45942.5153.1614.2351.001481.46284.881

Priors

ParameterPriorNote
(Intercept)Normal(20.09, 15.07)at the predictors' means
wtNormal(0, 15.4)autoscaled
am_f: manualNormal(0, 30.2)autoscaled
sigmaExponential(0.1659)residual SD

Sampler by chain

ChainDivergentMax tree depth hitsE-BFMIStep sizeMean acceptance
1001.0380.61230.9092
2001.1290.47110.9136

Leave-one-out cross-validation (PSIS-LOO)

QuantityEstimateSE
elpd_loo (expected log predictive density)−84.4354.209
p_loo (effective number of parameters)4.0141.203
LOOIC (−2 × elpd_loo)168.878.419

Posterior predictive checks

StatisticObservedReplicated (mean)P(rep ≥ obs)
Mean20.09120.0810.4967
Standard deviation6.0276.1490.5567
Maximum33.90031.9110.1867
Minimum10.4005.9470.0450
  • Outcome model: Gaussian (normal).
  • Credible intervals are equal-tailed posterior quantiles; P(> 0) is the share of draws above zero.
  • Bayesian results are not p-values and are not entered in the multiple-testing ledger.

Shortened for the Academy: 8 chart(s) dropped to stay under 100 KB; 8 chart(s) dropped to stay under 100 KB.

Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.

Worked examples in the app

  • Gaussian mtcarsmtcars · outcome: mpg · predictors: wt, am_f
  • Student t mtcarsmtcars · outcome: mpg · predictors: wt
  • Gaussian sleep slopess1_sleep · group: Subject · outcome: Reaction · predictors: Days · slopes: Days
  • Logistic visitss1_visits · group: patient · outcome: adverse event · predictors: visit, treatment
  • Binomial cbpps1_cbpp · group: herd · outcome: incidence · predictors: period · trials: size
  • Poisson tickss1_ticks · group: location · outcome: ticks · predictors: year, height (z)
  • Negbinomial tickss1_ticks · outcome: ticks · predictors: year
  • Ordinal satisfactionf_ordinal · outcome: satisfaction · predictors: minutes per week

In the guides

Where it sits in the decision guides

  • Binary outcome: logistic regression (regularized) · Statistics Guide · D — Predict an outcome
  • Count outcome: Poisson / negative binomial / zero-inflated · Statistics Guide · D — Predict an outcome
  • Repeated / clustered: mixed models, GEE · Statistics Guide · D — Predict an outcome

What you need

Outcomenumeric / categorical / boolean · 1 column
A number (Gaussian, Student-t), yes/no or a two-level category (logistic), a count (Poisson, negative binomial, or successes with Trials) or ordered categories (ordinal).
Predictorsnumeric / categorical / boolean · 0–20 columns · 2–30 levels
Predictors with one effect for every row (fixed effects); categories become treatment-coded columns.
Trialsnumeric · 0–1 column
Logistic with counts: the number of trials per row; the outcome is then the number of successes.
Exposurenumeric · 0–1 column
Counts: time at risk or size per row (> 0); its log is an offset, so effects are rate ratios.
Grouping factorcategorical / numeric / boolean · 0–1 column
The unit rows belong to (subject, school, site); each level gets its own intercept, drawn from a shared distribution.
Varying slopesnumeric · 0–2 columns
Numeric predictors whose effect may differ between levels of the grouping factor (correlated with the varying intercept).
Second grouping factorcategorical / numeric / boolean · 0–1 column
A second grouping factor with its own varying intercept, nested in the first or crossed with it.

Choices you make

model

Outcome modeldefault gaussian

The distribution of the outcome given the predictors.

  • Gaussian (normal)(default) — For a continuous outcome with roughly symmetric, constant-spread residuals.
  • Student-t (robust) — Like Gaussian, but heavy tails make a few outliers count less; the degrees of freedom are estimated.
  • Logistic (yes/no or successes of trials) — For a yes/no outcome, or successes out of a number of trials when you give Trials.
  • Poisson (counts) — For counts whose variance is close to their mean.
  • Negative binomial (overdispersed counts) — For counts more spread out than Poisson allows; a shape parameter is estimated.
  • Ordinal (cumulative logit) — For ordered categories such as ratings; one effect per predictor and a cutpoint between each pair of categories.
Event (modeled level)default —

Yes/no outcomes: the level whose probability is modeled (default: the second level, true for yes/no).

Interactionsdefault none

Add interaction terms so the effect of one predictor can depend on another.

  • None (main effects only)(default) — Fits main effects only; the usual starting point.
  • First two predictors (A × B) — Adds the product of the first two predictors, so one effect can depend on the other.
  • All pairs of predictors — Adds every two-way product; needs plenty of rows.
Second grouping factor isdefault nested

Whether the second grouping factor sits inside the first or is separate from it.

  • Nested in the first(default) — Levels of the second factor only make sense within the first (classes in schools).
  • Crossed with the first — The two factors are separate (subjects crossed with items).
Coefficient priordefault normal

The prior placed on every coefficient.

  • Normal (weakly informative)(default) — rstanarm's default: Normal(0, 2.5) on a scale set by the data.
  • Student-t (heavier tails) — Allows a few large effects while shrinking small ones.
  • Cauchy (very heavy tails) — A Student-t with one degree of freedom; vague about large effects.
  • Flat (improper) — No prior on the coefficients; results approach the classical fit, but leave-one-out and prior checks are less meaningful.
Coefficient prior scaledefault 2.5

Spread of the coefficient prior before autoscaling; smaller values shrink effects harder.

Advanced

Prior degrees of freedomdefault 3

Degrees of freedom of the Student-t coefficient prior; smaller means heavier tails.

Scale priors to the datadefault on

rstanarm's rule: multiply each coefficient's prior scale by sd(outcome) / sd(predictor) (Gaussian-type outcomes) or 1 / sd(predictor).

Intercept prior scaledefault 2.5

Spread of the intercept's Normal prior (at the predictors' means) before autoscaling.

Correlation prior (LKJ η)default 1

Prior on the correlation of varying intercepts and slopes: 1 is uniform; larger values favor correlations near 0.

Target acceptance (adapt_delta)default 0.8

Raise it (0.95, 0.99) when there are divergent transitions: smaller steps, slower but more accurate.

Maximum tree depthdefault 10

Caps the length of each trajectory at 2^depth steps; raise it when many draws hit the cap.

QR reparameterizationdefault off

Samples on an orthogonalized version of the predictors; helps when predictors are strongly correlated.

options

Algorithmdefault nuts

How the posterior is computed: NUTS draws from it; the others approximate it.

  • NUTS (Hamiltonian Monte Carlo)(default) — Draws from the exact posterior with several chains and checks itself; the default and the reference.
  • Pathfinder (fast approximation) — A quick variational approximation; good for a first look, check results with NUTS.
  • ADVI mean-field (approximation) — Variational inference with independent normal factors; fast but understates uncertainty.
  • ADVI full-rank (approximation) — Variational inference with a full covariance; slower than mean-field, often closer to NUTS.
  • Laplace (normal at the mode) — A normal approximation at the posterior mode; fastest, rough when the posterior is skewed.
Chainsdefault 4

Independent Markov chains; four lets R-hat compare them.

Warmup iterations per chaindefault 1000

Iterations used to tune the sampler; they are not kept.

Draws per chaindefault 1000

Draws kept per chain (NUTS) or in total (approximations).

Random seeddefault 1234

Fixes the random numbers, so reruns give identical draws in Python and in R.

Prior predictive check (ignore the data)default off

Draws from the priors alone, so you can see what outcomes they imply before fitting.

statistics

Leave-one-out cross-validationdefault on

Estimates out-of-sample fit (elpd) from the draws with Pareto-smoothed importance sampling, with k̂ per row.

Posterior predictive checksdefault on

Simulates new data from the fitted model and compares it with the observed outcome.

Credible leveldefault 0.95

Probability inside each credible interval: 0.95 gives 95% intervals (2.5% to 97.5% quantiles).

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Sampler converged (R-hat, ESS)

    Rank-normalized R-hat at most 1.01 and bulk and tail effective sample sizes of at least 400 for every reported parameter (Vehtari et al. 2021).

    • If violated → Run longer chains — More warmup and more draws give the chains time to mix and raise the effective sample sizes; if R-hat stays high, look for divergences or a weakly identified parameter.
  • No divergent transitions

    A divergent transition means the sampler hit a region it can't explore; any divergence can bias the results.

    • If violated → Smaller steps (adapt_delta 0.95) — A higher target acceptance makes the sampler take smaller steps, which removes most divergences; if some remain, the model's geometry needs a change (fewer varying slopes, stronger priors).
  • Trajectories within the tree depth

    Draws that hit the maximum tree depth make sampling slow; they don't bias the results.

    • If violated → Allow longer trajectories (tree depth 12) — Draws that hit the cap are slow, not wrong; a deeper tree lets each trajectory finish. Correlated predictors also cause this — try the QR reparameterization.
  • Energy (E-BFMI ≥ 0.3)

    E-BFMI below 0.3 in a chain means the momentum resampling explores the tails poorly.

  • Leave-one-out is reliable (Pareto k̂)

    Rows with k̂ above min(1 − 1/log10(S), 0.7) are too influential for importance sampling; their LOO estimate is unreliable. Pathfinder resamples its draws, so many repeat; when repeats tie in the tail, k̂ can't be estimated (blank) and the check says so.

  • Replicated data look like the observed data

    Posterior predictive p-values near 0 or 1 for the mean, SD, extremes or zeros mean the model misses that feature of the data.

  • Priors statedNot checked from data: state why it holds

    Bayesian results depend on the priors; the result lists the ones used.

What it reports

n
How many independent units the analysis used; it sets precision and power.
k
How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
family
The distribution assumed for the outcome: Gaussian, Student-t, logistic, binomial, Poisson, negative binomial or ordinal.
algorithm
How the posterior was computed: NUTS draws from it; Pathfinder, ADVI and Laplace approximate it.
chains
Independent Markov chains run from different starting points; comparing them is what R-hat does.
draws
Draws kept after warmup, over all chains; every summary on the card comes from them.
cred_level
Probability inside each credible interval: 0.95 gives the 2.5% to 97.5% quantiles of the posterior.
prior_only
True when the run ignored the outcome and drew from the priors alone (a prior predictive check).
rhat_max
The worst R-hat over the reported parameters; want 1.01 or less.
ess_bulk_min
The fewest effective draws for the center of any reported parameter; want at least 400.
ess_tail_min
The fewest effective draws for the 5% and 95% quantiles of any parameter; low values make interval ends noisy.
n_divergent
Draws that ended in a divergent transition; want 0.
divergent_share
Divergent transitions ÷ draws; above 1% the divergence check fails.
treedepth_hits
Draws whose trajectory hit the maximum tree depth: slow sampling, not biased sampling.
ebfmi_min
The lowest energy diagnostic across chains; below 0.3 warns of poor exploration.
elpd_loo
Expected log predictive density for new data, from leave-one-out; higher is better when comparing models on the same rows.
elpd_loo_se
Standard error of elpd_loo; differences between models smaller than about four of these are hard to tell apart.
p_loo
Effective number of parameters from leave-one-out; far above the real count suggests a misspecified model.
looic
−2 × elpd_loo, on the deviance scale like AIC; lower is better.
looic_se
Standard error of LOOIC (twice the SE of elpd_loo).
khat_max
The most influential row's k̂; above the threshold that row's leave-one-out estimate is unreliable.
n_bad_khat
How many rows have a Pareto k̂ above the threshold; inspect them, or refit without them for an exact LOO.
khat_threshold
min(1 − 1/log10(S), 0.7) for S draws: rows above it make PSIS-LOO unreliable.
r2_median
Median over draws of the Bayesian R²: the share of outcome variance the model's fitted values explain.
r2_low
Lower end of the Bayesian R²'s credible interval.
r2_high
Upper end of the Bayesian R²'s credible interval.

Per group, level or term: mean[<term>], sd[<term>], lower[<term>], median[<term>], upper[<term>], rhat[<term>], ess_bulk[<term>], ess_tail[<term>], mcse_mean[<term>], p_positive[<term>], ppc_p[<statistic>]

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses pandas, numpy, scipy, pyarrow, codesplash; R uses posterior, loo, nanoparquet, jsonlite, codesplashr.

Default traps between the two languages

  • Both engines write the same Stan data file (keys sorted, 17 significant digits) and run the same compiled program with the same seed, so the draws are identical; every number that feeds Stan beyond the raw columns (centering, autoscaled prior scales, the log of an exposure) is computed inside the program.
  • Summaries: R calls the posterior (1.7) and loo (2.10) packages; Python uses a port of the same algorithms (codesplash.bayes.diagnostics, also checked against those packages' values in crates/cs-mcmc's oracle fixture), so R-hat, ESS, MCSE and PSIS-LOO agree to about 1e-12.
Python

The exact script CodeSplash ran for example “Gaussian mtcars” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Bayesian regression model (Stan)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.model 1.0.1 · spec 188a0d6aba408b25
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.bayes import model as bm  # data, priors and summaries (twin of codesplashr cs_bayes_*)
from codesplash.ml.run import out_dir

# %% Data
df = pd.read_parquet("tests/parity/fixtures/mtcars.parquet", columns=["mpg", "wt", "am_f"])
n_input = len(df)
df["am_f"] = pd.Categorical(df["am_f"], categories=["automatic", "manual"])  # stored level order
df = df.dropna(subset=["mpg", "wt", "am_f"])  # listwise deletion over the analysis columns
df["am_f"] = df["am_f"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["mpg", "wt", "am_f"])  # infinite values stop the run (registry/errors.yaml)

outcome = "mpg"

# %% Model: the precompiled Stan program runs on a data file R writes byte for byte the same (identical draws)
fit = bm.fit_model(
    df,
    outcome=outcome,
    predictors=["wt", "am_f"],
    family="gaussian",
    trials=None,
    exposure=None,
    group=None,
    slopes=[],
    group2=None,
    nesting="nested",
    interactions="none",
    event_level=None,
    prior_dist="normal",
    prior_scale=2.5,
    prior_df=3,
    autoscale=True,
    intercept_scale=2.5,
    lkj=1,
    algorithm="nuts",
    chains=int(2),
    iter_warmup=int(300),
    iter_sampling=int(300),
    seed=int(1234),
    adapt_delta=0.8,
    max_treedepth=int(10),
    use_qr=False,
    prior_only=False,
    loo=True,
    ppc=True,
    cred=0.95,
    out_dir=out_dir("target/academy-parity/run-8142/bayes.model/gaussian-mtcars/out-python"),
)
values = fit["values"]
prep = fit["prep"]

# %% Result
cred = values["cred_level"]
fixed = [r for r in fit["rows"] if r["kind"] == "fixed"]
focus = next((r for r in fixed if r["term"] != "(Intercept)"), fixed[0] if fixed else fit["rows"][0])
label = bm.FAMILIES[prep.family]["label"]
what = "Prior predictive draws" if values["prior_only"] else "Posterior"
summary = (
    f"Bayesian {label.lower()} model of {outcome} (n = {values['n']}), {bm.ALGORITHM_LABELS[values['algorithm']]}. "
    f"{what}: {focus['term']} has median {focus['median']:.3g} ({cred:.0%} credible interval {focus['lower']:.3g} to {focus['upper']:.3g}); "
    f"P(> 0) = {focus['p_positive']:.2f}."
)
if values.get("rhat_max") is not None:
    summary += f" Largest R-hat {values['rhat_max']:.3f}"
    if values.get("n_divergent") is not None:
        summary += f", {values['n_divergent']} divergent transitions"
    summary += "."
if values.get("elpd_loo") is not None:
    summary += f" PSIS-LOO elpd = {values['elpd_loo']:.1f} (SE {values['elpd_loo_se']:.1f})."
statistics = [
    {"key": "focus_median", "label": f"{focus['term']} (posterior median)", "value": focus["median"]},
    {"key": "focus_cri", "label": f"{cred:.0%} credible interval", "value": [focus["lower"], focus["upper"]]},
    {"key": "focus_p_positive", "label": "P(effect > 0)", "value": focus["p_positive"]},
]
if values.get("rhat_max") is not None:
    statistics.append({"key": "rhat_max", "label": "Largest R-hat", "value": values["rhat_max"]})
if values.get("elpd_loo") is not None:
    statistics.append({"key": "elpd_loo", "label": "elpd (PSIS-LOO)", "value": values["elpd_loo"]})
if values.get("r2_median") is not None:
    statistics.append({"key": "r2_median", "label": "Bayesian R² (median)", "value": values["r2_median"]})
notes = [
    f"Outcome model: {label}" + (f"; event: {prep.event}" if prep.event and prep.family == "logistic" else "") + ".",
    "Credible intervals are equal-tailed posterior quantiles; P(> 0) is the share of draws above zero.",
    "Bayesian results are not p-values and are not entered in the multiple-testing ledger.",
] + fit["notes"]
cs.publish({
    "method": "bayes.model",
    "methodVersion": "1.0.1",
    "title": "Prior predictive check (Stan)" if values["prior_only"] else f"Bayesian {label.lower()} model (Stan)",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": values["n"],
    "summary": summary,
    "statistics": statistics,
    "tables": fit["tables"],
    "assumptions": fit["assumptions"],
    "warnings": warnings,
    "notes": notes,
    "values": values,
    "charts": fit["charts"],
    "artifacts": fit["artifacts"],
})
R

The exact script CodeSplash ran for example “Gaussian mtcars” · R version 4.5.1 (2025-06-13)

# Bayesian regression model (Stan)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bayes.model 1.0.1 · spec 188a0d6aba408b25
# Dataset: mtcars (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_bayes_fit_model (twin of codesplash.bayes.model) on the shared Stan programs (cs_stan_*)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/mtcars.parquet", col_select = c("mpg", "wt", "am_f")))
n_input <- nrow(df)
df[["am_f"]] <- factor(df[["am_f"]], levels = c("automatic", "manual"))  # stored level order
df <- df[stats::complete.cases(df[c("mpg", "wt", "am_f")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("mpg", "wt", "am_f"))  # infinite values stop the run (registry/errors.yaml)

outcome <- "mpg"

# %% Model: the precompiled Stan program runs on a data file Python writes byte for byte the same (identical draws)
fit <- cs_bayes_fit_model(
  df,
  outcome = outcome,
  predictors = c("wt", "am_f"),
  family = "gaussian",
  trials = NULL,
  exposure = NULL,
  group = NULL,
  slopes = c(),
  group2 = NULL,
  nesting = "nested",
  interactions = "none",
  event_level = NULL,
  prior_dist = "normal",
  prior_scale = 2.5,
  prior_df = 3,
  autoscale = TRUE,
  intercept_scale = 2.5,
  lkj = 1,
  algorithm = "nuts",
  chains = as.integer(2),
  iter_warmup = as.integer(300),
  iter_sampling = as.integer(300),
  seed = 1234,
  adapt_delta = 0.8,
  max_treedepth = as.integer(10),
  use_qr = FALSE,
  prior_only = FALSE,
  loo = TRUE,
  ppc = TRUE,
  cred = 0.95,
  out_dir = cs_ml_out_dir("target/academy-parity/run-8142/bayes.model/gaussian-mtcars/out-r")
)
values <- fit$values
prep <- fit$prep

# %% Result
cred <- values$cred_level
fixed <- Filter(function(r) r$kind == "fixed", fit$rows)
slopes_only <- Filter(function(r) r$term != "(Intercept)", fixed)
focus <- if (length(slopes_only)) slopes_only[[1]] else if (length(fixed)) fixed[[1]] else fit$rows[[1]]
labels <- c(gaussian = "Gaussian (normal)", student_t = "Student-t (robust)", logistic = "Logistic (Bernoulli)",
            binomial = "Logistic (successes of trials)", poisson = "Poisson", negbinomial = "Negative binomial",
            ordinal = "Ordinal (cumulative logit)")
label <- labels[[prep$family]]
alg_labels <- c(nuts = "NUTS (Hamiltonian Monte Carlo)", pathfinder = "Pathfinder (approximate)", meanfield = "ADVI mean-field (approximate)",
                fullrank = "ADVI full-rank (approximate)", laplace = "Laplace approximation at the mode")
what <- if (isTRUE(values$prior_only)) "Prior predictive draws" else "Posterior"
g3 <- function(x) formatC(signif(x, 3), digits = 3, format = "fg", flag = "#")
summary <- sprintf("Bayesian %s model of %s (n = %d), %s. %s: %s has median %s (%.0f%% credible interval %s to %s); P(> 0) = %.2f.",
                   tolower(label), outcome, values$n, alg_labels[[values$algorithm]], what, focus$term,
                   g3(focus$median), cred * 100, g3(focus$lower), g3(focus$upper), focus$p_positive)
if (!is.null(values$rhat_max) && is.finite(values$rhat_max)) {
  summary <- paste0(summary, sprintf(" Largest R-hat %.3f", values$rhat_max),
                    if (is.finite(values$n_divergent)) sprintf(", %d divergent transitions", as.integer(values$n_divergent)) else "", ".")
}
if (is.finite(values$elpd_loo)) summary <- paste0(summary, sprintf(" PSIS-LOO elpd = %.1f (SE %.1f).", values$elpd_loo, values$elpd_loo_se))
statistics <- list(
  list(key = "focus_median", label = sprintf("%s (posterior median)", focus$term), value = focus$median),
  list(key = "focus_cri", label = sprintf("%.0f%% credible interval", cred * 100), value = c(focus$lower, focus$upper)),
  list(key = "focus_p_positive", label = "P(effect > 0)", value = focus$p_positive)
)
if (!is.null(values$rhat_max) && is.finite(values$rhat_max)) statistics[[length(statistics) + 1L]] <- list(key = "rhat_max", label = "Largest R-hat", value = values$rhat_max)
if (is.finite(values$elpd_loo)) statistics[[length(statistics) + 1L]] <- list(key = "elpd_loo", label = "elpd (PSIS-LOO)", value = values$elpd_loo)
if (is.finite(values$r2_median)) statistics[[length(statistics) + 1L]] <- list(key = "r2_median", label = "Bayesian R² (median)", value = values$r2_median)
notes <- c(
  paste0("Outcome model: ", label, if (!is.null(prep$event) && prep$family == "logistic") paste0("; event: ", prep$event) else "", "."),
  "Credible intervals are equal-tailed posterior quantiles; P(> 0) is the share of draws above zero.",
  "Bayesian results are not p-values and are not entered in the multiple-testing ledger.",
  fit$notes
)
cs_publish(list(
  method = "bayes.model",
  methodVersion = "1.0.1",
  title = if (isTRUE(values$prior_only)) "Prior predictive check (Stan)" else sprintf("Bayesian %s model (Stan)", tolower(label)),
  engine = cs_engine_info("posterior", "loo"),
  n = values$n,
  summary = summary,
  statistics = statistics,
  tables = fit$tables,
  assumptions = fit$assumptions,
  warnings = warnings,
  notes = notes,
  values = values,
  charts = fit$charts,
  artifacts = fit$artifacts
))

Sources

  • Carpenter, B., Gelman, A., Hoffman, M. D., et al. (2017). Stan: A probabilistic programming language. Journal of Statistical Software, 76(1).
  • Hoffman, M. D., & Gelman, A. (2014). The No-U-Turn sampler. Journal of Machine Learning Research, 15, 1593–1623.
  • Vehtari, A., Gelman, A., Simpson, D., Carpenter, B., & Bürkner, P.-C. (2021). Rank-normalization, folding, and localization: An improved R-hat for assessing convergence of MCMC. Bayesian Analysis, 16(2), 667–718.
  • Vehtari, A., Gelman, A., & Gabry, J. (2017). Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27, 1413–1432.
  • Gelman, A., Goodrich, B., Gabry, J., & Vehtari, A. (2019). R-squared for Bayesian regression models. The American Statistician, 73(3), 307–309.
  • Gabry, J., & Goodrich, B. Prior distributions for rstanarm models (rstanarm vignette).
  • Betancourt, M. (2016). Diagnosing suboptimal cotangent disintegrations in Hamiltonian Monte Carlo. arXiv:1604.00695.

From the CodeSplash method registry · bayes.model v1.0.1.