How to use PosteriorParameters in sbi#
The PosteriorParameters classes in SBI are dataclasses used to initialize parameters for different types of posterior algorithms, when using the build_posterior method. This guide shows how to configure and use PosteriorParameters in your workflow.
sbi currently implements the following PosteriorParameters subclasses. Each subclass of PosteriorParameters holds parameters for a specific posterior sampling method.
DirectPosteriorParameters: used with DirectPosteriorImportanceSamplingPosteriorParameters: used with ImportanceSamplingPosteriorMCMCPosteriorParameters: used with MCMCPosteriorRejectionPosteriorParameters: used with RejectionPosteriorVectorFieldPosteriorParameters: : used with VectorFieldPosteriorVIPosteriorParameters: used with VIPosterior
Usage#
The example below uses MCMCPosteriorParameters for passing MCMC options to a posterior sampling via MCMC. You can follow a similar approach as the example below with your sbi workflow when using the other PosteriorParameters types.
import torch
from sbi.inference import NRE
from sbi.utils.torchutils import BoxUniform
def simulator(theta):
return 1.0 + theta + torch.randn(theta.shape, device=theta.device) * 0.1
num_dim = 3
prior = BoxUniform(low=-2 * torch.ones(num_dim), high=2 * torch.ones(num_dim))
theta = prior.sample((300,))
x = simulator(theta)
inference = NRE(prior=prior)
inference.append_simulations(theta, x)
inference.train();
Create an instance of MCMCPosteriorParameters with desired values to configure MCMC sampling.
from sbi.inference.posteriors import MCMCPosteriorParameters
params = MCMCPosteriorParameters(
method="slice_np_vectorized",
thin=1,
warmup_steps=100,
num_chains=4,
init_strategy="sir",
init_strategy_parameters={"num_candidate_samples": 1000},
num_workers=2,
mp_context="spawn"
)
Now pass the instance to build_posterior() using the posterior_parameters argument.
inference.build_posterior(posterior_parameters=params)
Modifying Parameters with .with_param()#
You can create a new copy with updated fields without mutating the original.
new_params = params.with_param(num_chains=8, warmup_steps=200)
inference.build_posterior(posterior_parameters=new_params)