quivers.diagnostics.comparison¶
Leave-one-out (LOO) comparison
estimates how well each observation is predicted by a fit to the others (Vehtari et al., 2017).
Pareto-smoothed importance sampling (PSIS) approximates it from
posterior draws and
flags unstable importance weights (Vehtari et al., 2024), and stacking chooses weights for combining the
predictions of several models (Yao et al., 2018). The module computes pointwise PSIS-LOO and model
comparisons through ArviZ. compare accepts a mapping of model names to
PosteriorAnalysis objects or DataTrees. Retained analyses reuse their raw
likelihoods; compared analyses must agree on score units and observed response
values. Variational analyses retain their provenance and use relative efficiency
one, without correcting variational approximation error. The
shared analysis API describes the retained tensors.
comparison
¶
Model comparison and PSIS-LOO via ArviZ.
Thin wrappers around the canonical ArviZ entry points with quivers-typed inputs. No information-criterion or PSIS math lives here; ArviZ is the source of truth.
compare
¶
compare(fits: Mapping[str, DataTree | PosteriorAnalysis], *, method: Literal['stacking', 'BB-pseudo-BMA', 'pseudo-BMA'] = 'stacking', var_name: str | None = None, reference: str | None = None, round_to: int | Literal['auto', 'none', 'None'] | None = 'auto') -> object
Rank candidate models by expected log predictive density.
Delegates to ArviZ, which computes PSIS-LOO on each fit's log-likelihood group and combines the results into a ranked comparison table.
| PARAMETER | DESCRIPTION |
|---|---|
fits
|
Per-model retained analyses or DataTrees. Each supplies raw observation log likelihoods. Retained analyses are checked for matching response values and observation units before their PSIS-LOO estimates are ranked. Variational analyses use relative efficiency one.
TYPE:
|
method
|
Model-weight estimator. Default "stacking" follows Yao, Vehtari, Simpson, and Gelman (2018) Yao et al. (2018).
TYPE:
|
var_name
|
Observed variable in the log-likelihood group; required when a fit carries multiple log-likelihood variables.
TYPE:
|
reference
|
Fit name used as the reference for ELPD differences. Default is the top-ranked model.
TYPE:
|
round_to
|
ArviZ rounding policy. Default "auto" retains display rounding. An integer specifies decimal places, while "none" or "None" preserves full numeric precision. None uses ArviZ's configured default.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
DataFrame
|
ArviZ ranking table with one row per model. |
Source code in src/quivers/diagnostics/comparison.py
loo
¶
Estimate expected log predictive density with PSIS-LOO.
This thin wrapper delegates all computation to ArviZ. It preserves ArviZ's canonical log scale and, with pointwise=True, returns its per-observation elpd_i and pareto_k arrays unchanged, including nonfinite Pareto estimates. PSIS follows Vehtari, Simpson, Gelman, Yao, and Gabry (2024) Vehtari et al. (2024); its use for leave-one-out evaluation follows Vehtari, Gelman, and Gabry (2017) Vehtari et al. (2017).
| PARAMETER | DESCRIPTION |
|---|---|
fit
|
Fit containing posterior and log-likelihood groups.
TYPE:
|
pointwise
|
Whether to include one elpd_i and pareto_k value per observation. None uses ArviZ's configured default.
TYPE:
|
var_name
|
Log-likelihood variable to evaluate. Required when the log-likelihood group contains multiple variables.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ELPDData
|
ArviZ's canonical PSIS-LOO result. |
Source code in src/quivers/diagnostics/comparison.py
Bridge sampling¶
quivers.diagnostics.bridge estimates marginal likelihoods by bridge sampling
(Meng and Wong, 1996) as the R bridgesampling package does
(Gronau et al., 2017; Gronau et al., 2020), with the normal and warp-3
(Meng and Schilling, 2002) proposals, the package's effective sample size, iteration and
restart, and the approximate relative mean-squared error of
@fruhwirth2004estimating. The fit methods are described in the
analysis guide.
bridge
¶
Marginal likelihoods by bridge sampling, as the R bridgesampling package.
Bridge sampling [@meng1996simulating] estimates the normalizing constant
.. math::
p(y) = \int p(y \mid \theta)\, p(\theta)\, d\theta
of an unnormalized posterior :math:q(\theta) = p(y \mid \theta) p(\theta)
from posterior draws and draws of a normalized proposal :math:g. For any
bridge function :math:h,
.. math::
p(y) = \frac{E_g[q(\theta) h(\theta)]}{E_{\text{post}}[g(\theta) h(\theta)]},
and the asymptotically optimal :math:h gives the fixed-point iteration
.. math::
\hat r^{(t+1)} = \frac{N_1}{N_2}
\frac{\sum_{i=1}^{N_2} \ell_{2,i} / (s_1 \ell_{2,i} + s_2 \hat r^{(t)})}
{\sum_{j=1}^{N_1} 1 / (s_1 \ell_{1,j} + s_2 \hat r^{(t)})},
\qquad \ell = q / g,
with :math:s_1 = N_\text{eff} / (N_\text{eff} + N_2) and
:math:s_2 = N_2 / (N_\text{eff} + N_2). Following the tutorial of
@gronau2017tutorial and the bridgesampling package [@gronau2020bridgesampling]
that brms calls, the draws are on the unconstrained scale, the first half of
every chain fits the proposal, the second half enters the iteration, and the
proposal is either a multivariate normal with the fitted mean and covariance
("normal") or the standard normal after the third-order warp of
@meng2002warp ("warp3"), which matches the posterior's mean, covariance
and skewness. The relative mean-squared error of the "normal" estimator
follows @fruhwirth2004estimating.
Every step reproduces the R implementation: Matrix nearPD for the
proposal covariance, coda effectiveSize (an autoregressive spectral
estimate at frequency zero) for :math:N_\text{eff}, the median of
:math:\log \ell_1 as the numerical offset, the convergence criteria and
tolerances, and the restart from the geometric mean of the last two
iterates when the first scheme does not converge. Log-domain sums replace
the package's arbitrary-precision arithmetic. Proposal draws come from a
seeded Torch stream, so estimates agree with R only within their Monte
Carlo error.
BridgeMethod
¶
Proposal of the bridge sampler: a fitted normal or the warp-3 transformation.
BridgeRelativeError
didactic-model
¶
Bases: ValueModel
Approximate error of one "normal" bridge estimate.
| PARAMETER | DESCRIPTION |
|---|---|
re2
|
Approximate relative mean-squared error of the marginal likelihood
estimate, :math:
TYPE:
|
cv
|
Coefficient of variation, the square root of
TYPE:
|
percentage
property
¶
Return the coefficient of variation as a percentage label.
| RETURNS | DESCRIPTION |
|---|---|
str
|
|
BridgeRepetitionSpread
didactic-model
¶
Bases: ValueModel
Spread of the log marginal likelihood over independent repetitions.
| PARAMETER | DESCRIPTION |
|---|---|
min
|
Smallest and largest log marginal likelihood.
TYPE:
|
max
|
Smallest and largest log marginal likelihood.
TYPE:
|
iqr
|
Interquartile range (R
TYPE:
|
BridgeResult
didactic-model
¶
BridgeResult(*, logml_repetitions: tuple[float, ...], niter: tuple[int, ...], method: BridgeMethod, neff: float, q11: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), q12: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), q21: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), q22: Tensor = field(opaque=True, extras=OPAQUE_BY_IDENTITY), log_det_warp: float = 0.0, nonfinite_posterior: int = 0, nonfinite_proposal: int = 0)
Bases: ValueModel
A bridge-sampling estimate, as a bridge or bridge_list object.
| PARAMETER | DESCRIPTION |
|---|---|
logml_repetitions
|
Log marginal likelihood of each independent proposal draw.
TYPE:
|
niter
|
Fixed-point iterations of each repetition, counting a restart's
iterations after the
TYPE:
|
method
|
Proposal used.
TYPE:
|
neff
|
Effective sample size of the iteration draws used in
TYPE:
|
q11
|
Log unnormalized posterior at the iteration draws
TYPE:
|
q12
|
Log proposal density at the iteration draws
TYPE:
|
q21
|
Log unnormalized posterior at each repetition's proposal draws
TYPE:
|
q22
|
Log proposal density at each repetition's proposal draws
TYPE:
|
log_det_warp
|
Log determinant of the warp's Cholesky factor; zero for
TYPE:
|
nonfinite_posterior
|
Iteration draws whose log posterior was
TYPE:
|
nonfinite_proposal
|
Proposal draws whose log posterior was
TYPE:
|
logml
property
¶
Return the log marginal likelihood (median over repetitions).
| RETURNS | DESCRIPTION |
|---|---|
float
|
The estimate, as |
repetitions
property
¶
Return the number of independent proposal draws.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Repetition count. |
error_measures
¶
error_measures() -> BridgeRelativeError | BridgeRepetitionSpread
Return the estimator's approximate error, as error_measures.
| RETURNS | DESCRIPTION |
|---|---|
BridgeRelativeError or BridgeRepetitionSpread
|
The relative mean-squared error of one |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
For one |
Notes
With :math:p = q / \hat p(y) the normalized posterior,
:math:f_1 = p(\tilde\theta) / (s_1 p(\tilde\theta) + s_2 g(\tilde\theta))
at proposal draws and
:math:f_2 = g(\theta) / (s_1 p(\theta) + s_2 g(\theta)) at
posterior draws, both with :math:s_i = N_i / (N_1 + N_2),
.. math::
\widehat{RE}^2 = \frac{V(f_1)}{N_2 \bar f_1^2}
+ \frac{\rho_{f_2}(0)}{N_1} \frac{V(f_2)}{\bar f_2^2},
where :math:\rho_{f_2}(0) is the autoregressive spectral density
of :math:f_2 at frequency zero (coda spectrum0.ar).
Source code in src/quivers/diagnostics/bridge.py
ar_spectrum0
¶
Return the AR spectral density at frequency zero, as coda spectrum0.ar.
| PARAMETER | DESCRIPTION |
|---|---|
series
|
One real series of length at least two.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the series is not finite or has fewer than two values. |
Notes
The autocovariances are the biased (divisor n) estimates of R
acf; the Levinson-Durbin recursion gives the innovation variances
of orders zero to min(n - 1, floor(10 log10 n)). Cost is
O(n p + p^2) for order bound p.
Source code in src/quivers/diagnostics/bridge.py
effective_size
¶
Return coda effectiveSize of an mcmc.list.
| PARAMETER | DESCRIPTION |
|---|---|
chains
|
One
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Per-parameter effective sizes summed over chains, each chain
contributing |
Source code in src/quivers/diagnostics/bridge.py
near_pd
¶
Return the nearest positive-definite matrix, as Matrix nearPD.
| PARAMETER | DESCRIPTION |
|---|---|
matrix
|
Square real matrix.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
ndarray
|
Higham's alternating projection with Dykstra's correction
( |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the matrix is negative semidefinite or the projection does not converge within 100 iterations. |
Source code in src/quivers/diagnostics/bridge.py
bridge_sampler
¶
bridge_sampler(log_posterior: Callable[[ndarray], ndarray], chains: ndarray, *, method: BridgeMethod = 'normal', repetitions: int = 1, use_neff: bool = True, maxiter: int = 1000, seed: int = 0) -> BridgeResult
Estimate a log marginal likelihood from unconstrained posterior chains.
| PARAMETER | DESCRIPTION |
|---|---|
log_posterior
|
Log unnormalized posterior density on the unconstrained scale,
including every normalizing constant of the prior and likelihood and
the log Jacobian of the constraining transforms, evaluated row-wise
at
TYPE:
|
chains
|
Unconstrained posterior draws
TYPE:
|
method
|
Proposal: a normal with the moments of the fitting half, or the standard normal after the warp-3 transformation.
TYPE:
|
repetitions
|
Independent proposal draws, each giving one estimate.
TYPE:
|
use_neff
|
Use the median coda effective size of the iteration draws in
TYPE:
|
maxiter
|
Iteration bound of the fixed-point scheme.
TYPE:
|
seed
|
Seed of the proposal draws.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
BridgeResult
|
Estimates, iteration counts, and the retained log densities. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If the draws, method, or settings are invalid, a parameter is constant across draws, or the log posterior is undefined at every proposal draw. |
RuntimeError
|
If the scheme does not converge. |
Notes
Cost is N1 + R N2 log-posterior evaluations for "normal" and
twice that for "warp3", plus O(N D^2 + D^3) for the proposal and
O(N D p) for the effective sizes with autoregression order p.
Source code in src/quivers/diagnostics/bridge.py
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 | |
bayes_factor_from_logml
¶
Return the Bayes factor of model 1 over model 2.
| PARAMETER | DESCRIPTION |
|---|---|
logml1
|
Log marginal likelihoods.
TYPE:
|
logml2
|
Log marginal likelihoods.
TYPE:
|
log
|
Return the log Bayes factor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
float
|
:math: |
Source code in src/quivers/diagnostics/bridge.py
posterior_model_probabilities
¶
posterior_model_probabilities(logml: Mapping[str, float], *, prior_prob: Sequence[float] | None = None) -> dict[str, float]
Return posterior model probabilities, as bridgesampling::post_prob.
| PARAMETER | DESCRIPTION |
|---|---|
logml
|
Log marginal likelihood of each named model, at least two.
TYPE:
|
prior_prob
|
Prior model probabilities in the order of
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
dict[str, float]
|
:math: |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If fewer than two models are given, prior probabilities do not match
the models or do not sum to one (R |
Source code in src/quivers/diagnostics/bridge.py
Cited sources¶
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.
Aki Vehtari, Daniel Simpson, Andrew Gelman, Yuling Yao, and Jonah Gabry. Pareto Smoothed Importance Sampling. Journal of Machine Learning Research, 25(72):1–58, 2024. URL: https://www.jmlr.org/papers/v25/19-556.html.
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.
Xiao-Li Meng and Wing Hung Wong. Simulating Ratios of Normalizing Constants via a Simple Identity: A Theoretical Exploration. Statistica Sinica, 6(4):831–860, 1996. URL: https://www3.stat.sinica.edu.tw/statistica/j6n4/j6n43/j6n43.htm.
Quentin F. Gronau, Alexandra Sarafoglou, Dora Matzke, Alexander Ly, Udo Boehm, Maarten Marsman, David S. Leslie, Jonathan J. Forster, Eric-Jan Wagenmakers, and Helen Steingroever. A Tutorial on Bridge Sampling. Journal of Mathematical Psychology, 81:80–97, 2017. doi:10.1016/j.jmp.2017.09.005.
Quentin F. Gronau, Henrik Singmann, and Eric-Jan Wagenmakers. bridgesampling: An R Package for Estimating Normalizing Constants. Journal of Statistical Software, 2020. doi:10.18637/jss.v092.i10.
Xiao-Li Meng and Stephen Schilling. Warp Bridge Sampling. Journal of Computational and Graphical Statistics, 11(3):552–586, 2002. doi:10.1198/106186002457.