Inference¶
Training algorithms¶
NPE_A
¶
Bases: PosteriorEstimator
Source code in sbi/inference/trainers/npe/npe_a.py
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 |
|
__init__(prior=None, density_estimator='mdn_snpe_a', num_components=10, device='cpu', logging_level='WARNING', summary_writer=None, show_progress_bars=True)
¶
NPE-A [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 has to be performed analytically. Thus, NPE-A is limited to Gaussian distributions for all but the last round. In the last round, NPE-A can use a Mixture of Gaussians.
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[str, Callable]
|
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 can be provided. The function will
be called with the first batch of simulations (theta, x), which can
thus be used for shape inference and potentially for z-scoring. It
needs to return a PyTorch |
'mdn_snpe_a'
|
num_components
|
int
|
Number of components of the mixture of Gaussians in the
last round. This overrides the |
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[TensorboardSummaryWriter]
|
A tensorboard |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during training. |
True
|
Source code in sbi/inference/trainers/npe/npe_a.py
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 |
|
build_posterior(density_estimator=None, prior=None, **kwargs)
¶
Build posterior from the neural density estimator.
This method first corrects the estimated density with correct_for_proposal
and then returns a DirectPosterior
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
density_estimator
|
Optional[TorchModule]
|
The density estimator that the posterior is based on.
If |
None
|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
Returns:
Type | Description |
---|---|
DirectPosterior
|
Posterior \(p(\theta|x)\) with |
Source code in sbi/inference/trainers/npe/npe_a.py
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 |
|
correct_for_proposal(density_estimator=None)
¶
Build mixture of Gaussians that approximates the posterior.
Returns a NPE_A_MDN
object, which applies the posthoc-correction required in
SNPE-A.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
density_estimator
|
Optional[TorchModule]
|
The density estimator that the posterior is based on.
If |
None
|
Returns:
Type | Description |
---|---|
NPE_A_MDN
|
Posterior \(p(\theta|x)\) with |
Source code in sbi/inference/trainers/npe/npe_a.py
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 |
|
train(final_round=False, 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, component_perturbation=0.005)
¶
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 |
---|---|---|---|
final_round
|
bool
|
Whether we are in the last round of training or not. For all but the last round, Algorithm 1 from [1] is executed. In last the round, Algorithm 2 from [1] is executed once. |
False
|
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
|
If |
required | |
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
|
component_perturbation
|
float
|
The standard deviation applied to all weights and biases when, in the last round, the Mixture of Gaussians is build from a single Gaussian. This value can be problem-specific and also depends on the number of mixture components. |
0.005
|
Returns:
Type | Description |
---|---|
ConditionalDensityEstimator
|
Density estimator that approximates the distribution \(p(\theta|x)\). |
Source code in sbi/inference/trainers/npe/npe_a.py
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 |
|
NPE_C
¶
Bases: PosteriorEstimator
Source code in sbi/inference/trainers/npe/npe_c.py
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 |
|
__init__(prior=None, density_estimator='maf', device='cpu', logging_level='WARNING', summary_writer=None, show_progress_bars=True)
¶
NPE-C / APT [1].
[1] Automatic Posterior Transformation for Likelihood-free Inference, Greenberg et al., ICML 2019, https://arxiv.org/abs/1905.07488.
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.
For the sequential mode in which the density estimator is trained across rounds, this class implements two loss variants of NPE-C: the non-atomic and the atomic version. The atomic loss of NPE-C can be used for any density estimator, i.e. also for normalizing flows. However, it suffers from leakage issues. On the other hand, the non-atomic loss can only be used only if the proposal distribution is a mixture of Gaussians, the density estimator is a mixture of Gaussians, and the prior is either Gaussian or Uniform. It does not suffer from leakage issues. At the beginning of each round, we print whether the non-atomic or the atomic version is used.
In this codebase, we will automatically switch to the non-atomic loss if the
following criteria are fulfilled:
- proposal is a DirectPosterior
with density_estimator mdn
, as built
with sbi.neural_nets.posterior_nn()
.
- the density estimator is a mdn
, as built with
sbi.neural_nets.posterior_nn()
.
- isinstance(prior, MultivariateNormal)
(from torch.distributions
) or
isinstance(prior, sbi.utils.BoxUniform)
Note that custom implementations of any of these densities (or estimators) will not trigger the non-atomic loss, and the algorithm will fall back onto using the atomic loss.
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[str, Callable]
|
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 can be provided. The function will
be called with the first batch of simulations (theta, x), which can
thus be used for shape inference and potentially for z-scoring. It
needs to return a PyTorch |
'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[TensorboardSummaryWriter]
|
A tensorboard |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during training. |
True
|
Source code in sbi/inference/trainers/npe/npe_c.py
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 |
|
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 |
---|---|
Module
|
Density estimator that approximates the distribution \(p(\theta|x)\). |
Source code in sbi/inference/trainers/npe/npe_c.py
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 |
|
FMPE
¶
Bases: NeuralInference
Implements the Flow Matching Posterior Estimator (FMPE) for simulation-based inference.
Source code in sbi/inference/trainers/fmpe/fmpe.py
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 |
|
__init__(prior, density_estimator='mlp', device='cpu', logging_level='WARNING', summary_writer=None, show_progress_bars=True)
¶
Initialization method for the FMPE class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prior
|
Optional[Distribution]
|
Prior distribution. |
required |
density_estimator
|
Union[str, Callable]
|
Neural network architecture used to learn the vector
field for flow matching. Can be a string, e.g., ‘mlp’ or ‘resnet’, or a
|
'mlp'
|
device
|
str
|
Device to use for training. |
'cpu'
|
logging_level
|
Union[int, str]
|
Logging level. |
'WARNING'
|
summary_writer
|
Optional[SummaryWriter]
|
Summary writer for tensorboard. |
None
|
show_progress_bars
|
bool
|
Whether to show progress bars. |
True
|
Source code in sbi/inference/trainers/fmpe/fmpe.py
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 |
|
build_posterior(density_estimator=None, prior=None, sample_with='direct', direct_sampling_parameters=None, **kwargs)
¶
Build the posterior distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
density_estimator
|
Optional[ConditionalDensityEstimator]
|
Density estimator for the posterior. |
None
|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
sample_with
|
str
|
Sampling method, currently only “direct” is supported. |
'direct'
|
direct_sampling_parameters
|
Optional[Dict[str, Any]]
|
kwargs for DirectPosterior. |
None
|
Returns:
Name | Type | Description |
---|---|---|
DirectPosterior |
DirectPosterior
|
Posterior distribution. |
Source code in sbi/inference/trainers/fmpe/fmpe.py
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 |
|
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, force_first_round_loss=False, show_train_summary=False, dataloader_kwargs=None)
¶
Train the flow matching estimator.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
training_batch_size
|
int
|
Batch size for training. Defaults to 50. |
200
|
learning_rate
|
float
|
Learning rate for training. Defaults to 5e-4. |
0.0005
|
validation_fraction
|
float
|
Fraction of the data to use for validation. |
0.1
|
stop_after_epochs
|
int
|
Number of epochs to train for. Defaults to 20. |
20
|
max_num_epochs
|
int
|
Maximum number of epochs to train for. |
2 ** 31 - 1
|
clip_max_norm
|
Optional[float]
|
Maximum norm for gradient clipping. Defaults to 5.0. |
5.0
|
resume_training
|
bool
|
Can be used in case training time is limited, e.g. on a
cluster. If |
False
|
force_first_round_loss
|
bool
|
Whether to allow training with simulations that have not been sampled from the prior, e.g., in a sequential inference setting. Note that can lead to biased inference results. |
False
|
show_train_summary
|
bool
|
Whether to show the training summary. Defaults to False. |
False
|
dataloader_kwargs
|
Optional[dict]
|
Additional keyword arguments for the dataloader. |
None
|
Returns:
Name | Type | Description |
---|---|---|
DensityEstimator |
ConditionalDensityEstimator
|
Trained flow matching estimator. |
Source code in sbi/inference/trainers/fmpe/fmpe.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 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 |
|
NPSE
¶
Bases: NeuralInference
Source code in sbi/inference/trainers/npse/npse.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 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 |
|
__init__(prior=None, score_estimator='mlp', sde_type='ve', device='cpu', logging_level='WARNING', summary_writer=None, show_progress_bars=True, **kwargs)
¶
Base class for Neural Posterior Score Estimation methods.
Instead of performing conditonal density estimation, NPSE methods perform conditional score estimation i.e. they estimate the gradient of the log density using denoising score matching loss.
NOTE: NPSE does not support multi-round inference with flexible proposals yet. You can try to run multi-round with truncated proposals, but note that this is not tested yet.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
score_estimator
|
Union[str, Callable]
|
Neural network architecture for the score estimator. Can be a string (e.g. ‘mlp’ or ‘ada_mlp’) or a callable that returns a neural network. |
'mlp'
|
sde_type
|
str
|
Type of SDE to use. Must be one of [‘vp’, ‘ve’, ‘subvp’]. |
'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]
|
Tensorboard summary writer. |
None
|
show_progress_bars
|
bool
|
Whether to show progress bars during training. |
True
|
kwargs
|
Additional keyword arguments. |
{}
|
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/npse/npse.py
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 |
|
append_simulations(theta, x, proposal=None, exclude_invalid_x=None, data_device=None)
¶
Store parameters and simulation outputs to use them for later training.
Data are stored as entries in lists for each type of variable (parameter/data).
Stores \(\theta\), \(x\), prior_masks (indicating if simulations are coming from the prior or not) and an index indicating which round the batch of simulations came from.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
theta
|
Tensor
|
Parameter sets. |
required |
x
|
Tensor
|
Simulation outputs. |
required |
proposal
|
Optional[DirectPosterior]
|
The distribution that the parameters \(\theta\) were sampled from.
Pass |
None
|
exclude_invalid_x
|
Optional[bool]
|
Whether invalid simulations are discarded during
training. For single-round SNPE, it is fine to discard invalid
simulations, but for multi-round SNPE (atomic), discarding invalid
simulations gives systematically wrong results. If |
None
|
data_device
|
Optional[str]
|
Where to store the data, default is on the same device where the training is happening. If training a large dataset on a GPU with not much VRAM can set to ‘cpu’ to store data on system memory instead. |
None
|
Returns:
Type | Description |
---|---|
NPSE
|
NeuralInference object (returned so that this function is chainable). |
Source code in sbi/inference/trainers/npse/npse.py
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 |
|
build_posterior(score_estimator=None, prior=None, sample_with='sde')
¶
Build posterior from the score estimator.
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 it compensates for the leakage. - reject samples that lie outside of the prior bounds.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
score_estimator
|
Optional[ConditionalScoreEstimator]
|
The score estimator that the posterior is based on.
If |
None
|
prior
|
Optional[Distribution]
|
Prior distribution. |
None
|
sample_with
|
str
|
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. |
'sde'
|
Returns:
Type | Description |
---|---|
ScorePosterior
|
Posterior \(p(\theta|x)\) with |
Source code in sbi/inference/trainers/npse/npse.py
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 |
|
train(training_batch_size=200, learning_rate=0.0005, validation_fraction=0.1, stop_after_epochs=200, max_num_epochs=2 ** 31 - 1, clip_max_norm=5.0, calibration_kernel=None, ema_loss_decay=0.1, resume_training=False, force_first_round_loss=False, discard_prior_samples=False, retrain_from_scratch=False, show_train_summary=False, dataloader_kwargs=None)
¶
Returns a score estimator that approximates the score \(\nabla_\theta \log p(\theta|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. |
200
|
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
|
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 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 |
---|---|
ConditionalScoreEstimator
|
Score estimator that approximates the posterior score. |
Source code in sbi/inference/trainers/npse/npse.py
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 |
|
NLE_A
¶
Bases: LikelihoodEstimator
Source code in sbi/inference/trainers/nle/nle_a.py
13 14 15 16 17 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 |
|
__init__(prior=None, density_estimator='maf', device='cpu', logging_level='WARNING', summary_writer=None, show_progress_bars=True)
¶
Neural Likelihood Estimation [1].
[1] Sequential Neural Likelihood: Fast Likelihood-free Inference with Autoregressive Flows_, Papamakarios et al., AISTATS 2019, https://arxiv.org/abs/1805.07226
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[str, Callable]
|
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 can be provided. The function will
be called with the first batch of simulations (theta, x), which can
thus be used for shape inference and potentially for z-scoring. It
needs to return a PyTorch |
'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[TensorboardSummaryWriter]
|
A tensorboard |
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
14 15 16 17 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 |
|
NRE_A
¶
Bases: RatioEstimator
Source code in sbi/inference/trainers/nre/nre_a.py
15 16 17 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 |
|
__init__(prior=None, classifier='resnet', device='cpu', logging_level='warning', summary_writer=None, show_progress_bars=True)
¶
AALR[1], here known as NRE_A.
[1] Likelihood-free MCMC with Amortized Approximate Likelihood Ratios, Hermans et al., ICML 2020, https://arxiv.org/abs/1903.04057
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, Callable]
|
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). Alternatively, a function that builds a custom
neural network can be provided. The function will be called with the
first batch of simulations (theta, x), which can thus be used for shape
inference and potentially for z-scoring. It needs to return a PyTorch
|
'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[TensorboardSummaryWriter]
|
A tensorboard |
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
16 17 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 |
|
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[Dict[str, Any]]
|
Additional or updated kwargs to be passed to the self._loss fn. |
None
|
Returns:
Type | Description |
---|---|
Module
|
Classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\). |
Source code in sbi/inference/trainers/nre/nre_a.py
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 |
|
NRE_B
¶
Bases: RatioEstimator
Source code in sbi/inference/trainers/nre/nre_b.py
15 16 17 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 |
|
__init__(prior=None, classifier='resnet', device='cpu', logging_level='warning', summary_writer=None, show_progress_bars=True)
¶
SRE[1], here known as NRE_B.
[1] On Contrastive Learning for Likelihood-free Inference, Durkan et al., ICML 2020, https://arxiv.org/pdf/2002.03712
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, Callable]
|
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). Alternatively, a function that builds a custom
neural network can be provided. The function will be called with the
first batch of simulations (theta, x), which can thus be used for shape
inference and potentially for z-scoring. It needs to return a PyTorch
|
'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[TensorboardSummaryWriter]
|
A tensorboard |
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
16 17 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 |
|
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 |
---|---|
Module
|
Classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\). |
Source code in sbi/inference/trainers/nre/nre_b.py
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 |
|
NRE_C
¶
Bases: RatioEstimator
Source code in sbi/inference/trainers/nre/nre_c.py
15 16 17 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 |
|
__init__(prior=None, classifier='resnet', device='cpu', logging_level='warning', summary_writer=None, show_progress_bars=True)
¶
NRE-C[1] is a generalization of the non-sequential (amortized) versions of
NRE_A and NRE_B. We call the algorithm NRE_C within sbi
.
NRE-C:
(1) like NRE_B, features a “multiclass” loss function where several marginally
drawn parameter-data pairs are contrasted against a jointly drawn pair.
(2) like AALR/NRE_A, i.e., the non-sequential version of NRE_A, it encourages
the approximate ratio \(p(\theta,x)/p(\theta)p(x)\), accessed through
.potential()
within sbi
, to be exact at optimum. This addresses the
issue that NRE_B estimates this ratio only up to an arbitrary function
(normalizing constant) of the data \(x\).
Just like for all ratio estimation algorithms, the sequential version of NRE_C will be estimated only up to a function (normalizing constant) of the data \(x\) in rounds after the first.
[1] Contrastive Neural Ratio Estimation, Benajmin Kurt Miller, et. al., NeurIPS 2022, https://arxiv.org/abs/2210.06170
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, Callable]
|
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). Alternatively, a function that builds a custom
neural network can be provided. The function will be called with the
first batch of simulations (theta, x), which can thus be used for shape
inference and potentially for z-scoring. It needs to return a PyTorch
|
'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[TensorboardSummaryWriter]
|
A tensorboard |
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
16 17 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 |
|
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 |
---|---|
Module
|
Classifier that approximates the ratio \(p(\theta,x)/p(\theta)p(x)\). |
Source code in sbi/inference/trainers/nre/nre_c.py
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 |
|
BNRE
¶
Bases: NRE_A
Source code in sbi/inference/trainers/nre/bnre.py
15 16 17 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 |
|
__init__(prior=None, classifier='resnet', device='cpu', logging_level='warning', summary_writer=None, show_progress_bars=True)
¶
Balanced neural ratio estimation (BNRE)[1].
BNRE is a variation of NRE aiming to produce more conservative posterior approximations.
[1] Delaunoy, A., Hermans, J., Rozet, F., Wehenkel, A., & Louppe, G.. Towards Reliable Simulation-Based Inference with Balanced Neural Ratio Estimation. NeurIPS 2022. https://arxiv.org/abs/2208.13624
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, Callable]
|
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). Alternatively, a function that builds a custom
neural network can be provided. The function will be called with the
first batch of simulations \((\theta, x)\), which can thus be used for
shape inference and potentially for z-scoring. It needs to return a
PyTorch |
'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[TensorboardSummaryWriter]
|
A tensorboard |
None
|
show_progress_bars
|
bool
|
Whether to show a progressbar during simulation and sampling. |
True
|
Source code in sbi/inference/trainers/nre/bnre.py
16 17 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 |
|
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
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 |
|
MCABC
¶
Bases: ABCBASE
Monte-Carlo Approximate Bayesian Computation (Rejection ABC).
Source code in sbi/inference/abc/mcabc.py
17 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 |
|
__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
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 |
|
__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
|
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[None]
|
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
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 |
|
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 |
|
__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[None]
|
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 |
|
get_kernel_variance(particles, weights, samples_per_dim=100, kernel_variance_scale=1.0)
¶
Return kernel variance for a given population of particles and weights.
Source code in sbi/inference/abc/smcabc.py
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 |
|
get_new_kernel(thetas)
¶
Return new kernel distribution for a given set of paramters.
Source code in sbi/inference/abc/smcabc.py
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 |
|
get_particle_ranges(particles, weights, samples_per_dim=100)
¶
Return range of particles in each parameter dimension.
Source code in sbi/inference/abc/smcabc.py
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 |
|
resample_if_ess_too_small(particles, log_weights, ess_min, pop_idx)
¶
Return resampled particles and uniform weights if effectice sampling size is too small.
Source code in sbi/inference/abc/smcabc.py
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 |
|
run_lra_update_weights(particles, xs, observation, log_weights, lra_with_weights)
¶
Return particles and weights adjusted with LRA.
Runs (weighted) linear regression from xs onto particles to adjust the particles.
Updates the SMC weights according to the new particles.
Source code in sbi/inference/abc/smcabc.py
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 |
|
run_sass_set_xo(num_particles, num_pilot_simulations, x_o, num_iid_samples, lra=False, sass_expansion_degree=1)
¶
Return transform for semi-automatic summary statistics.
Runs an single round of rejection abc with fixed budget and accepts num_particles simulations to run the regression for sass.
Sets self.x_o once the x_shape can be derived from simulations.
Source code in sbi/inference/abc/smcabc.py
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 |
|
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 (\(\theta, x\)) pairs obtained from sampling the proposal and simulating.
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 |
|
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 MultipleIndependent
pytorch Distribution. In case the elements are not PyTorch distributions, make sure
to use process_prior on each element in the list beforehand. See FAQ 7 for details.
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 as well. For example, it will take care of casting parameters to numpy
or adding a batch dimension to the simulator output, if needed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prior
|
Union[Sequence[Distribution], Distribution, rv_frozen, multi_rv_frozen]
|
Prior object with |
required |
custom_prior_wrapper_kwargs
|
Optional[Dict]
|
kwargs to be passed to the class that wraps a custom prior into a pytorch Distribution, e.g., for passing bounds for a prior with bounded support (lower_bound, upper_bound), or argument constraints. (arg_constraints), see pytorch.distributions.Distribution for more info. |
None
|
Raises:
Type | Description |
---|---|
AttributeError
|
If prior objects lacks |
Returns:
Name | Type | Description |
---|---|---|
prior |
Distribution
|
Prior that emits samples and evaluates log prob as PyTorch Tensors. |
theta_numel |
int
|
Number of parameters - elements in a single sample from the prior. |
prior_returns_numpy |
bool
|
Whether the return type of the prior was a Numpy array. |
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 |
|
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 |
required |
is_numpy_simulator
|
bool
|
whether the simulator needs theta in numpy types, returned
from |
required |
Returns:
Name | Type | Description |
---|---|---|
simulator |
Callable
|
processed simulator that returns |
Source code in sbi/utils/user_input_checks.py
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 |
|