importance_resample#

bayesflow.utils.importance_resample(samples, log_ratio: ndarray | Callable[[Any], ndarray], *, method: Literal['psis', 'is'] = 'psis', r_eff: float = 1.0, rng: int | Generator | None = None, return_diagnostics: bool = False)[source]#

Correct posterior samples by importance resampling.

log_ratio is the log density ratio between the target and current posterior, up to an additive normalization constant. It can be a precomputed array or a callable receiving samples. For posterior approximation correction, use prior_log_prob(samples) + likelihood_log_prob(samples) - posterior_log_prob(samples). For a prior shift, the unchanged likelihood cancels, so use new_prior_log_prob(samples) - old_prior_log_prob(samples).

The ratio must have shape (*batch_shape, num_samples). Sample arrays must begin with the same dimensions, so native BayesFlow output with shape (num_conditions, num_samples, ...) works directly. Mapping values are resampled with shared indices to preserve joint draws. Callers are responsible for using a common parameterization and including model-specific Jacobians.

Parameters:
samplesnp.ndarray or mapping of np.ndarray

Posterior samples to correct.

log_rationp.ndarray or callable

Target-to-current posterior log density ratio at each draw.

method{“psis”, “is”}, optional

"psis" Pareto-smooths the ratios before resampling. "is" uses the normalized ratios directly. Default is "psis".

r_efffloat, optional

Relative sampling efficiency used by method="psis" to select the Pareto tail size. Independent BayesFlow samples use the default 1.0.

rngint or np.random.Generator, optional

Local random generator or seed used for systematic resampling.

return_diagnosticsbool, optional

If True, also return diagnostics. For method="psis", these contain "pareto_k" with shape batch_shape; for method="is", the diagnostics dictionary is empty.

Returns:
resampled

Values with the same structure and shapes as samples. Mapping values are gathered with shared indices to preserve joint draws.

diagnosticsdict, optional

Returned only when return_diagnostics=True.

References

Vehtari, A., Simpson, D., Gelman, A., Yao, Y., & Gabry, J. (2024). Pareto smoothed importance sampling. Journal of Machine Learning Research, 25(72), 1-58.