Posteriors¶
DirectPosterior
¶
Bases: NeuralPosterior
Posterior \(p(\theta|x_o)\) with log_prob()
and sample()
methods, only
applicable to SNPE.
SNPE trains a neural network to directly approximate the posterior distribution.
However, for bounded priors, the neural network can have leakage: it puts non-zero
mass in regions where the prior is zero. The DirectPosterior
class wraps the
trained network to deal with these cases.
Specifically, this class offers the following functionality:
- correct the calculation of the log probability such that it compensates for the
leakage.
- reject samples that lie outside of the prior bounds.
This class can not be used in combination with SNLE or SNRE.
Source code in sbi/inference/posteriors/direct_posterior.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 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 |
|
__init__(posterior_estimator, prior, max_sampling_batch_size=10000, device=None, x_shape=None, enable_transform=True)
¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prior
|
Distribution
|
Prior distribution with |
required |
posterior_estimator
|
ConditionalDensityEstimator
|
The trained neural posterior. |
required |
max_sampling_batch_size
|
int
|
Batchsize of samples being drawn from the proposal at every iteration. |
10000
|
device
|
Optional[str]
|
Training device, e.g., “cpu”, “cuda” or “cuda:0”. If None,
|
None
|
x_shape
|
Optional[Size]
|
Deprecated, should not be passed. |
None
|
enable_transform
|
bool
|
Whether to transform parameters to unconstrained space
during MAP optimization. When False, an identity transform will be
returned for |
True
|
Source code in sbi/inference/posteriors/direct_posterior.py
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 |
|
leakage_correction(x, num_rejection_samples=10000, force_update=False, show_progress_bars=False, rejection_sampling_batch_size=10000)
¶
Return leakage correction factor for a leaky posterior density estimate.
The factor is estimated from the acceptance probability during rejection sampling from the posterior.
This is to avoid re-estimating the acceptance probability from scratch
whenever log_prob
is called and norm_posterior=True
. Here, it
is estimated only once for self.default_x
and saved for later. We
re-evaluate only whenever a new x
is passed.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_rejection_samples
|
int
|
Number of samples used to estimate correction factor. |
10000
|
show_progress_bars
|
bool
|
Whether to show a progress bar during sampling. |
False
|
rejection_sampling_batch_size
|
int
|
Batch size for rejection sampling. |
10000
|
Returns:
Type | Description |
---|---|
Tensor
|
Saved or newly-estimated correction factor (as a scalar |
Source code in sbi/inference/posteriors/direct_posterior.py
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 |
|
log_prob(theta, x=None, norm_posterior=True, track_gradients=False, leakage_correction_params=None)
¶
Returns the log-probability of the posterior \(p(\theta|x)\).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
theta
|
Tensor
|
Parameters \(\theta\). |
required |
norm_posterior
|
bool
|
Whether to enforce a normalized posterior density.
Renormalization of the posterior is useful when some
probability falls out or leaks out of the prescribed prior support.
The normalizing factor is calculated via rejection sampling, so if you
need speedier but unnormalized log posterior estimates set here
|
True
|
track_gradients
|
bool
|
Whether the returned tensor supports tracking gradients. This can be helpful for e.g. sensitivity analysis, but increases memory consumption. |
False
|
leakage_correction_params
|
Optional[dict]
|
A |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Tensor
|
support of the prior, -∞ (corresponding to 0 probability) outside. |
Source code in sbi/inference/posteriors/direct_posterior.py
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 |
|
log_prob_batched(theta, x, norm_posterior=True, track_gradients=False, leakage_correction_params=None)
¶
Given a batch of observations [x_1, …, x_B] and a batch of parameters [$ heta_1$,…, $ heta_B$] this function evalautes the log-probabilities of the posteriors \(p( heta_1|x_1)\), …, \(p( heta_B|x_B)\) in a batched (i.e. vectorized) manner.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
theta
|
Tensor
|
Batch of parameters $ heta$ of shape |
required |
x
|
Tensor
|
Batch of observations \(x\) of shape |
required |
norm_posterior
|
bool
|
Whether to enforce a normalized posterior density.
Renormalization of the posterior is useful when some
probability falls out or leaks out of the prescribed prior support.
The normalizing factor is calculated via rejection sampling, so if you
need speedier but unnormalized log posterior estimates set here
|
True
|
track_gradients
|
bool
|
Whether the returned tensor supports tracking gradients. This can be helpful for e.g. sensitivity analysis, but increases memory consumption. |
False
|
leakage_correction_params
|
Optional[dict]
|
A |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Source code in sbi/inference/posteriors/direct_posterior.py
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 |
|
map(x=None, num_iter=1000, num_to_optimize=100, learning_rate=0.01, init_method='posterior', num_init_samples=1000, save_best_every=10, show_progress_bars=False, force_update=False)
¶
Returns the maximum-a-posteriori estimate (MAP).
The method can be interrupted (Ctrl-C) when the user sees that the
log-probability converges. The best estimate will be saved in self._map
and
can be accessed with self.map()
. The MAP is obtained by running gradient
ascent from a given number of starting positions (samples from the posterior
with the highest log-probability). After the optimization is done, we select the
parameter set that has the highest log-probability after the optimization.
Warning: The default values used by this function are not well-tested. They might require hand-tuning for the problem at hand.
For developers: if the prior is a BoxUniform
, we carry out the optimization
in unbounded space and transform the result back into bounded space.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Optional[Tensor]
|
Deprecated - use |
None
|
num_iter
|
int
|
Number of optimization steps that the algorithm takes to find the MAP. |
1000
|
learning_rate
|
float
|
Learning rate of the optimizer. |
0.01
|
init_method
|
Union[str, Tensor]
|
How to select the starting parameters for the optimization. If
it is a string, it can be either [ |
'posterior'
|
num_init_samples
|
int
|
Draw this number of samples from the posterior and evaluate the log-probability of all of them. |
1000
|
num_to_optimize
|
int
|
From the drawn |
100
|
save_best_every
|
int
|
The best log-probability is computed, saved in the
|
10
|
show_progress_bars
|
bool
|
Whether to show a progressbar during sampling from the posterior. |
False
|
force_update
|
bool
|
Whether to re-calculate the MAP when x is unchanged and have a cached value. |
False
|
log_prob_kwargs
|
Will be empty for SNLE and SNRE. Will contain {‘norm_posterior’: True} for SNPE. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The MAP estimate. |
Source code in sbi/inference/posteriors/direct_posterior.py
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 |
|
sample(sample_shape=torch.Size(), x=None, max_sampling_batch_size=10000, sample_with=None, show_progress_bars=True)
¶
Return samples from posterior distribution \(p(\theta|x)\).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_shape
|
Shape
|
Desired shape of samples that are drawn from posterior. If
sample_shape is multidimensional we simply draw |
Size()
|
sample_with
|
Optional[str]
|
This argument only exists to keep backward-compatibility with
|
None
|
show_progress_bars
|
bool
|
Whether to show sampling progress monitor. |
True
|
Source code in sbi/inference/posteriors/direct_posterior.py
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 |
|
sample_batched(sample_shape, x, max_sampling_batch_size=10000, show_progress_bars=True)
¶
Given a batch of observations [x_1, …, x_B] this function samples from posteriors \(p(\theta|x_1)\), … ,\(p(\theta|x_B)\), in a batched (i.e. vectorized) manner.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_shape
|
Shape
|
Desired shape of samples that are drawn from the posterior given every observation. |
required |
x
|
Tensor
|
A batch of observations, of shape |
required |
max_sampling_batch_size
|
int
|
Maximum batch size for rejection sampling. |
10000
|
show_progress_bars
|
bool
|
Whether to show sampling progress monitor. |
True
|
Returns:
Type | Description |
---|---|
Tensor
|
Samples from the posteriors of shape (*sample_shape, B, *input_shape) |
Source code in sbi/inference/posteriors/direct_posterior.py
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 |
|
ImportanceSamplingPosterior
¶
Bases: NeuralPosterior
Provides importance sampling to sample from the posterior.
SNLE or SNRE train neural networks to approximate the likelihood(-ratios).
ImportanceSamplingPosterior
allows to estimate the posterior log-probability by
estimating the normlalization constant with importance sampling. It also allows to
perform importance sampling (with .sample()
) and to draw approximate samples with
sampling-importance-resampling (SIR) (with .sir_sample()
)
Source code in sbi/inference/posteriors/importance_posterior.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 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 |
|
__init__(potential_fn, proposal, theta_transform=None, method='sir', oversampling_factor=32, max_sampling_batch_size=10000, device=None, x_shape=None)
¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
potential_fn
|
Union[Callable, BasePotential]
|
The potential function from which to draw samples. Must be a
|
required |
proposal
|
Any
|
The proposal distribution. |
required |
theta_transform
|
Optional[TorchTransform]
|
Transformation that is applied to parameters. Is not used
during but only when calling |
None
|
method
|
str
|
Either of [ |
'sir'
|
oversampling_factor
|
int
|
Number of proposed samples from which only one is selected based on its importance weight. |
32
|
max_sampling_batch_size
|
int
|
The batch size of samples being drawn from the proposal at every iteration. |
10000
|
device
|
Optional[str]
|
Device on which to sample, e.g., “cpu”, “cuda” or “cuda:0”. If
None, |
None
|
x_shape
|
Optional[Size]
|
Deprecated, should not be passed. |
None
|
Source code in sbi/inference/posteriors/importance_posterior.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 |
|
estimate_normalization_constant(x, num_samples=10000, force_update=False)
¶
Returns the normalization constant via importance sampling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_samples
|
int
|
Number of importance samples used for the estimate. |
10000
|
force_update
|
bool
|
Whether to re-calculate the normlization constant when x is unchanged and have a cached value. |
False
|
Source code in sbi/inference/posteriors/importance_posterior.py
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 |
|
log_prob(theta, x=None, track_gradients=False, normalization_constant_params=None)
¶
Returns the log-probability of theta under the posterior.
The normalization constant is estimated with importance sampling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
theta
|
Tensor
|
Parameters \(\theta\). |
required |
track_gradients
|
bool
|
Whether the returned tensor supports tracking gradients. This can be helpful for e.g. sensitivity analysis, but increases memory consumption. |
False
|
normalization_constant_params
|
Optional[dict]
|
Parameters passed on to
|
None
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Source code in sbi/inference/posteriors/importance_posterior.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 |
|
map(x=None, num_iter=1000, num_to_optimize=100, learning_rate=0.01, init_method='proposal', num_init_samples=1000, save_best_every=10, show_progress_bars=False, force_update=False)
¶
Returns the maximum-a-posteriori estimate (MAP).
The method can be interrupted (Ctrl-C) when the user sees that the
log-probability converges. The best estimate will be saved in self._map
and
can be accessed with self.map()
. The MAP is obtained by running gradient
ascent from a given number of starting positions (samples from the posterior
with the highest log-probability). After the optimization is done, we select the
parameter set that has the highest log-probability after the optimization.
Warning: The default values used by this function are not well-tested. They might require hand-tuning for the problem at hand.
For developers: if the prior is a BoxUniform
, we carry out the optimization
in unbounded space and transform the result back into bounded space.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Optional[Tensor]
|
Deprecated - use |
None
|
num_iter
|
int
|
Number of optimization steps that the algorithm takes to find the MAP. |
1000
|
learning_rate
|
float
|
Learning rate of the optimizer. |
0.01
|
init_method
|
Union[str, Tensor]
|
How to select the starting parameters for the optimization. If
it is a string, it can be either [ |
'proposal'
|
num_init_samples
|
int
|
Draw this number of samples from the posterior and evaluate the log-probability of all of them. |
1000
|
num_to_optimize
|
int
|
From the drawn |
100
|
save_best_every
|
int
|
The best log-probability is computed, saved in the
|
10
|
show_progress_bars
|
bool
|
Whether to show a progressbar during sampling from the posterior. |
False
|
force_update
|
bool
|
Whether to re-calculate the MAP when x is unchanged and have a cached value. |
False
|
log_prob_kwargs
|
Will be empty for SNLE and SNRE. Will contain {‘norm_posterior’: True} for SNPE. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The MAP estimate. |
Source code in sbi/inference/posteriors/importance_posterior.py
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 |
|
sample(sample_shape=torch.Size(), x=None, method=None, oversampling_factor=32, max_sampling_batch_size=10000, sample_with=None, show_progress_bars=False)
¶
Return samples from the approximate posterior distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_shape
|
Shape
|
Shape of samples that are drawn from posterior. |
Size()
|
x
|
Optional[Tensor]
|
Observed data. |
None
|
method
|
Optional[str]
|
Either of [ |
None
|
oversampling_factor
|
int
|
Number of proposed samples from which only one is selected based on its importance weight. |
32
|
max_sampling_batch_size
|
int
|
The batch size of samples being drawn from the proposal at every iteration. |
10000
|
show_progress_bars
|
bool
|
Whether to show a progressbar during sampling. |
False
|
Source code in sbi/inference/posteriors/importance_posterior.py
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 |
|
MCMCPosterior
¶
Bases: NeuralPosterior
Provides MCMC to sample from the posterior.
SNLE or SNRE train neural networks to approximate the likelihood(-ratios).
MCMCPosterior
allows to sample from the posterior with MCMC.
Source code in sbi/inference/posteriors/mcmc_posterior.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 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 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 |
|
mcmc_method: str
property
writable
¶
Returns MCMC method.
posterior_sampler
property
¶
Returns sampler created by sample
.
__getstate__()
¶
Get state of MCMCPosterior.
Removes the posterior sampler from the state, as it may not be picklable.
Returns:
Name | Type | Description |
---|---|---|
Dict |
Dict
|
State of MCMCPosterior. |
Source code in sbi/inference/posteriors/mcmc_posterior.py
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 |
|
__init__(potential_fn, proposal, theta_transform=None, method='slice_np_vectorized', thin=-1, warmup_steps=200, num_chains=20, init_strategy='resample', init_strategy_parameters=None, init_strategy_num_candidates=None, num_workers=1, mp_context='spawn', device=None, x_shape=None)
¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
potential_fn
|
Union[Callable, BasePotential]
|
The potential function from which to draw samples. Must be a
|
required |
proposal
|
Any
|
Proposal distribution that is used to initialize the MCMC chain. |
required |
theta_transform
|
Optional[TorchTransform]
|
Transformation that will be applied during sampling. Allows to perform MCMC in unconstrained space. |
None
|
method
|
str
|
Method used for MCMC sampling, one of |
'slice_np_vectorized'
|
thin
|
int
|
The thinning factor for the chain, default 1 (no thinning). |
-1
|
warmup_steps
|
int
|
The initial number of samples to discard. |
200
|
num_chains
|
int
|
The number of chains. Should generally be at most
|
20
|
init_strategy
|
str
|
The initialisation strategy for chains; |
'resample'
|
init_strategy_parameters
|
Optional[Dict[str, Any]]
|
Dictionary of keyword arguments passed to the
init strategy, e.g., for |
None
|
init_strategy_num_candidates
|
Optional[int]
|
Number of candidates to find init
locations in |
None
|
num_workers
|
int
|
number of cpu cores used to parallelize mcmc |
1
|
mp_context
|
str
|
Multiprocessing start method, either |
'spawn'
|
device
|
Optional[str]
|
Training device, e.g., “cpu”, “cuda” or “cuda:0”. If None,
|
None
|
x_shape
|
Optional[Size]
|
Deprecated, should not be passed. |
None
|
Source code in sbi/inference/posteriors/mcmc_posterior.py
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 |
|
get_arviz_inference_data()
¶
Returns arviz InferenceData object constructed most recent samples.
Note: the InferenceData is constructed using the posterior samples generated in
most recent call to .sample(...)
.
For Pyro and PyMC samplers, InferenceData will contain diagnostics, but for sbi slice samplers, only the samples are added.
Returns:
Name | Type | Description |
---|---|---|
inference_data |
InferenceData
|
Arviz InferenceData object. |
Source code in sbi/inference/posteriors/mcmc_posterior.py
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 |
|
log_prob(theta, x=None, track_gradients=False)
¶
Returns the log-probability of theta under the posterior.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
theta
|
Tensor
|
Parameters \(\theta\). |
required |
track_gradients
|
bool
|
Whether the returned tensor supports tracking gradients. This can be helpful for e.g. sensitivity analysis, but increases memory consumption. |
False
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Source code in sbi/inference/posteriors/mcmc_posterior.py
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 |
|
map(x=None, num_iter=1000, num_to_optimize=100, learning_rate=0.01, init_method='proposal', num_init_samples=1000, save_best_every=10, show_progress_bars=False, force_update=False)
¶
Returns the maximum-a-posteriori estimate (MAP).
The method can be interrupted (Ctrl-C) when the user sees that the
log-probability converges. The best estimate will be saved in self._map
and
can be accessed with self.map()
. The MAP is obtained by running gradient
ascent from a given number of starting positions (samples from the posterior
with the highest log-probability). After the optimization is done, we select the
parameter set that has the highest log-probability after the optimization.
Warning: The default values used by this function are not well-tested. They might require hand-tuning for the problem at hand.
For developers: if the prior is a BoxUniform
, we carry out the optimization
in unbounded space and transform the result back into bounded space.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Optional[Tensor]
|
Deprecated - use |
None
|
num_iter
|
int
|
Number of optimization steps that the algorithm takes to find the MAP. |
1000
|
learning_rate
|
float
|
Learning rate of the optimizer. |
0.01
|
init_method
|
Union[str, Tensor]
|
How to select the starting parameters for the optimization. If
it is a string, it can be either [ |
'proposal'
|
num_init_samples
|
int
|
Draw this number of samples from the posterior and evaluate the log-probability of all of them. |
1000
|
num_to_optimize
|
int
|
From the drawn |
100
|
save_best_every
|
int
|
The best log-probability is computed, saved in the
|
10
|
show_progress_bars
|
bool
|
Whether to show a progressbar during sampling from the posterior. |
False
|
force_update
|
bool
|
Whether to re-calculate the MAP when x is unchanged and have a cached value. |
False
|
log_prob_kwargs
|
Will be empty for SNLE and SNRE. Will contain {‘norm_posterior’: True} for SNPE. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The MAP estimate. |
Source code in sbi/inference/posteriors/mcmc_posterior.py
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 |
|
sample(sample_shape=torch.Size(), x=None, method=None, thin=None, warmup_steps=None, num_chains=None, init_strategy=None, init_strategy_parameters=None, init_strategy_num_candidates=None, mcmc_parameters=None, mcmc_method=None, sample_with=None, num_workers=None, mp_context=None, show_progress_bars=True)
¶
Return samples from posterior distribution \(p(\theta|x)\) with MCMC.
Check the __init__()
method for a description of all arguments as well as
their default values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_shape
|
Shape
|
Desired shape of samples that are drawn from posterior. If
sample_shape is multidimensional we simply draw |
Size()
|
mcmc_parameters
|
Optional[Dict]
|
Dictionary that is passed only to support the API of
|
None
|
mcmc_method
|
Optional[str]
|
This argument only exists to keep backward-compatibility with
|
None
|
sample_with
|
Optional[str]
|
This argument only exists to keep backward-compatibility with
|
None
|
show_progress_bars
|
bool
|
Whether to show sampling progress monitor. |
True
|
Returns:
Type | Description |
---|---|
Tensor
|
Samples from posterior. |
Source code in sbi/inference/posteriors/mcmc_posterior.py
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 |
|
sample_batched(sample_shape, x, method=None, thin=None, warmup_steps=None, num_chains=None, init_strategy=None, init_strategy_parameters=None, num_workers=None, mp_context=None, show_progress_bars=True)
¶
Given a batch of observations [x_1, …, x_B] this function samples from posteriors \(p(\theta|x_1)\), … ,\(p(\theta|x_B)\), in a batched (i.e. vectorized) manner.
Check the __init__()
method for a description of all arguments as well as
their default values.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_shape
|
Shape
|
Desired shape of samples that are drawn from the posterior given every observation. |
required |
x
|
Tensor
|
A batch of observations, of shape |
required |
method
|
Optional[str]
|
Method used for MCMC sampling, e.g., “slice_np_vectorized”. |
None
|
thin
|
Optional[int]
|
The thinning factor for the chain, default 1 (no thinning). |
None
|
warmup_steps
|
Optional[int]
|
The initial number of samples to discard. |
None
|
num_chains
|
Optional[int]
|
The number of chains used for each |
None
|
init_strategy
|
Optional[str]
|
The initialisation strategy for chains. |
None
|
init_strategy_parameters
|
Optional[Dict[str, Any]]
|
Dictionary of keyword arguments passed to the init strategy. |
None
|
num_workers
|
Optional[int]
|
number of cpu cores used to parallelize initial parameter generation and mcmc sampling. |
None
|
mp_context
|
Optional[str]
|
Multiprocessing start method, either |
None
|
show_progress_bars
|
bool
|
Whether to show sampling progress monitor. |
True
|
Returns:
Type | Description |
---|---|
Tensor
|
Samples from the posteriors of shape (*sample_shape, B, *input_shape) |
Source code in sbi/inference/posteriors/mcmc_posterior.py
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 |
|
set_mcmc_method(method)
¶
Sets sampling method to for MCMC and returns NeuralPosterior
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
Method to use. |
required |
Returns:
Type | Description |
---|---|
NeuralPosterior
|
|
Source code in sbi/inference/posteriors/mcmc_posterior.py
170 171 172 173 174 175 176 177 178 179 180 |
|
RejectionPosterior
¶
Bases: NeuralPosterior
Provides rejection sampling to sample from the posterior.
SNLE or SNRE train neural networks to approximate the likelihood(-ratios).
RejectionPosterior
allows to sample from the posterior with rejection sampling.
Source code in sbi/inference/posteriors/rejection_posterior.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 235 236 237 238 239 240 241 242 243 244 245 246 |
|
__init__(potential_fn, proposal, theta_transform=None, max_sampling_batch_size=10000, num_samples_to_find_max=10000, num_iter_to_find_max=100, m=1.2, device=None, x_shape=None)
¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
potential_fn
|
Union[Callable, BasePotential]
|
The potential function from which to draw samples. Must be a
|
required |
proposal
|
Any
|
The proposal distribution. |
required |
theta_transform
|
Optional[TorchTransform]
|
Transformation that is applied to parameters. Is not used
during but only when calling |
None
|
max_sampling_batch_size
|
int
|
The batchsize of samples being drawn from the proposal at every iteration. |
10000
|
num_samples_to_find_max
|
int
|
The number of samples that are used to find the
maximum of the |
10000
|
num_iter_to_find_max
|
int
|
The number of gradient ascent iterations to find the
maximum of the |
100
|
m
|
float
|
Multiplier to the |
1.2
|
device
|
Optional[str]
|
Training device, e.g., “cpu”, “cuda” or “cuda:0”. If None,
|
None
|
x_shape
|
Optional[Size]
|
Deprecated, should not be passed. |
None
|
Source code in sbi/inference/posteriors/rejection_posterior.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 |
|
log_prob(theta, x=None, track_gradients=False)
¶
Returns the log-probability of theta under the posterior.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
theta
|
Tensor
|
Parameters \(\theta\). |
required |
track_gradients
|
bool
|
Whether the returned tensor supports tracking gradients. This can be helpful for e.g. sensitivity analysis, but increases memory consumption. |
False
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Source code in sbi/inference/posteriors/rejection_posterior.py
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 |
|
map(x=None, num_iter=1000, num_to_optimize=100, learning_rate=0.01, init_method='proposal', num_init_samples=1000, save_best_every=10, show_progress_bars=False, force_update=False)
¶
Returns the maximum-a-posteriori estimate (MAP).
The method can be interrupted (Ctrl-C) when the user sees that the
log-probability converges. The best estimate will be saved in self._map
and
can be accessed with self.map()
. The MAP is obtained by running gradient
ascent from a given number of starting positions (samples from the posterior
with the highest log-probability). After the optimization is done, we select the
parameter set that has the highest log-probability after the optimization.
Warning: The default values used by this function are not well-tested. They might require hand-tuning for the problem at hand.
For developers: if the prior is a BoxUniform
, we carry out the optimization
in unbounded space and transform the result back into bounded space.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Optional[Tensor]
|
Deprecated - use |
None
|
num_iter
|
int
|
Number of optimization steps that the algorithm takes to find the MAP. |
1000
|
learning_rate
|
float
|
Learning rate of the optimizer. |
0.01
|
init_method
|
Union[str, Tensor]
|
How to select the starting parameters for the optimization. If
it is a string, it can be either [ |
'proposal'
|
num_init_samples
|
int
|
Draw this number of samples from the posterior and evaluate the log-probability of all of them. |
1000
|
num_to_optimize
|
int
|
From the drawn |
100
|
save_best_every
|
int
|
The best log-probability is computed, saved in the
|
10
|
show_progress_bars
|
bool
|
Whether to show a progressbar during sampling from the posterior. |
False
|
force_update
|
bool
|
Whether to re-calculate the MAP when x is unchanged and have a cached value. |
False
|
log_prob_kwargs
|
Will be empty for SNLE and SNRE. Will contain {‘norm_posterior’: True} for SNPE. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The MAP estimate. |
Source code in sbi/inference/posteriors/rejection_posterior.py
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 |
|
sample(sample_shape=torch.Size(), x=None, max_sampling_batch_size=None, num_samples_to_find_max=None, num_iter_to_find_max=None, m=None, sample_with=None, show_progress_bars=True)
¶
Return samples from posterior \(p(\theta|x)\) via rejection sampling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_shape
|
Shape
|
Desired shape of samples that are drawn from posterior. If
sample_shape is multidimensional we simply draw |
Size()
|
sample_with
|
Optional[str]
|
This argument only exists to keep backward-compatibility with
|
None
|
show_progress_bars
|
bool
|
Whether to show sampling progress monitor. |
True
|
Returns:
Type | Description |
---|---|
Samples from posterior. |
Source code in sbi/inference/posteriors/rejection_posterior.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 158 159 160 161 162 163 164 165 166 |
|
ScorePosterior
¶
Bases: NeuralPosterior
Posterior \(p(\theta|x_o)\) with log_prob()
and sample()
methods. It samples
from the diffusion model given the score_estimator and rejects samples that lie
outside of the prior bounds.
The posterior is defined by a score estimator and a prior. The score estimator provides the gradient of the log-posterior with respect to the parameters. The prior is used to reject samples that lie outside of the prior bounds.
Sampling is done by running a diffusion process with a predictor and optionally a corrector.
Log probabilities are obtained by calling the potential function, which in turn uses zuko probabilistic ODEs to compute the log-probability.
Source code in sbi/inference/posteriors/score_posterior.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 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 |
|
__init__(score_estimator, prior, max_sampling_batch_size=10000, device=None, enable_transform=False, sample_with='sde')
¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
prior
|
Distribution
|
Prior distribution with |
required |
score_estimator
|
ConditionalScoreEstimator
|
The trained neural score estimator. |
required |
max_sampling_batch_size
|
int
|
Batchsize of samples being drawn from the proposal at every iteration. |
10000
|
device
|
Optional[str]
|
Training device, e.g., “cpu”, “cuda” or “cuda:0”. If None,
|
None
|
enable_transform
|
bool
|
Whether to transform parameters to unconstrained space
during MAP optimization. When False, an identity transform will be
returned for |
False
|
sample_with
|
str
|
Whether to sample from the posterior using the ODE-based sampler or the SDE-based sampler. |
'sde'
|
Source code in sbi/inference/posteriors/score_posterior.py
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 |
|
log_prob(theta, x=None, track_gradients=False, atol=1e-05, rtol=1e-06, exact=True)
¶
Returns the log-probability of the posterior \(p(\theta|x)\).
This requires building and evaluating the probability flow ODE.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
theta
|
Tensor
|
Parameters \(\theta\). |
required |
x
|
Optional[Tensor]
|
Observed data \(x_o\). If None, the default \(x_o\) is used. |
None
|
track_gradients
|
bool
|
Whether the returned tensor supports tracking gradients. This can be helpful for e.g. sensitivity analysis, but increases memory consumption. |
False
|
atol
|
float
|
Absolute tolerance for the ODE solver. |
1e-05
|
rtol
|
float
|
Relative tolerance for the ODE solver. |
1e-06
|
exact
|
bool
|
Whether to use the exact Jacobian of the transformation or an stochastic approximation, which is faster but less accurate. |
True
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Tensor
|
support of the prior, -∞ (corresponding to 0 probability) outside. |
Source code in sbi/inference/posteriors/score_posterior.py
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 |
|
map(x=None, num_iter=1000, num_to_optimize=1000, learning_rate=1e-05, init_method='posterior', num_init_samples=1000, save_best_every=1000, show_progress_bars=False, force_update=False)
¶
Returns the maximum-a-posteriori estimate (MAP).
The method can be interrupted (Ctrl-C) when the user sees that the
log-probability converges. The best estimate will be saved in self._map
and
can be accessed with self.map()
. The MAP is obtained by running gradient
ascent from a given number of starting positions (samples from the posterior
with the highest log-probability). After the optimization is done, we select the
parameter set that has the highest log-probability after the optimization.
Warning: The default values used by this function are not well-tested. They might require hand-tuning for the problem at hand.
For developers: if the prior is a BoxUniform
, we carry out the optimization
in unbounded space and transform the result back into bounded space.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Optional[Tensor]
|
Deprecated - use |
None
|
num_iter
|
int
|
Number of optimization steps that the algorithm takes to find the MAP. |
1000
|
num_to_optimize
|
int
|
From the drawn |
1000
|
learning_rate
|
float
|
Learning rate of the optimizer. |
1e-05
|
init_method
|
Union[str, Tensor]
|
How to select the starting parameters for the optimization. If
it is a string, it can be either [ |
'posterior'
|
num_init_samples
|
int
|
Draw this number of samples from the posterior and evaluate the log-probability of all of them. |
1000
|
save_best_every
|
int
|
The best log-probability is computed, saved in the
|
1000
|
show_progress_bars
|
bool
|
Whether to show a progressbar during sampling from the posterior. |
False
|
force_update
|
bool
|
Whether to re-calculate the MAP when x is unchanged and have a cached value. |
False
|
Returns:
Type | Description |
---|---|
Tensor
|
The MAP estimate. |
Source code in sbi/inference/posteriors/score_posterior.py
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 |
|
sample(sample_shape=torch.Size(), x=None, predictor='euler_maruyama', corrector=None, predictor_params=None, corrector_params=None, steps=500, ts=None, max_sampling_batch_size=10000, sample_with=None, show_progress_bars=True)
¶
Return samples from posterior distribution \(p(\theta|x)\).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_shape
|
Shape
|
Shape of the samples to be drawn. |
Size()
|
x
|
Optional[Tensor]
|
Deprecated - use |
None
|
predictor
|
Union[str, Predictor]
|
The predictor for the diffusion-based sampler. Can be a string or
a custom predictor following the API in |
'euler_maruyama'
|
corrector
|
Optional[Union[str, Corrector]]
|
The corrector for the diffusion-based sampler. Either of [None]. |
None
|
predictor_params
|
Optional[Dict]
|
Additional parameters passed to predictor. |
None
|
corrector_params
|
Optional[Dict]
|
Additional parameters passed to corrector. |
None
|
steps
|
int
|
Number of steps to take for the Euler-Maruyama method. |
500
|
ts
|
Optional[Tensor]
|
Time points at which to evaluate the diffusion process. If None, a linear grid between t_max and t_min is used. |
None
|
max_sampling_batch_size
|
int
|
Maximum batch size for sampling. |
10000
|
sample_with
|
Optional[str]
|
Deprecated - use |
None
|
show_progress_bars
|
bool
|
Whether to show a progress bar during sampling. |
True
|
Source code in sbi/inference/posteriors/score_posterior.py
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 |
|
sample_via_zuko(x, sample_shape=torch.Size())
¶
Return samples from posterior distribution with probability flow ODE.
This build the probability flow ODE and then samples from the corresponding flow. This is implemented via the zuko library.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Tensor
|
Condition. |
required |
sample_shape
|
Shape
|
The shape of the samples to be returned. |
Size()
|
Returns:
Type | Description |
---|---|
Tensor
|
Samples. |
Source code in sbi/inference/posteriors/score_posterior.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 |
|
VIPosterior
¶
Bases: NeuralPosterior
Provides VI (Variational Inference) to sample from the posterior.
SNLE or SNRE train neural networks to approximate the likelihood(-ratios).
VIPosterior
allows to learn a tractable variational posterior \(q(\theta)\) which
approximates the true posterior \(p(\theta|x_o)\). After this second training stage,
we can produce approximate posterior samples, by just sampling from q with no
additional cost. For additional information see [1] and [2].
References:
[1] Variational methods for simulation-based inference, Manuel Glöckler, Michael
Deistler, Jakob Macke, 2022, https://openreview.net/forum?id=kZ0UYdhqkNY
[2] Sequential Neural Posterior and Likelihood Approximation, Samuel Wiqvist, Jes
Frellsen, Umberto Picchini, 2021, https://arxiv.org/abs/2102.06522
Source code in sbi/inference/posteriors/vi_posterior.py
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 |
|
q: Distribution
property
writable
¶
Returns the variational posterior.
vi_method: str
property
writable
¶
Variational inference method e.g. one of [rKL, fKL, IW, alpha].
__deepcopy__(memo=None)
¶
This method is called when using copy.deepcopy
on the object.
It defines how the object is copied. We need to overwrite this method, since the default implementation does use getstate and setstate which we overwrite to enable pickling (and in particular the necessary modifications are incompatible deep copying).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
memo
|
Optional[Dict]
|
Deep copy internal memo. Defaults to None. |
None
|
Returns:
Name | Type | Description |
---|---|---|
VIPosterior |
VIPosterior
|
Deep copy of the VIPosterior. |
Source code in sbi/inference/posteriors/vi_posterior.py
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 |
|
__getstate__()
¶
This method is called when pickling the object.
It defines what is pickled. We need to overwrite this method, since some parts due not support pickle protocols (e.g. due to local functions, etc.).
Returns:
Name | Type | Description |
---|---|---|
Dict |
Dict
|
All attributes of the VIPosterior. |
Source code in sbi/inference/posteriors/vi_posterior.py
608 609 610 611 612 613 614 615 616 617 618 619 620 621 |
|
__init__(potential_fn, prior=None, q='maf', theta_transform=None, vi_method='rKL', device='cpu', x_shape=None, parameters=[], modules=[])
¶
Parameters:
Name | Type | Description | Default |
---|---|---|---|
potential_fn
|
Union[Callable, BasePotential]
|
The potential function from which to draw samples. Must be a
|
required |
prior
|
Optional[TorchDistribution]
|
This is the prior distribution. Note that this is only
used to check/construct the variational distribution or within some
quality metrics. Please make sure that this matches with the prior
within the potential_fn. If |
None
|
q
|
Union[str, PyroTransformedDistribution, VIPosterior, Callable]
|
Variational distribution, either string, |
'maf'
|
theta_transform
|
Optional[TorchTransform]
|
Maps form prior support to unconstrained space. The inverse is used here to ensure that the posterior support is equal to that of the prior. |
None
|
vi_method
|
str
|
This specifies the variational methods which are used to fit q to
the posterior. We currently support [rKL, fKL, IW, alpha]. Note that
some of the divergences are |
'rKL'
|
device
|
str
|
Training device, e.g., |
'cpu'
|
x_shape
|
Optional[Size]
|
Deprecated, should not be passed. |
None
|
parameters
|
Iterable
|
List of parameters of the variational posterior. This is only
required for user-defined q i.e. if q does not have a |
[]
|
modules
|
Iterable
|
List of modules of the variational posterior. This is only
required for user-defined q i.e. if q does not have a |
[]
|
Source code in sbi/inference/posteriors/vi_posterior.py
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 |
|
__setstate__(state_dict)
¶
This method is called when unpickling the object.
Especially, we need to restore the removed attributes and ensure that the object e.g. remains deep copy compatible.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state_dict
|
Dict
|
Given state dictionary, we will restore the object from it. |
required |
Source code in sbi/inference/posteriors/vi_posterior.py
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 |
|
evaluate(quality_control_metric='psis', N=int(50000.0))
¶
This function will evaluate the quality of the variational posterior
distribution. We currently support two different metrics of type psis
, which
checks the quality based on the tails of importance weights (there should not be
much with a large one), or prop
which checks the proportionality between q
and potential_fn.
NOTE: In our experience prop
is sensitive to distinguish good
from ok
whereas psis
is more sensitive in distinguishing very bad
from ok
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
quality_control_metric
|
str
|
The metric of choice, we currently support [psis, prop, prop_prior]. |
'psis'
|
N
|
int
|
Number of samples which is used to evaluate the metric. |
int(50000.0)
|
Source code in sbi/inference/posteriors/vi_posterior.py
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 |
|
log_prob(theta, x=None, track_gradients=False)
¶
Returns the log-probability of theta under the variational posterior.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
theta
|
Tensor
|
Parameters |
required |
track_gradients
|
bool
|
Whether the returned tensor supports tracking gradients. This can be helpful for e.g. sensitivity analysis but increases memory consumption. |
False
|
Returns:
Type | Description |
---|---|
Tensor
|
|
Source code in sbi/inference/posteriors/vi_posterior.py
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 |
|
map(x=None, num_iter=1000, num_to_optimize=100, learning_rate=0.01, init_method='proposal', num_init_samples=10000, save_best_every=10, show_progress_bars=False, force_update=False)
¶
Returns the maximum-a-posteriori estimate (MAP).
The method can be interrupted (Ctrl-C) when the user sees that the
log-probability converges. The best estimate will be saved in self._map
and
can be accessed with self.map()
. The MAP is obtained by running gradient
ascent from a given number of starting positions (samples from the posterior
with the highest log-probability). After the optimization is done, we select the
parameter set that has the highest log-probability after the optimization.
Warning: The default values used by this function are not well-tested. They might require hand-tuning for the problem at hand.
For developers: if the prior is a BoxUniform
, we carry out the optimization
in unbounded space and transform the result back into bounded space.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Optional[TorchTensor]
|
Deprecated - use |
None
|
num_iter
|
int
|
Number of optimization steps that the algorithm takes to find the MAP. |
1000
|
learning_rate
|
float
|
Learning rate of the optimizer. |
0.01
|
init_method
|
Union[str, TorchTensor]
|
How to select the starting parameters for the optimization. If
it is a string, it can be either [ |
'proposal'
|
num_init_samples
|
int
|
Draw this number of samples from the posterior and evaluate the log-probability of all of them. |
10000
|
num_to_optimize
|
int
|
From the drawn |
100
|
save_best_every
|
int
|
The best log-probability is computed, saved in the
|
10
|
show_progress_bars
|
bool
|
Whether to show a progressbar during sampling from the posterior. |
False
|
force_update
|
bool
|
Whether to re-calculate the MAP when x is unchanged and have a cached value. |
False
|
log_prob_kwargs
|
Will be empty for SNLE and SNRE. Will contain {‘norm_posterior’: True} for SNPE. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The MAP estimate. |
Source code in sbi/inference/posteriors/vi_posterior.py
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 |
|
sample(sample_shape=torch.Size(), x=None, **kwargs)
¶
Samples from the variational posterior distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
sample_shape
|
Shape
|
Shape of samples |
Size()
|
Returns:
Type | Description |
---|---|
Tensor
|
Samples from posterior. |
Source code in sbi/inference/posteriors/vi_posterior.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 |
|
set_q(q, parameters=[], modules=[])
¶
Defines the variational family.
You can specify over which parameters/modules we optimize. This is required for
custom distributions which e.g. do not inherit nn.Modules or has the function
parameters
or modules
to give direct access to trainable parameters.
Further, you can pass a function, which constructs a variational distribution
if called.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
q
|
Union[str, PyroTransformedDistribution, VIPosterior, Callable]
|
Variational distribution, either string, distribution, or a VIPosterior
object. This specifies a parametric class of distribution over which
the best possible posterior approximation is searched. For string input,
we currently support [nsf, scf, maf, mcf, gaussian, gaussian_diag]. Of
course, you can also specify your own variational family by passing a
|
required |
parameters
|
Iterable
|
List of parameters associated with the distribution object. |
[]
|
modules
|
Iterable
|
List of modules associated with the distribution object. |
[]
|
Source code in sbi/inference/posteriors/vi_posterior.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 |
|
set_vi_method(method)
¶
Sets variational inference method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
One of [rKL, fKL, IW, alpha]. |
required |
Returns:
Type | Description |
---|---|
VIPosterior
|
|
Source code in sbi/inference/posteriors/vi_posterior.py
263 264 265 266 267 268 269 270 271 272 273 274 |
|
train(x=None, n_particles=256, learning_rate=0.001, gamma=0.999, max_num_iters=2000, min_num_iters=10, clip_value=10.0, warm_up_rounds=100, retrain_from_scratch=False, reset_optimizer=False, show_progress_bar=True, check_for_convergence=True, quality_control=True, quality_control_metric='psis', **kwargs)
¶
This method trains the variational posterior.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x
|
Optional[TorchTensor]
|
The observation. |
None
|
n_particles
|
int
|
Number of samples to approximate expectations within the variational bounds. The larger the more accurate are gradient estimates, but the computational cost per iteration increases. |
256
|
learning_rate
|
float
|
Learning rate of the optimizer. |
0.001
|
gamma
|
float
|
Learning rate decay per iteration. We use an exponential decay scheduler. |
0.999
|
max_num_iters
|
int
|
Maximum number of iterations. |
2000
|
min_num_iters
|
int
|
Minimum number of iterations. |
10
|
clip_value
|
float
|
Gradient clipping value, decreasing may help if you see invalid values. |
10.0
|
warm_up_rounds
|
int
|
Initialize the posterior as the prior. |
100
|
retrain_from_scratch
|
bool
|
Retrain the variational distributions from scratch. |
False
|
reset_optimizer
|
bool
|
Reset the divergence optimizer |
False
|
show_progress_bar
|
bool
|
If any progress report should be displayed. |
True
|
quality_control
|
bool
|
If False quality control is skipped. |
True
|
quality_control_metric
|
str
|
Which metric to use for evaluating the quality. |
'psis'
|
kwargs
|
Hyperparameters check corresponding |
{}
|
Returns:
VIPosterior: VIPosterior
(can be used to chain calls).
Source code in sbi/inference/posteriors/vi_posterior.py
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 |
|