bayespecon.diagnostics.bayesfactor.compile_log_posterior¶
- bayespecon.diagnostics.bayesfactor.compile_log_posterior(pymc_model)[source]¶
Compile a PyMC model’s log-posterior into a callable for bridge sampling.
This is the Python equivalent of the R
bridgesamplingpackage’s automaticlog_probextraction from Stan models. The compiled function evaluates the full unnormalized log-posterior \(\log p(y \mid \theta) p(\theta)\) at any parameter vector, including allpm.Potentialterms (e.g., Jacobians like \(\log|I - \rho W|\)).- Parameters:¶
- pymc_model : pymc.Model¶
A compiled PyMC model object (e.g.,
model._pymc_modelafter callingfit()).
- Returns:¶
log_posterior_fn (callable) – A function
f(theta_flat) -> floatthat evaluates the log unnormalized posterior at a flat parameter vector in the unconstrained (transformed) space.param_names (list of str) – Names of the free parameters in the unconstrained space (e.g.,
"sigma_log__"instead of"sigma"), matching the order intheta_flat.param_info (dict) – Dict with keys
"shapes"and"sizes"mapping parameter names to their shapes and total scalar sizes.constrained_to_unconstrained (callable) – A function
f(constrained_samples_dict) -> ndarraythat converts a dict of constrained posterior samples (as stored inidata.posterior, keyed by original parameter names like"sigma") into a flat array in the unconstrained space, in the same order asparam_names. This is needed because PyMC’scompile_logp()operates in the unconstrained space, but posterior samples are stored in the constrained space.
Examples
After fitting a model:
model = SAR(y=y, X=X, W=W) model.fit(draws=2000, idata_kwargs={"log_likelihood": True}) logp_fn, names, info, to_unconstrained = compile_log_posterior(model.pymc_model) # Convert constrained posterior samples to unconstrained space theta = to_unconstrained(model.inference_data.posterior) print(logp_fn(theta[0])) # evaluate at first sample