Inference¶
Training algorithms¶
NPE_A
¶
Bases: PosteriorEstimatorTrainer
Neural Posterior Estimation algorithm as in Papamakarios et al. (2016) [1].
[1] Fast epsilon-free Inference of Simulation Models with Bayesian Conditional Density Estimation, Papamakarios et al., NeurIPS 2016. https://arxiv.org/abs/1605.06376
Like all NPE methods, this method trains a deep neural density estimator to directly approximate the posterior. Also like all other NPE methods, in the first round, this density estimator is trained with a maximum-likelihood loss.
This class implements NPE-A. NPE-A trains across multiple rounds with a maximum-likelihood loss. This will make training converge to the proposal posterior instead of the true posterior. To correct for this, SNPE-A applies a post-hoc correction after training. This correction is performed analytically and requires Mixture of Gaussians (MoG) density estimators.
Note
In multi-round SNPE-A, the number of MoG components grows multiplicatively with each round: if the proposal has L components and the density estimator has K components, the corrected posterior has L×K components. For many rounds, consider using SNPE-C (APT) instead, which handles multi-round inference more efficiently.
Example:¶
::
import torch
from sbi.inference import NPE_A
from sbi.utils import BoxUniform
# 1. Setup simulator, prior, and observation
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
x_o = torch.randn(1, 3) # Observed data
def simulator(theta):
return theta + torch.randn_like(theta) * 0.1
# 2. Multi-round inference
inference = NPE_A(prior=prior, num_components=5)
proposal = prior
for round_idx in range(5):
theta = proposal.sample((100,))
x = simulator(theta)
density_estimator = inference.append_simulations(theta, x).train()
posterior = inference.build_posterior(density_estimator)
proposal = posterior.set_default_x(x_o)
# 3. Sample from final posterior
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/npe/npe_a.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 | |
__init__(prior=None, density_estimator='mdn_snpe_a', num_components=10, device='cpu', logging_level='WARNING', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialize NPE-A [1].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
A probability distribution that expresses prior knowledge about the
parameters, e.g. which ranges are meaningful for them. Any
object with |
None
|
density_estimator
|
Union[Literal['mdn_snpe_a'], ConditionalEstimatorBuilder[ConditionalDensityEstimator]]
|
If it is a string (only “mdn_snpe_a” is valid), use a
pre-configured mixture of densities network. Alternatively, a function
that builds a custom neural network, which adheres to
|
'mdn_snpe_a'
|
num_components
|
int
|
Number of components of the mixture of Gaussians. Note: In multi-round SNPE-A, the number of components grows multiplicatively with each round due to the analytical correction (L components in proposal × K components in density = L*K posterior components). |
10
|
device
|
str
|
Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”. |
'cpu'
|
logging_level
|
Union[int, str]
|
Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. |
'WARNING'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during training. |
True
|
Source code in sbi/inference/trainers/npe/npe_a.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
build_posterior(density_estimator=None, prior=None, sample_with='direct', **kwargs)
¶
Build posterior from the neural density estimator.
Returns an NPE_A_Posterior that applies the SNPE-A correction formula
p(θ|x) ∝ q(θ|x) × prior(θ) / proposal(θ)
Note
NPE_A only supports sample_with="direct". The corrected posterior is a
Mixture of Gaussians (MoG) which can be sampled directly and efficiently.
MCMC, VI, rejection, and importance sampling methods do not provide
benefits over direct MoG sampling and are therefore not supported.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
density_estimator
|
Optional[ConditionalDensityEstimator]
|
The density estimator that the posterior is based on.
If |
None
|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
sample_with
|
Literal['direct']
|
Must be “direct”. Other sampling methods are not supported. |
'direct'
|
**kwargs
|
Additional arguments passed to NPE_A_Posterior. |
{}
|
Returns:
| Type | Description |
|---|---|
NPE_A_Posterior
|
NPE_A_Posterior with the SNPE-A correction applied. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If sample_with is not “direct”. |
Source code in sbi/inference/trainers/npe/npe_a.py
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 | |
train(training_batch_size=200, learning_rate=0.0005, validation_fraction=0.1, stop_after_epochs=20, max_num_epochs=2 ** 31 - 1, clip_max_norm=5.0, calibration_kernel=None, resume_training=False, retrain_from_scratch=False, show_train_summary=False, dataloader_kwargs=None)
¶
Return density estimator that approximates the proposal posterior.
[1] Fast epsilon-free Inference of Simulation Models with Bayesian Conditional Density Estimation, Papamakarios et al., NeurIPS 2016, https://arxiv.org/abs/1605.06376.
Training is performed with maximum likelihood on samples from the latest round, which leads the algorithm to converge to the proposal posterior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
training_batch_size
|
int
|
Training batch size. |
200
|
learning_rate
|
float
|
Learning rate for Adam optimizer. |
0.0005
|
validation_fraction
|
float
|
The fraction of data to use for validation. |
0.1
|
stop_after_epochs
|
int
|
The number of epochs to wait for improvement on the validation set before terminating training. |
20
|
max_num_epochs
|
int
|
Maximum number of epochs to run. If reached, we stop
training even when the validation loss is still decreasing. Otherwise,
we train until validation loss increases (see also |
2 ** 31 - 1
|
clip_max_norm
|
Optional[float]
|
Value at which to clip the total gradient norm in order to prevent exploding gradients. Use None for no clipping. |
5.0
|
calibration_kernel
|
Optional[Callable]
|
A function to calibrate the loss with respect to the
simulations |
None
|
resume_training
|
bool
|
Can be used in case training time is limited, e.g. on a
cluster. If |
False
|
retrain_from_scratch
|
bool
|
Whether to retrain the conditional density estimator for the posterior from scratch each round. Not supported for SNPE-A. |
False
|
show_train_summary
|
bool
|
Whether to print the number of epochs and validation loss and leakage after the training. |
False
|
dataloader_kwargs
|
Optional[Dict]
|
Additional or updated kwargs to be passed to the training and validation dataloaders (like, e.g., a collate_fn) |
None
|
Returns:
| Type | Description |
|---|---|
ConditionalDensityEstimator
|
Density estimator that approximates the distribution \(p(\theta|x)\). |
Source code in sbi/inference/trainers/npe/npe_a.py
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
NPE_B
¶
Bases: PosteriorEstimatorTrainer
Neural Posterior Estimation algorithm (NPE-B) as in Lueckmann et al. (2017) [1].
NPE-B (also known as SNPE-B) trains a neural network to directly approximate the posterior \(p(\theta|x)\) using an importance-weighted loss. Unlike NPE-A, this importance weighting ensures convergence to the true posterior in multi-round inference, and it is not limited to Gaussian proposals. NPE-B can use flexible density estimators like normalizing flows.
For single-round inference, NPE-A, NPE-B, and NPE-C are equivalent and use plain NLL loss.
[1] Flexible statistical inference for mechanistic models of neural dynamics, Lueckmann, Gonçalves et al., NeurIPS 2017. https://arxiv.org/abs/1711.01861
Example:¶
::
import torch
from sbi.inference import NPE_B
from sbi.utils import BoxUniform
# 1. Setup simulator, prior, and observation
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
x_o = torch.randn(1, 3) # Observed data
def simulator(theta):
return theta + torch.randn_like(theta) * 0.1
# 2. Multi-round inference
inference = NPE_B(prior=prior)
proposal = prior
for round_idx in range(5):
theta = proposal.sample((100,))
x = simulator(theta)
density_estimator = inference.append_simulations(theta, x).train()
posterior = inference.build_posterior(density_estimator)
proposal = posterior.set_default_x(x_o)
# 3. Sample from final posterior
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/npe/npe_b.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
__init__(prior=None, density_estimator='maf', device='cpu', logging_level='WARNING', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialize NPE-B.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
A probability distribution that expresses prior knowledge about the parameters, e.g. which ranges are meaningful for them. |
None
|
density_estimator
|
Union[Literal['nsf', 'maf', 'mdn', 'made'], ConditionalEstimatorBuilder[ConditionalDensityEstimator]]
|
If it is a string, use a pre-configured network of the
provided type (one of nsf, maf, mdn, made). Alternatively, a function
that builds a custom neural network, which adheres to
|
'maf'
|
device
|
str
|
Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”. |
'cpu'
|
logging_level
|
Union[int, str]
|
Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. |
'WARNING'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during training. |
True
|
Source code in sbi/inference/trainers/npe/npe_b.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
NPE_C
¶
Bases: PosteriorEstimatorTrainer
Neural Posterior Estimation algorithm (NPE-C) as in Greenberg et al. (2019) [1].
NPE-C (also known as APT - Automatic Posterior Transformation, aka SNPE-C) trains a neural network over multiple rounds to directly approximate the posterior for a specific observation x_o. In the first round, NPE-C is equivalent to other NPE methods and is fully amortized (direct inference for any new observation). After the first round, NPE-C automatically selects between two loss variants depending on the chosen density estimator: the non-atomic loss (for Mixture of Gaussians) which is stable and avoids leakage, or the atomic loss (for flows) which is more flexible but may suffer from leakage issues.
For single-round inference, NPE-A, NPE-B, and NPE-C are equivalent and use plain NLL loss.
[1] Automatic Posterior Transformation for Likelihood-free Inference, Greenberg et al., ICML 2019, https://arxiv.org/abs/1905.07488.
Example:¶
::
import torch
from sbi.inference import NPE_C
from sbi.utils import BoxUniform
# 1. Setup simulator, prior, and observation
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
x_o = torch.randn(1, 3) # Observed data
def simulator(theta):
return theta + torch.randn_like(theta) * 0.1
# 2. Multi-round inference
inference = NPE_C(prior=prior)
proposal = prior
for round_idx in range(5):
theta = proposal.sample((100,))
x = simulator(theta)
density_estimator = inference.append_simulations(theta, x).train()
posterior = inference.build_posterior(density_estimator)
proposal = posterior.set_default_x(x_o)
# 3. Sample from final posterior
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/npe/npe_c.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 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 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 | |
__init__(prior=None, density_estimator='maf', device='cpu', logging_level='WARNING', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialize NPE-C.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
A probability distribution that expresses prior knowledge about the parameters, e.g. which ranges are meaningful for them. |
None
|
density_estimator
|
Union[Literal['nsf', 'maf', 'mdn', 'made'], ConditionalEstimatorBuilder[ConditionalDensityEstimator]]
|
If it is a string, use a pre-configured network of the
provided type (one of nsf, maf, mdn, made). Alternatively, a function
that builds a custom neural network, which adheres to
|
'maf'
|
device
|
str
|
Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”. |
'cpu'
|
logging_level
|
Union[int, str]
|
Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. |
'WARNING'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during training. |
True
|
Source code in sbi/inference/trainers/npe/npe_c.py
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
train(num_atoms=10, training_batch_size=200, learning_rate=0.0005, validation_fraction=0.1, stop_after_epochs=20, max_num_epochs=2 ** 31 - 1, clip_max_norm=5.0, calibration_kernel=None, resume_training=False, force_first_round_loss=False, discard_prior_samples=False, use_combined_loss=False, retrain_from_scratch=False, show_train_summary=False, dataloader_kwargs=None)
¶
Return density estimator that approximates the distribution \(p(\theta|x)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_atoms
|
int
|
Number of atoms to use for classification. |
10
|
training_batch_size
|
int
|
Training batch size. |
200
|
learning_rate
|
float
|
Learning rate for Adam optimizer. |
0.0005
|
validation_fraction
|
float
|
The fraction of data to use for validation. |
0.1
|
stop_after_epochs
|
int
|
The number of epochs to wait for improvement on the validation set before terminating training. |
20
|
max_num_epochs
|
int
|
Maximum number of epochs to run. If reached, we stop
training even when the validation loss is still decreasing. Otherwise,
we train until validation loss increases (see also
|
2 ** 31 - 1
|
clip_max_norm
|
Optional[float]
|
Value at which to clip the total gradient norm in order to prevent exploding gradients. Use None for no clipping. |
5.0
|
calibration_kernel
|
Optional[Callable]
|
A function to calibrate the loss with respect to the
simulations |
None
|
resume_training
|
bool
|
Can be used in case training time is limited, e.g. on a
cluster. If |
False
|
force_first_round_loss
|
bool
|
If |
False
|
discard_prior_samples
|
bool
|
Whether to discard samples simulated in round 1, i.e. from the prior. Training may be sped up by ignoring such less targeted samples. |
False
|
use_combined_loss
|
bool
|
Whether to train the neural net also on prior samples using maximum likelihood in addition to training it on all samples using atomic loss. The extra MLE loss helps prevent density leaking with bounded priors. |
False
|
retrain_from_scratch
|
bool
|
Whether to retrain the conditional density estimator for the posterior from scratch each round. |
False
|
show_train_summary
|
bool
|
Whether to print the number of epochs and validation loss and leakage after the training. |
False
|
dataloader_kwargs
|
Optional[Dict]
|
Additional or updated kwargs to be passed to the training and validation dataloaders (like, e.g., a collate_fn) |
None
|
Returns:
| Type | Description |
|---|---|
ConditionalDensityEstimator
|
Density estimator that approximates the distribution \(p(\theta|x)\). |
Source code in sbi/inference/trainers/npe/npe_c.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | |
FMPE
¶
Bases: VectorFieldTrainer
Flow Matching Posterior Estimation (FMPE) [1].
FMPE trains a continuous normalizing flow (CNF) to transform samples from the prior distribution to the posterior distribution using flow matching. Instead of maximum likelihood, it trains a vector field to match the marginal vector field of a conditional flow that interpolates between the prior and posterior. The neural network architecture for the vector field is not constrained like for flows and can be any expressive network. Sampling is performed by solving an ODE, which can be slower than flow-based NPE, but log_prob evaluation can also be slower.
NOTE: FMPE does not support multi-round inference with flexible proposals yet. You can try multi-round with truncated proposals, but this is not tested.
[1] Flow Matching for Generative Modeling, Lipman et al., ICLR 2023, https://arxiv.org/abs/2210.02747
Example:¶
::
import torch
from sbi.inference import FMPE
from sbi.utils import BoxUniform
# 1. Setup prior and simulate data
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
theta = prior.sample((100,))
x = theta + torch.randn_like(theta) * 0.1
# 2. Train flow matching estimator
inference = FMPE(prior=prior)
flow_estimator = inference.append_simulations(theta, x).train()
# 3. Build posterior (uses ODE solver for sampling)
posterior = inference.build_posterior(flow_estimator)
# 4. Sample from posterior
x_o = torch.randn(1, 3)
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/vfpe/fmpe.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
__init__(prior=None, vf_estimator='mlp', density_estimator=None, device='cpu', logging_level='WARNING', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialization method for the FMPE class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
vf_estimator
|
Union[Literal['mlp', 'ada_mlp', 'transformer', 'transformer_cross_attn'], ConditionalEstimatorBuilder[ConditionalVectorFieldEstimator]]
|
Neural network architecture used to learn the
vector field estimator. Can be a string (e.g. ‘mlp’, ‘ada_mlp’,
‘transformer’ or ‘transformer_cross_attn’) or a callable that implements
the |
'mlp'
|
density_estimator
|
Optional[ConditionalEstimatorBuilder[ConditionalVectorFieldEstimator]]
|
Deprecated. Use |
None
|
device
|
str
|
Device to use for training. |
'cpu'
|
logging_level
|
Union[int, str]
|
Logging level. |
'WARNING'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show progress bars. |
True
|
Source code in sbi/inference/trainers/vfpe/fmpe.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
build_posterior(vector_field_estimator=None, prior=None, sample_with='ode', vectorfield_sampling_parameters=None, posterior_parameters=None)
¶
Build posterior from the flow matching estimator.
Note that this is the same as the NPSE posterior, but the sample_with method is set to “ode” by default.
For FMPE, the posterior distribution that is returned here implements the following functionality over the raw neural density estimator: - correct the calculation of the log probability such that samples outside of the prior bounds have log probability -inf. - reject samples that lie outside of the prior bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_field_estimator
|
Optional[ConditionalVectorFieldEstimator]
|
The flow matching estimator that
the posterior is based on. If |
None
|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
sample_with
|
Literal['ode', 'sde']
|
Method to use for sampling from the posterior. Can be one of ‘sde’ (default) or ‘ode’. The ‘sde’ method uses the score to do a Langevin diffusion step, while the ‘ode’ method uses the score to define a probabilistic ODE and solves it with a numerical ODE solver. |
'ode'
|
vectorfield_sampling_parameters
|
Optional[Dict[str, Any]]
|
Additional keyword arguments passed to
|
None
|
posterior_parameters
|
Optional[VectorFieldPosteriorParameters]
|
Configuration passed to the init method for VectorFieldPosterior. |
None
|
Returns:
| Type | Description |
|---|---|
NeuralPosterior
|
Posterior \(p(\theta|x)\) with |
Source code in sbi/inference/trainers/vfpe/fmpe.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | |
NPSE
¶
Bases: VectorFieldTrainer
Neural Posterior Score Estimation (NPSE) [1, 2].
NPSE trains a neural network to estimate the score function (gradient of the log posterior) \(\nabla_\theta \log p(\theta|x)\) using denoising score matching. NPSE learns the score of a diffusion process that transforms the prior into the posterior. The neural network can be any expressive architecture. Sampling is performed using SDE solvers (e.g., Langevin dynamics) or ODE solvers, which can be slower than flow-based NPE, but expressiveness can be higher.
NOTE: NPSE does not support multi-round inference with flexible proposals yet. You can try multi-round with truncated proposals, but this is not tested.
[1] Score modeling for simulation-based inference, Geffner et al., ICML 2023. [2] Sequential neural score estimation: Likelihood-free inference with conditional score based diffusion models, Sharrock et al., ICML 2024.
Example:¶
::
import torch
from sbi.inference import NPSE
from sbi.utils import BoxUniform
# 1. Setup prior and simulate data
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
theta = prior.sample((100,))
x = theta + torch.randn_like(theta) * 0.1
# 2. Train score estimator
inference = NPSE(prior=prior, sde_type="ve")
score_estimator = inference.append_simulations(theta, x).train()
# 3. Build posterior (uses SDE solver by default)
posterior = inference.build_posterior(score_estimator)
# 4. Sample from posterior using Langevin dynamics
x_o = torch.randn(1, 3)
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/vfpe/npse.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
__init__(prior=None, vf_estimator='mlp', score_estimator=None, density_estimator=None, sde_type='ve', device='cpu', logging_level='WARNING', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialize Neural Posterior Score Estimation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
vf_estimator
|
Union[Literal['mlp', 'ada_mlp', 'transformer', 'transformer_cross_attn'], ConditionalEstimatorBuilder[ConditionalVectorFieldEstimator]]
|
Neural network architecture for the
vector field estimator aiming to estimate the marginal scores of the
target diffusion process. Can be a string (e.g. ‘mlp’, ‘ada_mlp’,
‘transformer’ or ‘transformer_cross_attn’) or a callable that implements
the |
'mlp'
|
score_estimator
|
Optional[Union[Literal['mlp', 'ada_mlp', 'transformer', 'transformer_cross_attn'], ConditionalEstimatorBuilder[ConditionalVectorFieldEstimator]]]
|
Deprecated, use |
None
|
density_estimator
|
Optional[ConditionalEstimatorBuilder[ConditionalVectorFieldEstimator]]
|
Deprecated, use |
None
|
sde_type
|
Literal['vp', 've', 'subvp']
|
Type of SDE to use. Must be one of [‘vp’, ‘ve’, ‘subvp’].
Only used when |
've'
|
device
|
str
|
Device to run the training on. |
'cpu'
|
logging_level
|
Union[int, str]
|
Logging level for the training. Can be an integer or a string. |
'WARNING'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show progress bars during training. |
True
|
References
- Geffner, Tomas, George Papamakarios, and Andriy Mnih. “Score modeling for simulation-based inference.” ICML 2023.
- Sharrock, Louis, et al. “Sequential neural score estimation: Likelihood- free inference with conditional score based diffusion models.” ICML 2024
Source code in sbi/inference/trainers/vfpe/npse.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 | |
build_posterior(vector_field_estimator=None, prior=None, sample_with='sde', vectorfield_sampling_parameters=None, posterior_parameters=None)
¶
Build posterior from the vector field estimator.
Note that this is the same as the FMPE posterior, but the sample_with method is set to “sde” by default.
For NPSE, the posterior distribution that is returned here implements the following functionality over the raw neural density estimator: - correct the calculation of the log probability such that samples outside of the prior bounds have log probability -inf. - reject samples that lie outside of the prior bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vector_field_estimator
|
Optional[ConditionalVectorFieldEstimator]
|
The vector field estimator that the posterior is
based on. If |
None
|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
sample_with
|
Literal['ode', 'sde']
|
Method to use for sampling from the posterior. Can be one of ‘sde’ (default) or ‘ode’. The ‘sde’ method uses the score to do a Langevin diffusion step, while the ‘ode’ method solves a probabilistic ODE with a numerical ODE solver. |
'sde'
|
vectorfield_sampling_parameters
|
Optional[Dict[str, Any]]
|
Additional keyword arguments passed to
|
None
|
posterior_parameters
|
Optional[VectorFieldPosteriorParameters]
|
Configuration passed to the init method for VectorFieldPosterior. |
None
|
Returns:
| Type | Description |
|---|---|
NeuralPosterior
|
Posterior \(p(\theta|x)\) with |
Source code in sbi/inference/trainers/vfpe/npse.py
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 | |
NLE_A
¶
Bases: LikelihoodEstimatorTrainer
Neural Likelihood Estimation (NLE) as in Papamakarios et al. (2019) [1].
NLE trains a neural network to approximate the likelihood \(p(x|\theta)\) using a conditional density estimator (normalizing flow). Unlike NPE methods, which directly estimate the posterior, NLE estimates the likelihood.
NLE can be run multi-round without need for correction, but requires running potentially expensive posterior sampling in each round.
[1] Sequential Neural Likelihood: Fast Likelihood-free Inference with Autoregressive Flows, Papamakarios et al., AISTATS 2019, https://arxiv.org/abs/1805.07226
Example:¶
::
import torch
from sbi.inference import NLE_A
from sbi.utils import BoxUniform
# 1. Setup prior and simulate data
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
theta = prior.sample((100,))
x = theta + torch.randn_like(theta) * 0.1
# 2. Train likelihood estimator
inference = NLE_A(prior=prior)
likelihood_estimator = inference.append_simulations(theta, x).train()
# 3. Build posterior (uses MCMC for sampling)
posterior = inference.build_posterior(likelihood_estimator)
# 4. Sample from posterior
x_o = torch.randn(1, 3)
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/nle/nle_a.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
__init__(prior=None, density_estimator='maf', device='cpu', logging_level='WARNING', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialize Neural Likelihood Estimation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
A probability distribution that expresses prior knowledge about the
parameters, e.g. which ranges are meaningful for them. If |
None
|
density_estimator
|
Union[Literal['nsf', 'maf', 'mdn', 'made'], ConditionalEstimatorBuilder[ConditionalDensityEstimator]]
|
If it is a string, use a pre-configured network of the
provided type (one of nsf, maf, mdn, made). Alternatively, a function
that builds a custom neural network, which adheres to
|
'maf'
|
device
|
str
|
Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”. |
'cpu'
|
logging_level
|
Union[int, str]
|
Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. |
'WARNING'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during simulation and sampling. |
True
|
Source code in sbi/inference/trainers/nle/nle_a.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
NRE_A
¶
Bases: RatioEstimatorTrainer
Neural Ratio Estimation (NRE-A / AALR) as in Hermans et al. (2020) [1].
NRE-A trains a neural classifier to estimate the likelihood-to-evidence ratio \(r(\theta, x) = p(x|\theta) / p(x)\) by distinguishing between samples from the joint distribution \(p(\theta, x)\) and samples from the marginals \(p(\theta)p(x)\). Posterior sampling is then performed via MCMC, rejection sampling, or variational inference using the estimated ratio.
NRE can be run multi-round without need for correction, but requires running potentially expensive posterior sampling in each round.
[1] Likelihood-free MCMC with Amortized Approximate Likelihood Ratios, Hermans et al., ICML 2020, https://arxiv.org/abs/1903.04057
Example:¶
::
import torch
from sbi.inference import NRE_A
from sbi.utils import BoxUniform
# 1. Setup prior and simulate data
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
theta = prior.sample((100,))
x = theta + torch.randn_like(theta) * 0.1
# 2. Train ratio estimator
inference = NRE_A(prior=prior)
ratio_estimator = inference.append_simulations(theta, x).train()
# 3. Build posterior (uses MCMC or rejection sampling)
posterior = inference.build_posterior(ratio_estimator)
# 4. Sample from posterior
x_o = torch.randn(1, 3)
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/nre/nre_a.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
__init__(prior=None, classifier='resnet', device='cpu', logging_level='warning', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialize NRE_A.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
A probability distribution that expresses prior knowledge about the
parameters, e.g. which ranges are meaningful for them. If |
None
|
classifier
|
Union[str, ConditionalEstimatorBuilder[RatioEstimator]]
|
Classifier trained to approximate likelihood ratios. If it is
a string, use a pre-configured network of the provided type (one of
linear, mlp, resnet), or a callable that implements the
|
'resnet'
|
device
|
str
|
Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”. |
'cpu'
|
logging_level
|
Union[int, str]
|
Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. |
'warning'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during simulation and sampling. |
True
|
Source code in sbi/inference/trainers/nre/nre_a.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
train(training_batch_size=200, learning_rate=0.0005, validation_fraction=0.1, stop_after_epochs=20, max_num_epochs=2 ** 31 - 1, clip_max_norm=5.0, resume_training=False, discard_prior_samples=False, retrain_from_scratch=False, show_train_summary=False, dataloader_kwargs=None, loss_kwargs=None)
¶
Return classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
training_batch_size
|
int
|
Training batch size. |
200
|
learning_rate
|
float
|
Learning rate for Adam optimizer. |
0.0005
|
validation_fraction
|
float
|
The fraction of data to use for validation. |
0.1
|
stop_after_epochs
|
int
|
The number of epochs to wait for improvement on the validation set before terminating training. |
20
|
max_num_epochs
|
int
|
Maximum number of epochs to run. If reached, we stop
training even when the validation loss is still decreasing. Otherwise,
we train until validation loss increases (see also |
2 ** 31 - 1
|
clip_max_norm
|
Optional[float]
|
Value at which to clip the total gradient norm in order to prevent exploding gradients. Use None for no clipping. |
5.0
|
resume_training
|
bool
|
Can be used in case training time is limited, e.g. on a
cluster. If |
False
|
discard_prior_samples
|
bool
|
Whether to discard samples simulated in round 1, i.e. from the prior. Training may be sped up by ignoring such less targeted samples. |
False
|
retrain_from_scratch
|
bool
|
Whether to retrain the conditional density estimator for the posterior from scratch each round. |
False
|
show_train_summary
|
bool
|
Whether to print the number of epochs and validation loss and leakage after the training. |
False
|
dataloader_kwargs
|
Optional[Dict]
|
Additional or updated kwargs to be passed to the training and validation dataloaders (like, e.g., a collate_fn) |
None
|
loss_kwargs
|
Optional[LossArgsNRE_A]
|
Additional or updated kwargs to be passed to the self._loss fn. |
None
|
Returns:
| Type | Description |
|---|---|
RatioEstimator
|
Classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\). |
Source code in sbi/inference/trainers/nre/nre_a.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 | |
NRE_B
¶
Bases: RatioEstimatorTrainer
Neural Ratio Estimation (NRE-B / SRE) as in Durkan et al. (2020) [1].
NRE-B is an extension of NRE-A that trains a neural classifier using a contrastive (1-out-of-K) loss to estimate the likelihood-to-evidence ratio. Instead of binary classification, it contrasts one sample from the joint \(p(\theta, x)\) against \(K-1\) samples from the marginals \(p(\theta)p(x)\). This multi-class formulation improves training stability compared to NRE-A.
NRE can be run multi-round without need for correction, but requires running potentially expensive posterior sampling in each round.
[1] On Contrastive Learning for Likelihood-free Inference, Durkan et al., ICML 2020, https://arxiv.org/pdf/2002.03712
Example:¶
::
import torch
from sbi.inference import NRE_B
from sbi.utils import BoxUniform
# 1. Setup prior and simulate data
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
theta = prior.sample((100,))
x = theta + torch.randn_like(theta) * 0.1
# 2. Train ratio estimator with contrastive loss
inference = NRE_B(prior=prior)
ratio_estimator = inference.append_simulations(theta, x).train(num_atoms=10)
# 3. Build posterior
posterior = inference.build_posterior(ratio_estimator)
# 4. Sample from posterior
x_o = torch.randn(1, 3)
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/nre/nre_b.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
__init__(prior=None, classifier='resnet', device='cpu', logging_level='warning', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialize NRE_B.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
A probability distribution that expresses prior knowledge about the
parameters, e.g. which ranges are meaningful for them. If |
None
|
classifier
|
Union[str, ConditionalEstimatorBuilder[RatioEstimator]]
|
Classifier trained to approximate likelihood ratios. If it is
a string, use a pre-configured network of the provided type (one of
linear, mlp, resnet), or a callable that implements the
|
'resnet'
|
device
|
str
|
Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”. |
'cpu'
|
logging_level
|
Union[int, str]
|
Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. |
'warning'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during simulation and sampling. |
True
|
Source code in sbi/inference/trainers/nre/nre_b.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 | |
train(num_atoms=10, training_batch_size=200, learning_rate=0.0005, validation_fraction=0.1, stop_after_epochs=20, max_num_epochs=2 ** 31 - 1, clip_max_norm=5.0, resume_training=False, discard_prior_samples=False, retrain_from_scratch=False, show_train_summary=False, dataloader_kwargs=None)
¶
Return classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_atoms
|
int
|
Number of atoms to use for classification. |
10
|
training_batch_size
|
int
|
Training batch size. |
200
|
learning_rate
|
float
|
Learning rate for Adam optimizer. |
0.0005
|
validation_fraction
|
float
|
The fraction of data to use for validation. |
0.1
|
stop_after_epochs
|
int
|
The number of epochs to wait for improvement on the validation set before terminating training. |
20
|
max_num_epochs
|
int
|
Maximum number of epochs to run. If reached, we stop
training even when the validation loss is still decreasing. Otherwise,
we train until validation loss increases (see also |
2 ** 31 - 1
|
clip_max_norm
|
Optional[float]
|
Value at which to clip the total gradient norm in order to prevent exploding gradients. Use None for no clipping. |
5.0
|
resume_training
|
bool
|
Can be used in case training time is limited, e.g. on a
cluster. If |
False
|
discard_prior_samples
|
bool
|
Whether to discard samples simulated in round 1, i.e. from the prior. Training may be sped up by ignoring such less targeted samples. |
False
|
retrain_from_scratch
|
bool
|
Whether to retrain the conditional density estimator for the posterior from scratch each round. |
False
|
show_train_summary
|
bool
|
Whether to print the number of epochs and validation loss and leakage after the training. |
False
|
dataloader_kwargs
|
Optional[Dict]
|
Additional or updated kwargs to be passed to the training and validation dataloaders (like, e.g., a collate_fn) |
None
|
Returns:
| Type | Description |
|---|---|
RatioEstimator
|
Classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\). |
Source code in sbi/inference/trainers/nre/nre_b.py
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
NRE_C
¶
Bases: RatioEstimatorTrainer
Neural Ratio Estimation (NRE-C / CNRE) as in Miller et al. (2022) [1].
NRE-C generalizes NRE-A and NRE-B using a “multi-class sigmoid” loss that ensures the estimated ratio \(p(\theta,x)/p(\theta)p(x)\) is exact at optimum in the first round. This addresses the issue that NRE-B’s ratio is only defined up to an arbitrary function of \(x\). NRE-C provides more accurate ratio estimates while maintaining the benefits of contrastive learning.
[1] Contrastive Neural Ratio Estimation, Benjamin Kurt Miller, et al., NeurIPS 2022, https://arxiv.org/abs/2210.06170
Example:¶
::
import torch
from sbi.inference import NRE_C
from sbi.utils import BoxUniform
# 1. Setup prior and simulate data
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
theta = prior.sample((100,))
x = theta + torch.randn_like(theta) * 0.1
# 2. Train ratio estimator
inference = NRE_C(prior=prior)
ratio_estimator = inference.append_simulations(theta, x).train(num_classes=5)
# 3. Build posterior
posterior = inference.build_posterior(ratio_estimator)
# 4. Sample from posterior
x_o = torch.randn(1, 3)
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/nre/nre_c.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
__init__(prior=None, classifier='resnet', device='cpu', logging_level='warning', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Initialize NRE-C.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
A probability distribution that expresses prior knowledge about the
parameters, e.g. which ranges are meaningful for them. If |
None
|
classifier
|
Union[str, ConditionalEstimatorBuilder[RatioEstimator]]
|
Classifier trained to approximate likelihood ratios. If it is
a string, use a pre-configured network of the provided type (one of
linear, mlp, resnet), or a callable that implements the
|
'resnet'
|
device
|
str
|
Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”. |
'cpu'
|
logging_level
|
Union[int, str]
|
Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. |
'warning'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during simulation and sampling. |
True
|
Source code in sbi/inference/trainers/nre/nre_c.py
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | |
train(num_classes=5, gamma=1.0, training_batch_size=200, learning_rate=0.0005, validation_fraction=0.1, stop_after_epochs=20, max_num_epochs=2 ** 31 - 1, clip_max_norm=5.0, resume_training=False, discard_prior_samples=False, retrain_from_scratch=False, show_train_summary=False, dataloader_kwargs=None)
¶
Return classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_classes
|
int
|
Number of theta to classify against, corresponds to \(K\) in
Contrastive Neural Ratio Estimation. Minimum value is 1. Similar to
|
5
|
gamma
|
float
|
Determines the relative weight of the sum of all \(K\) dependently drawn classes against the marginally drawn one. Specifically, \(p(y=k) :=p_K\), \(p(y=0) := p_0\), \(p_0 = 1 - K p_K\), and finally \(\gamma := K p_K / p_0\). |
1.0
|
training_batch_size
|
int
|
Training batch size. |
200
|
learning_rate
|
float
|
Learning rate for Adam optimizer. |
0.0005
|
validation_fraction
|
float
|
The fraction of data to use for validation. |
0.1
|
stop_after_epochs
|
int
|
The number of epochs to wait for improvement on the validation set before terminating training. |
20
|
max_num_epochs
|
int
|
Maximum number of epochs to run. If reached, we stop
training even when the validation loss is still decreasing. Otherwise,
we train until validation loss increases (see also |
2 ** 31 - 1
|
clip_max_norm
|
Optional[float]
|
Value at which to clip the total gradient norm in order to prevent exploding gradients. Use None for no clipping. |
5.0
|
exclude_invalid_x
|
Whether to exclude simulation outputs |
required | |
resume_training
|
bool
|
Can be used in case training time is limited, e.g. on a
cluster. If |
False
|
discard_prior_samples
|
bool
|
Whether to discard samples simulated in round 1, i.e. from the prior. Training may be sped up by ignoring such less targeted samples. |
False
|
retrain_from_scratch
|
bool
|
Whether to retrain the conditional density estimator for the posterior from scratch each round. |
False
|
show_train_summary
|
bool
|
Whether to print the number of epochs and validation loss and leakage after the training. |
False
|
dataloader_kwargs
|
Optional[Dict]
|
Additional or updated kwargs to be passed to the training and validation dataloaders (like, e.g., a collate_fn) |
None
|
Returns:
| Type | Description |
|---|---|
RatioEstimator
|
Classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\). |
Source code in sbi/inference/trainers/nre/nre_c.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
BNRE
¶
Bases: NRE_A
Balanced Neural Ratio Estimation (BNRE) as in Delaunoy et al. (2022) [1].
BNRE is a variation of NRE-A that adds a balancing regularizer to the binary cross-entropy loss. This regularizer encourages the classifier to predict equal probabilities for joint and marginal samples on average, which can lead to more conservative and reliable posterior approximations. BNRE is particularly useful when robustness is prioritized over tightness of the posterior.
NRE can be run multi-round without need for correction, but requires running potentially expensive posterior sampling in each round.
[1] Towards Reliable Simulation-Based Inference with Balanced Neural Ratio Estimation, Delaunoy, A., Hermans, J., Rozet, F., Wehenkel, A., & Louppe, G., NeurIPS 2022. https://arxiv.org/abs/2208.13624
Example:¶
::
import torch
from sbi.inference import BNRE
from sbi.utils import BoxUniform
# 1. Setup prior and simulate data
prior = BoxUniform(low=torch.zeros(3), high=torch.ones(3))
theta = prior.sample((100,))
x = theta + torch.randn_like(theta) * 0.1
# 2. Train balanced ratio estimator
inference = BNRE(prior=prior)
# Note: regularization_strength needs to be tuned carefully for your problem
ratio_estimator = inference.append_simulations(theta, x).train(
regularization_strength=100.0
)
# 3. Build posterior
posterior = inference.build_posterior(ratio_estimator)
# 4. Sample from posterior
x_o = torch.randn(1, 3)
samples = posterior.sample((1000,), x=x_o)
Source code in sbi/inference/trainers/nre/bnre.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
__init__(prior=None, classifier='resnet', device='cpu', logging_level='warning', summary_writer=None, tracker=None, show_progress_bars=True)
¶
Balanced neural ratio estimation (BNRE).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
Optional[Distribution]
|
A probability distribution that expresses prior knowledge about the
parameters, e.g. which ranges are meaningful for them. If |
None
|
classifier
|
Union[str, ConditionalEstimatorBuilder[RatioEstimator]]
|
Classifier trained to approximate likelihood ratios. If it is
a string, use a pre-configured network of the provided type (one of
linear, mlp, resnet), or a callable that implements the
|
'resnet'
|
device
|
str
|
Training device, e.g., “cpu”, “cuda” or “cuda:{0, 1, …}”. |
'cpu'
|
logging_level
|
Union[int, str]
|
Minimum severity of messages to log. One of the strings INFO, WARNING, DEBUG, ERROR and CRITICAL. |
'warning'
|
summary_writer
|
Optional[SummaryWriter]
|
Deprecated alias for the TensorBoard summary writer.
Use |
None
|
tracker
|
Optional[Tracker]
|
Tracking adapter used to log training metrics. If None, a TensorBoard tracker is used with a default log directory. |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during simulation and sampling. |
True
|
Source code in sbi/inference/trainers/nre/bnre.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | |
train(regularization_strength=100.0, training_batch_size=200, learning_rate=0.0005, validation_fraction=0.1, stop_after_epochs=20, max_num_epochs=2 ** 31 - 1, clip_max_norm=5.0, resume_training=False, discard_prior_samples=False, retrain_from_scratch=False, show_train_summary=False, dataloader_kwargs=None)
¶
Return classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\). Args:
regularization_strength: The multiplicative coefficient applied to the
balancing regularizer ($\lambda$).
training_batch_size: Training batch size.
learning_rate: Learning rate for Adam optimizer.
validation_fraction: The fraction of data to use for validation.
stop_after_epochs: The number of epochs to wait for improvement on the
validation set before terminating training.
max_num_epochs: Maximum number of epochs to run. If reached, we stop
training even when the validation loss is still decreasing. Otherwise,
we train until validation loss increases (see also `stop_after_epochs`).
clip_max_norm: Value at which to clip the total gradient norm in order to
prevent exploding gradients. Use None for no clipping.
exclude_invalid_x: Whether to exclude simulation outputs `x=NaN` or `x=±∞`
during training. Expect errors, silent or explicit, when `False`.
resume_training: Can be used in case training time is limited, e.g. on a
cluster. If `True`, the split between train and validation set, the
optimizer, the number of epochs, and the best validation log-prob will
be restored from the last time `.train()` was called.
discard_prior_samples: Whether to discard samples simulated in round 1, i.e.
from the prior. Training may be sped up by ignoring such less targeted
samples.
retrain_from_scratch: Whether to retrain the conditional density
estimator for the posterior from scratch each round.
show_train_summary: Whether to print the number of epochs and validation
loss and leakage after the training.
dataloader_kwargs: Additional or updated kwargs to be passed to the training
and validation dataloaders (like, e.g., a collate_fn)
Returns: Classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\).
Source code in sbi/inference/trainers/nre/bnre.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 | |
MCABC
¶
Bases: ABCBASE
Monte-Carlo Approximate Bayesian Computation (Rejection ABC).
Source code in sbi/inference/abc/mcabc.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
__call__(x_o, num_simulations, eps=None, quantile=None, lra=False, sass=False, sass_fraction=0.25, sass_expansion_degree=1, kde=False, kde_kwargs=None, return_summary=False, num_iid_samples=1)
¶
Run MCABC and return accepted parameters or KDE object fitted on them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_o
|
Union[Tensor, ndarray]
|
Observed data. |
required |
num_simulations
|
int
|
Number of simulations to run. |
required |
eps
|
Optional[float]
|
Acceptance threshold \(\epsilon\) for distance between observed and simulated data. |
None
|
quantile
|
Optional[float]
|
Upper quantile of smallest distances for which the corresponding
parameters are returned, e.g, q=0.01 will return the top 1%. Exactly
one of quantile or |
None
|
lra
|
bool
|
Whether to run linear regression adjustment as in Beaumont et al. 2002 |
False
|
sass
|
bool
|
Whether to determine semi-automatic summary statistics as in Fearnhead & Prangle 2012. |
False
|
sass_fraction
|
float
|
Fraction of simulation budget used for the initial sass run. |
0.25
|
sass_expansion_degree
|
int
|
Degree of the polynomial feature expansion for the sass regression, default 1 - no expansion. |
1
|
kde
|
bool
|
Whether to run KDE on the accepted parameters to return a KDE object from which one can sample. |
False
|
kde_kwargs
|
Optional[Dict[str, Any]]
|
kwargs for performing KDE: ‘bandwidth=’; either a float, or a string naming a bandwidth heuristics, e.g., ‘cv’ (cross validation), ‘silvermann’ or ‘scott’, default ‘cv’. ‘transform’: transform applied to the parameters before doing KDE. ‘sample_weights’: weights associated with samples. See ‘get_kde’ for more details |
None
|
return_summary
|
bool
|
Whether to return the distances and data corresponding to the accepted parameters. |
False
|
num_iid_samples
|
int
|
Number of simulations per parameter. Choose
|
1
|
Returns:
| Name | Type | Description |
|---|---|---|
theta |
if kde False
|
accepted parameters |
kde |
if kde True
|
KDE object based on accepted parameters from which one can .sample() and .log_prob(). |
summary |
if summary True
|
dictionary containing the accepted paramters (if kde True), distances and simulated data x. |
Source code in sbi/inference/abc/mcabc.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
__init__(simulator, prior, distance='l2', requires_iid_data=None, distance_kwargs=None, num_workers=1, simulation_batch_size=1, distance_batch_size=-1, show_progress_bars=True)
¶
Monte-Carlo Approximate Bayesian Computation (Rejection ABC) [1].
[1] Pritchard, J. K., Seielstad, M. T., Perez-Lezaun, A., & Feldman, M. W. (1999). Population growth of human Y chromosomes: a study of Y chromosome microsatellites. Molecular biology and evolution, 16(12), 1791-1798.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulator
|
Callable
|
A function that takes parameters \(\theta\) and maps them to
simulations, or observations, |
required |
prior
|
Distribution
|
A probability distribution that expresses prior knowledge about the
parameters, e.g. which ranges are meaningful for them. Any
object with |
required |
distance
|
Union[str, Callable]
|
Distance function to compare observed and simulated data. Can be
a custom callable function or one of |
'l2'
|
requires_iid_data
|
Optional[bool]
|
Whether to allow conditioning on iid sampled data or not. Typically, this information is inferred by the choice of the distance, but in case a custom distance is used, this information is pivotal. |
None
|
distance_kwargs
|
Optional[Dict]
|
Configurations parameters for the distances. In particular useful for the MMD and Wasserstein distance. |
None
|
num_workers
|
int
|
Number of parallel workers to use for simulations. |
1
|
simulation_batch_size
|
int
|
Number of parameter sets that the simulator maps to data x at once. If None, we simulate all parameter sets at the same time. If >= 1, the simulator has to process data of shape (simulation_batch_size, parameter_dimension). |
1
|
distance_batch_size
|
int
|
Number of simulations that the distance function evaluates against the reference observations at once. If -1, we evaluate all simulations at the same time. |
-1
|
Source code in sbi/inference/abc/mcabc.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
SMCABC
¶
Bases: ABCBASE
Sequential Monte Carlo Approximate Bayesian Computation.
Source code in sbi/inference/abc/smcabc.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 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 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 | |
__call__(x_o, num_particles, num_initial_pop, num_simulations, epsilon_decay, distance_based_decay=False, ess_min=None, kernel_variance_scale=1.0, use_last_pop_samples=True, return_summary=False, kde=False, kde_kwargs=None, kde_sample_weights=False, lra=False, lra_with_weights=False, sass=False, sass_fraction=0.25, sass_expansion_degree=1, num_iid_samples=1)
¶
Run SMCABC and return accepted parameters or KDE object fitted on them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_o
|
Union[Tensor, ndarray]
|
Observed data. |
required |
num_particles
|
int
|
Number of particles in each population. |
required |
num_initial_pop
|
int
|
Number of simulations used for initial population. |
required |
num_simulations
|
int
|
Total number of possible simulations. |
required |
epsilon_decay
|
float
|
Factor with which the acceptance threshold \(\epsilon\) decays. |
required |
distance_based_decay
|
bool
|
Whether the \(\epsilon\) decay is constant over populations or calculated from the previous populations distribution of distances. |
False
|
ess_min
|
Optional[float]
|
Threshold of effective sampling size for resampling weights. Not used when None (default). |
None
|
kernel_variance_scale
|
float
|
Factor for scaling the perturbation kernel variance. |
1.0
|
use_last_pop_samples
|
bool
|
Whether to fill up the current population with samples from the previous population when the budget is used up. If False, the current population is discarded and the previous population is returned. |
True
|
lra
|
bool
|
Whether to run linear regression adjustment as in Beaumont et al. 2002 |
False
|
lra_with_weights
|
bool
|
Whether to run lra as weighted linear regression with SMC weights |
False
|
sass
|
bool
|
Whether to determine semi-automatic summary statistics (sass) as in Fearnhead & Prangle 2012. |
False
|
sass_fraction
|
float
|
Fraction of simulation budget used for the initial sass run. |
0.25
|
sass_expansion_degree
|
int
|
Degree of the polynomial feature expansion for the sass regression, default 1 - no expansion. |
1
|
kde
|
bool
|
Whether to run KDE on the accepted parameters to return a KDE object from which one can sample. |
False
|
kde_kwargs
|
Optional[Dict[str, Any]]
|
kwargs for performing KDE: ‘bandwidth=’; either a float, or a string naming a bandwidth heuristics, e.g., ‘cv’ (cross validation), ‘silvermann’ or ‘scott’, default ‘cv’. ‘transform’: transform applied to the parameters before doing KDE. ‘sample_weights’: weights associated with samples. See ‘get_kde’ for more details |
None
|
kde_sample_weights
|
bool
|
Whether perform weighted KDE with SMC weights or on raw particles. |
False
|
return_summary
|
bool
|
Whether to return a dictionary with all accepted particles, weights, etc. at the end. |
False
|
num_iid_samples
|
int
|
Number of simulations per parameter. Choose
|
1
|
Returns:
| Name | Type | Description |
|---|---|---|
theta |
if kde False
|
accepted parameters of the last population. |
kde |
if kde True
|
KDE object fitted on accepted parameters, from which one can .sample() and .log_prob(). |
summary |
if return_summary True
|
dictionary containing the accepted paramters (if kde True), distances and simulated data x of all populations. |
Source code in sbi/inference/abc/smcabc.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 | |
__init__(simulator, prior, distance='l2', requires_iid_data=None, distance_kwargs=None, num_workers=1, simulation_batch_size=1, distance_batch_size=-1, show_progress_bars=True, kernel='gaussian', algorithm_variant='C')
¶
Sequential Monte Carlo Approximate Bayesian Computation.
We distinguish between three different SMC methods here
- A: Toni et al. 2010 (Phd Thesis)
- B: Sisson et al. 2007 (with correction from 2009)
- C: Beaumont et al. 2009
In Toni et al. 2010 we find an overview of the differences on page 34: - B: same as A except for resampling of weights if the effective sampling size is too small. - C: same as A except for calculation of the covariance of the perturbation kernel: the kernel covariance is a scaled version of the covariance of the previous population.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulator
|
Callable
|
A function that takes parameters \(\theta\) and maps them to
simulations, or observations, |
required |
prior
|
Distribution
|
A probability distribution that expresses prior knowledge about the
parameters, e.g. which ranges are meaningful for them. Any
object with |
required |
distance
|
Union[str, Callable]
|
Distance function to compare observed and simulated data. Can be
a custom callable function or one of |
'l2'
|
requires_iid_data
|
Optional[bool]
|
Whether to allow conditioning on iid sampled data or not. Typically, this information is inferred by the choice of the distance, but in case a custom distance is used, this information is pivotal. |
None
|
distance_kwargs
|
Optional[Dict]
|
Configurations parameters for the distances. In particular useful for the MMD and Wasserstein distance. |
None
|
num_workers
|
int
|
Number of parallel workers to use for simulations. |
1
|
simulation_batch_size
|
int
|
Number of parameter sets that the simulator maps to data x at once. If None, we simulate all parameter sets at the same time. If >= 1, the simulator has to process data of shape (simulation_batch_size, parameter_dimension). |
1
|
distance_batch_size
|
int
|
Number of simulations that the distance function evaluates against the reference observations at once. If -1, we evaluate all simulations at the same time. |
-1
|
show_progress_bars
|
bool
|
Whether to show a progressbar during simulation and sampling. |
True
|
kernel
|
Optional[str]
|
Perturbation kernel. |
'gaussian'
|
algorithm_variant
|
str
|
Indicating the choice of algorithm variant, A, B, or C. |
'C'
|
Source code in sbi/inference/abc/smcabc.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
sample_from_population_with_weights(particles, weights, num_samples=1)
staticmethod
¶
Return samples from particles sampled with weights.
Source code in sbi/inference/abc/smcabc.py
587 588 589 590 591 592 593 594 595 596 597 598 599 600 | |
Helpers¶
simulate_for_sbi(simulator, proposal, num_simulations, num_workers=1, simulation_batch_size=1, seed=None, show_progress_bar=True)
¶
Returns pairs :math:(\theta, x) by sampling proposal and running simulations.
This function performs two steps:
- Sample parameters \(\theta\) from the
proposal. - Simulate these parameters to obtain \(x\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
simulator
|
Callable
|
A function that takes parameters \(\theta\) and maps them to
simulations, or observations, |
required |
proposal
|
Any
|
Probability distribution that the parameters \(\theta\) are sampled from. |
required |
num_simulations
|
int
|
Number of simulations that are run. |
required |
num_workers
|
int
|
Number of parallel workers to use for simulations. |
1
|
simulation_batch_size
|
Union[int, None]
|
Number of parameter sets of shape (simulation_batch_size, parameter_dimension) that the simulator receives per call. If None, we set simulation_batch_size=num_simulations and simulate all parameter sets with one call. Otherwise, we construct batches of parameter sets and distribute them among num_workers. |
1
|
seed
|
Optional[int]
|
Seed for reproducibility. |
None
|
show_progress_bar
|
bool
|
Whether to show a progress bar for simulating. This will not affect whether there will be a progressbar while drawing samples from the proposal. |
True
|
Returns: Sampled parameters \(\theta\) and simulation-outputs \(x\).
Source code in sbi/utils/simulation_utils.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | |
process_prior(prior, custom_prior_wrapper_kwargs=None)
¶
Return PyTorch distribution-like prior from user-provided prior.
NOTE: If the prior argument is a sequence of PyTorch distributions, they will be interpreted as independent prior dimensions wrapped in a :class:MultipleIndependent PyTorch Distribution. In case the elements are not PyTorch distributions, make sure to use :func:process_prior on each element in the list beforehand.
NOTE: Returns a tuple (processed_prior, num_params, whether_prior_returns_numpy). The last two entries in the tuple can be passed on to process_simulator to prepare the simulator. For example, it ensures parameters are cast to numpy or adds a batch dimension to the simulator output, if needed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior (
|
class: |
required | |
custom_prior_wrapper_kwargs
|
dict
|
Additional arguments passed to the wrapper class that processes the prior
into a PyTorch Distribution, such as bounds ( |
None
|
Raises:
| Type | Description |
|---|---|
AttributeError
|
If prior objects lack |
Returns:
| Type | Description |
|---|---|
Tuple[Distribution, int, bool]
|
Tuple[torch.distributions.Distribution, int, bool]:
- |
Example:¶
::
import torch
from torch.distributions import Uniform
from sbi.utils.user_input_checks import process_prior
prior = Uniform(torch.zeros(1), torch.ones(1))
prior, theta_numel, prior_returns_numpy = process_prior(prior)
Source code in sbi/utils/user_input_checks.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
process_simulator(user_simulator, prior, is_numpy_simulator)
¶
Returns a simulator that meets the requirements for usage in sbi.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_simulator
|
Callable
|
simulator provided by the user, possibly written in numpy. |
required |
prior
|
Distribution
|
prior as pytorch distribution or processed with :func: |
required |
is_numpy_simulator
|
bool
|
whether the simulator needs theta in numpy types, returned
from |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
simulator: processed simulator that returns :class: |
Example:¶
::
import torch
from sbi.utils.user_input_checks import process_simulator
from torch.distributions import Uniform
from sbi.utils.user_input_checks import process_prior
prior = Uniform(torch.zeros(1), torch.ones(1))
prior, theta_numel, prior_returns_numpy = process_prior(prior)
simulator = lambda theta: theta + 1
simulator = process_simulator(simulator, prior, prior_returns_numpy)
Source code in sbi/utils/user_input_checks.py
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 | |