8. Analysis pipelines¶
quivers.formulas compiles a regression formula in the notation of lme4 and brms (Bates et al., 2015; Bürkner, 2017) and a dataframe into a QVR program, and fits it. y ~ x models the response column y by an intercept and the predictor x, and (1 | g) adds an intercept for each level of g, drawn from a shared population distribution so that groups with little data are pulled toward the population mean (partial pooling, as in QVR chapter 3) (Gelman et al., 2013). Inspect the generated programs, fit Gaussian, hierarchical, ordinal, categorical, and mixture regressions, compare two models by PSIS-LOO, and run a posterior predictive check.
The main objects:
fitparses the formula against a dataframe, compiles it to aMonadicProgram, and runs the No-U-Turn Sampler (NUTS), Hamiltonian Monte Carlo (HMC), or stochastic variational inference (SVI). It returns aBayesianFit.- The posterior of a fit is an
MCMCResultfor NUTS and HMC, whose samples have shape(chain, draw)for each site, or a fittedGuidefor SVI. to_datatreeconverts anMCMCResultto the ArviZDataTreethat the diagnostics read.to_datatree_from_sviconverts SVI draws, andto_datatree_anyaccepts either.
Setup¶
The workflow needs the formulas, data, and diagnostics extras:
import numpy as np
import pandas as pd
import torch
from quivers.formulas import fit, formula_to_qvr
from quivers.diagnostics import to_datatree, compare, posterior_predictive_check
A first fit: Gaussian regression in one line¶
Simulate 200 rows with a known linear relation:
torch.manual_seed(0)
np.random.seed(0)
N = 200
x = np.random.randn(N)
y = 1.0 + 2.0 * x + 0.5 * np.random.randn(N)
df = pd.DataFrame({"y": y, "x": x})
Fit y ~ x with a Gaussian family by SVI:
Under method="svi", num_steps is the number of optimization steps and learning_rate the step size of the optimizer (default 1e-2). Under NUTS and HMC, num_warmup, num_samples, and num_chains set the chains, and SVI refuses them.
A BayesianFit has these fields:
| Field | Contents |
|---|---|
.formula |
The parsed Formula: columns, family, response. |
.program |
The compiled MonadicProgram. |
.posterior |
An MCMCResult (NUTS or HMC) or a Guide (SVI). |
.observations |
The observations dict used for inference: response values, data inputs, and group indices. |
The QVR program that the formula compiled to:
object Resp : FinSet 200
program model : Resp -> Resp
let intercept <- sample Normal(loc=0.0, scale=5.0)
let beta_x <- sample Normal(loc=0.0, scale=4.883378911472473)
let beta_x_per_row = beta_x * x
let sigma <- sample HalfCauchy(scale=2.0)
let eta = intercept + beta_x_per_row
let mu = eta
observe y : Resp <- Normal(loc=mu, scale=sigma)
return y
export model
The predictor values do not appear in the program: x is a data input, read from the observations at fit time. The default prior on a coefficient, Normal(0.0, 5.0), is divided by the root mean square of its column, which gives beta_x its scale of about 4.88. The intercept has no row index because its column is constant.
Emit the source without fitting:
import tempfile
from pathlib import Path
src = formula_to_qvr("y ~ x", data=df)
with tempfile.TemporaryDirectory() as tmp:
result.dump_qvr(Path(tmp) / "regression.qvr") # write the same source to disk
Recover the coefficients¶
Under SVI the posterior is an AutoNormalGuide. Compare the means of its draws with the true values (intercept 1.0, slope 2.0):
draws = [result.posterior.rsample(torch.zeros(1, 1)) for _ in range(200)]
ic = torch.stack([d["intercept"] for d in draws])
bx = torch.stack([d["beta_x"] for d in draws])
print(f"intercept (true 1.0): {ic.mean().item():.3f} ± {ic.std().item():.3f}")
print(f"beta_x (true 2.0): {bx.mean().item():.3f} ± {bx.std().item():.3f}")
The ± values are standard deviations of the guide's draws, the spread of the approximation. Whether that spread is accurate needs a reference, such as a well-mixed NUTS fit of the same model.
Predict on new rows¶
Pass a frame of covariates to predict without a response column:
future = pd.DataFrame({"x": [-1.0, 0.0, 1.0]})
future_mean = result.posterior_epred(new_data=future, num_samples=20, seed=7)
future_response = result.posterior_predict(new_data=future, num_samples=20, seed=7)
assert future_mean.shape == future_response.shape == (1, 20, 3)
The first result contains expected responses; the second adds response noise.
posterior_linpred instead exposes the linear predictor, with
transform=True for its inverse-link value. New rows reuse fitted transforms
and contrasts. Grouped models accept fitted group levels in any row order.
New or missing group identities require allow_new_levels=True;
sample_new_levels selects joint donor or fitted Gaussian/LKJ effects.
re_formula="~0" excludes varying effects by setting them to zero.
Responses and likelihood weights are unnecessary; offsets, exposures,
auxiliary predictors, and per-row trials still require
their columns. The new-row guide
gives a grouped distributional example and the neural-input contract.
Random effects: hierarchical model under SVI¶
Eight groups, each with its own intercept offset, and twelve rows per group:
torch.manual_seed(0)
np.random.seed(0)
N_g, N_per = 8, 12
g = np.repeat(np.arange(N_g), N_per)
alpha = np.random.randn(N_g) * 0.6 # group-level offsets
x = np.random.randn(N_g * N_per)
y = 1.5 + 0.7 * x + alpha[g] + 0.4 * np.random.randn(N_g * N_per)
df = pd.DataFrame({"y": y, "x": x, "g": g})
Add the group intercept (1 | g):
result = fit(
"y ~ x + (1 | g)",
data=df,
family="gaussian",
method="svi",
num_steps=4000,
seed=0,
)
print(result.qvr_source)
object Resp : FinSet 96
object g : FinSet 8
program model(g_idx : Int[Fin Resp]) : Resp -> Resp
let intercept <- sample Normal(loc=0.0, scale=5.0)
let beta_x <- sample Normal(loc=0.0, scale=5.019989651784464)
let beta_x_per_row = beta_x * x
let sigma_g_Intercept <- sample HalfNormal(scale=1.0)
let z_g_Intercept : g <- sample Normal(loc=0.0, scale=1.0)
let alpha_g = sigma_g_Intercept * z_g_Intercept
let alpha_g_per_row = alpha_g[g_idx]
let sigma <- sample HalfCauchy(scale=2.0)
let eta = intercept + beta_x_per_row + alpha_g_per_row
let mu = eta
observe y : Resp <- Normal(loc=mu, scale=sigma)
return y
export model
The group intercept becomes a scale sigma_g_Intercept with a HalfNormal prior, a plate z_g_Intercept of standard Normal draws over the levels of g, the offsets alpha_g = sigma_g_Intercept * z_g_Intercept, and the term alpha_g[g_idx] for each row, where g_idx, an input of the program, is the index map from rows to groups. This is the non-centered parameterization (Papaspiliopoulos et al., 2007): the offsets are computed from standardized draws rather than drawn as Normal(0, sigma_g_Intercept).
def mean_param(res, name, n=200):
draws = torch.stack(
[res.posterior.rsample(torch.zeros(1, 1))[name] for _ in range(n)]
)
return draws.mean().item(), draws.std().item()
for name, true in [
("intercept", 1.5),
("beta_x", 0.7),
("sigma_g_Intercept", 0.6),
("sigma", 0.4),
]:
m, s = mean_param(result, name)
print(f"{name:20s} (true {true:.2f}): {m:.3f} ± {s:.3f}")
intercept (true 1.50): 2.034 ± 0.037
beta_x (true 0.70): 0.641 ± 0.041
sigma_g_Intercept (true 0.60): 0.653 ± 0.040
sigma (true 0.40): 0.418 ± 0.032
The intercept is about 0.5 above its true value, far more than its reported spread of 0.04. The eight simulated offsets alpha have mean 0.53, and the data identify only the sum of the intercept and the mean offset, \(1.5 + 0.53 \approx 2.03\), which is what the fit recovers. The spread of 0.04 may still be too small, since a mean-field guide ignores the posterior correlation between the intercept and the offsets and tends to understate uncertainty (Blei et al., 2017). For a richer approximation pass guide=AutoMultivariateNormalGuide, and for sampling use method="nuts" and check its diagnostics.
Options: method, guide, reparameterize¶
method="nuts" | "hmc" | "svi". The default,"nuts", samples the posterior with the No-U-Turn Sampler and returns anMCMCResult."svi"fits aGuideby optimization, which can be faster on large models. Both need diagnostics.guide=Cls(SVI only). The default isAutoNormalGuide, a mean-field Normal. The alternatives includeAutoMultivariateNormalGuide(full covariance),AutoLowRankMultivariateNormalGuide(memory \(O(D \cdot \mathit{rank})\)),AutoLaplaceApproximation(a Normal at the MAP), andAutoIAFGuide(an inverse autoregressive flow), described in QVR chapter 6. Pass the class, not an instance:fit(..., guide=AutoMultivariateNormalGuide).reparameterize="noncentered" | "centered".fitandformula_to_qvrpass it to the formula compiler, andresult.qvr_sourceshows the program it produced.
Ordinal responses with thresholds for each rater¶
A cumulative (ordinal) model treats ordered categories as intervals of a latent continuous scale cut at ordered thresholds (McCullagh, 1980). The family cumulative learns the thresholds. With thresholds_by, each level of a grouping column gets its own spacing of the thresholds, partially pooled, beside crossed rater and item intercepts:
result = fit(
"rating ~ condition + (1 | rater) + (1 | item)",
data=ratings,
family="cumulative",
thresholds_by="rater",
method="svi",
num_steps=4000,
seed=0,
)
The response labels must be consecutive integers starting at zero. The generated program exponentiates log spacings, sums them cumulatively, and centers each rater's thresholds, so the thresholds are ordered in every draw, the rater intercept is a shift of location, and the thresholds describe how each rater uses the scale.
This combines one centered shape with one varying location per rater. The
compiler reuses the formula's rater intercept, or adds it when absent;
a binary cumulative model needs only that location coordinate.
result.posterior_thresholds(num_samples=100) exposes the effective row
profiles with chain, draw, row, and threshold axes. For nonproportional
cs(expr) terms, the compiler additionally constrains spacing to preserve
training-row ordering and retains fitted cutpoints during prediction.
The ordinal guide
explains the conditional slack priors and explicit new-group support policies.
Training with a neural predictor¶
A PyTorch module that produces one score for each row can enter the linear predictor additively:
net = torch.nn.Linear(feature_count, 1)
result = fit(
"rating ~ condition + (1 | rater) + (1 | item)",
data=ratings,
family="cumulative",
thresholds_by="rater",
predictor=net,
predictor_data=features,
method="svi",
num_steps=4000,
seed=0,
)
The optimizer updates the module's parameters together with the program's and the guide's. The generated QVR reads the module's output as the data input neural_eta, and the module itself is an attachment, held in the Python process and not part of the program. A predictor that is trained must thus use SVI. A frozen predictor also works with NUTS or HMC.
Unordered choices with varying effects¶
Encode the alternatives of an unordered response as consecutive integers starting at zero. Three choices with an intercept for each participant:
rng = np.random.default_rng(4)
N = 120
participant = np.repeat(np.arange(12), 10)
x = rng.normal(size=N)
logits = np.column_stack([
np.zeros(N),
-0.4 + 1.1 * x,
0.7 - 0.6 * x,
])
prob = np.exp(logits - logits.max(axis=1, keepdims=True))
prob /= prob.sum(axis=1, keepdims=True)
choice = np.array([rng.choice(3, p=row) for row in prob])
choice_data = pd.DataFrame({
"choice": choice,
"x": x,
"participant": participant,
})
The family categorical takes category zero as the reference and learns one coefficient vector for each other category:
choice_fit = fit(
"choice ~ x + (1 | participant)",
data=choice_data,
family="categorical",
method="svi",
num_steps=250,
seed=0,
)
The program builds an (N, 3) matrix of logits whose first column is zero and applies a softmax along the categories. Each fixed coefficient and each non-centered group effect has two entries, one for each non-reference category, so every term is a contrast with the reference category and the logits are identified.
A neural classifier may give all three logits or only the two non-reference ones. fit converts a full (N, 3) output to contrasts with the reference before adding it:
classifier = torch.nn.Linear(feature_count, 3)
choice_fit = fit(
"choice ~ condition + (1 | participant)",
data=choice_data,
family="categorical",
predictor=classifier,
predictor_data=features,
method="svi",
num_steps=3000,
)
A finite mixture of regressions¶
Each observation comes from one of three Gaussian components, and x shifts the component locations:
rng = np.random.default_rng(8)
N = 150
x = rng.normal(size=N)
component = rng.choice(3, size=N, p=[0.25, 0.5, 0.25])
offset = np.array([-2.5, 0.0, 2.5])
y = 0.8 * x + offset[component] + rng.normal(scale=0.4, size=N)
mixture_data = pd.DataFrame({"y": y, "x": x})
mixture_fit = fit(
"y ~ x",
data=mixture_data,
family="mixture",
mixture_components=3,
method="svi",
num_steps=250,
seed=0,
)
family="mixture" with mixture_components=3 is brms's mixture(gaussian, nmix = 3): each component has its own intercept, slope, and scale (mu1, sigma1, ...), and the mixing proportions share one Dirichlet simplex theta. Relabelling the components leaves the likelihood unchanged (Stephens, 2000), so the intercepts are ordered: the second and third are the first plus positive gaps, which removes the relabelled modes from the parameter space. MixtureNormal sums over the component assignment inside the likelihood, so the guide has only continuous sites, and mixture_fit.pp_mixture() returns each row's posterior component probabilities. The mixture guide covers heterogeneous components, predicted proportions, and the brms correspondence. The SVI budgets of 250 steps keep these fits short. Raise them and check diagnostics before reading either posterior.
Model comparison with PSIS-LOO¶
Fit a Bernoulli outcome with and without its predictor, with a small \(N\) and short chains:
torch.manual_seed(0)
np.random.seed(0)
N = 80
x = np.random.randn(N)
logit = -0.5 + 1.2 * x
y = np.random.binomial(1, 1 / (1 + np.exp(-logit))).astype(float)
df = pd.DataFrame({"y": y, "x": x})
res_with_x = fit(
"y ~ x", data=df, family="bernoulli", method="nuts",
num_warmup=100, num_samples=200, num_chains=2, seed=0,
)
res_intercept = fit(
"y ~ 1", data=df, family="bernoulli", method="nuts",
num_warmup=100, num_samples=200, num_chains=2, seed=0,
)
PSIS-LOO needs the log likelihood of each observation under each posterior draw
(Vehtari et al., 2017). analysis retains these raw response scores together with the
draws, so the likelihood calculation uses the model's checked response family:
analysis_with_x = res_with_x.analysis()
analysis_intercept = res_intercept.analysis()
y_obs = analysis_with_x.observed_data["y"]
ll_with_x = analysis_with_x.log_likelihood["y"]
ll_intercept = analysis_intercept.log_likelihood["y"]
Convert each posterior to a DataTree with an observed data group and a log likelihood group:
compare ranks the fits by PSIS-LOO and computes stacking weights (Yao et al., 2018):
table = compare({"with_x": analysis_with_x, "intercept_only": analysis_intercept}, round_to=2)
print(table.to_string())
rank elpd_diff dse p_worse diag_diff diag_elpd p elpd se weight
with_x 0 0.00 0.00 NaN 2.15 -45.38 4.88 0.85
intercept_only 1 -5.32 3.95 0.91 N < 100 1.01 -50.70 3.45 0.15
The model with the predictor ranks first and takes most of the stacking weight. Its advantage in elpd, 5.32, is about 1.3 standard errors (dse 3.95), and diag_diff warns that with fewer than 100 observations the normal approximation behind dse and p_worse is unreliable. The columns are explained in QVR chapter 8.
Posterior predictive checks¶
posterior_predictive_check computes the posterior predictive p-value \(\Pr(T(y^{\text{rep}}) \ge T(y))\) of a test statistic \(T\) (Gelman et al., 1996). BayesianFit.posterior_predict draws replicated responses from the fitted native model on its retained training rows. It keeps separate chain and draw axes and includes response noise. Compare the replicated mean with the observed mean:
pp = res_with_x.posterior_predict(seed=7) # (chain, draw, row)
idata = to_datatree(
res_with_x.posterior,
observed_data={"y": y_obs},
posterior_predictive={"y": pp},
)
ppc = posterior_predictive_check(idata, observed_name="y", statistic="mean")
print(f"observed mean: {float(ppc['observed']):.3f}")
print(f"predictive mean: {ppc['predictive_mean']:.3f}")
print(f"ppp (mean): {ppc['ppp']:.3f}")
A p-value near 0.5 puts the observed mean in the middle of the replicated distribution. Values near 0 or 1 suggest that the model misses the statistic. The mean of a Bernoulli outcome is a weak test, since a model with an intercept tends to reproduce it. The built-in statistics are mean, median, sd, var, min, max, mad, IQR, q05, and q95, and a callable is also accepted. sd and var divide by \(n - 1\), as in R. by= computes the check separately for each level of a named dimension of the data.
Recovering the formula¶
A BayesianFit keeps the parsed Formula beside the compiled program:
print(result.formula.formula) # original formula string
print(result.formula.response_name) # "y"
for col in result.formula.fixed_columns:
print(f" {col.qvr_name}: term={col.term!r}, is_intercept={col.is_intercept}")
The translation is a lens (FormulaToQVRModule): a pair of maps in which the forward map emits the QVR module together with a complement, FormulaData, holding what the module does not encode (the data arrays, the original column names, display labels, and the formula string). The backward map rebuilds the original Formula from the module and the complement, and lens.backward(module, complement) == formula holds, comparing every field, data arrays included. The formulas API reference gives the signatures.
Next¶
- The analysis guide documents
quivers.formulas,quivers.data, andquivers.diagnostics, including the prior override syntax and theDatasetSchemapath from a dataframe to a QVR program without a formula. - Chapter 5 builds and fits a
MonadicProgramwithout the formula compiler. - The DSL guide covers writing
.qvrprograms directly.
Cited sources¶
Douglas Bates, Martin Mächler, Ben Bolker, and Steve Walker. Fitting Linear Mixed-Effects Models Using lme4. Journal of Statistical Software, 2015. doi:10.18637/jss.v067.i01.
Paul-Christian Bürkner. brms: An R Package for Bayesian Multilevel Models Using Stan. Journal of Statistical Software, 2017. doi:10.18637/jss.v080.i01.
Andrew Gelman, John B. Carlin, Hal S. Stern, David B. Dunson, Aki Vehtari, and Donald B. Rubin. Bayesian Data Analysis. Chapman and Hall/CRC, 3 edition, 2013. ISBN 9781439840955. URL: https://www.routledge.com/Bayesian-Data-Analysis/Gelman-Carlin-Stern-Dunson-Vehtari-Rubin/p/book/9781439840955.
Omiros Papaspiliopoulos, Gareth O. Roberts, and Martin Sköld. A General Framework for the Parametrization of Hierarchical Models. Statistical Science, 22(1):59–73, 2007. URL: https://projecteuclid.org/journals/statistical-science/volume-22/issue-1/A-General-Framework-for-the-Parametrization-of-Hierarchical-Models/10.1214/088342307000000014.pdf, doi:10.1214/088342307000000014.
David M. Blei, Alp Kucukelbir, and Jon D. McAuliffe. Variational Inference: A Review for Statisticians. Journal of the American Statistical Association, 112(518):859–877, 2017. URL: https://doi.org/10.1080/01621459.2017.1285773, doi:10.1080/01621459.2017.1285773.
Peter McCullagh. Regression Models for Ordinal Data. Journal of the Royal Statistical Society: Series B (Methodological), 42(2):109–127, 1980. URL: https://academic.oup.com/jrsssb/article/42/2/109/7027621, doi:10.1111/j.2517-6161.1980.tb01109.x.
Matthew Stephens. Dealing with label switching in mixture models. Journal of the Royal Statistical Society: Series B (Statistical Methodology), 62(4):795–809, 2000. URL: https://rss.onlinelibrary.wiley.com/doi/abs/10.1111/1467-9868.00265, doi:10.1111/1467-9868.00265.
Aki Vehtari, Andrew Gelman, and Jonah Gabry. Practical Bayesian model evaluation using leave-one-out cross-validation and WAIC. Statistics and Computing, 27:1413–1432, 2017. URL: https://link.springer.com/article/10.1007/s11222-016-9696-4, doi:10.1007/s11222-016-9696-4.
Yuling Yao, Aki Vehtari, Daniel Simpson, and Andrew Gelman. Using Stacking to Average Bayesian Predictive Distributions (with Discussion). Bayesian Analysis, 13(3):917–1007, 2018. URL: https://doi.org/10.1214/17-BA1091, doi:10.1214/17-BA1091.
Andrew Gelman, Xiao-Li Meng, and Hal Stern. Posterior predictive assessment of model fitness via realized discrepancies. Statistica Sinica, 6(4):733–807, 1996. With discussion. URL: https://www3.stat.sinica.edu.tw/statistica/J6N4/J6N41/J6N41.htm.