AI-generated. An AI assistant drafted this page, and no maintainer has reviewed it yet. Please report errors on the issue tracker.
Validation¶
This page documents the predictive checks, the scores of an approximate posterior against a reference posterior, and simulation-based calibration. The diagnostics recorded on a posterior, such as R-hat and leave-one-out cross-validation, are on Diagnostics.
Predictive checks¶
predictive_check(kernel, law, test_fns, observed_data=None, *, num_replications=500)
¶
Compare replicated data with the observed data through test statistics.
A replication is a draw of the kernel's event from the merge
kernel & law, which draws the inputs from law and then the
kernel's event at those values. With the posterior as law the check is a
posterior predictive check, and with the prior it is a prior predictive
check. Each statistic is computed on the same replications and, when
observed_data is given, on the observed data; its p-value is the fraction
of replications whose statistic is at least the observed one.
A statistic receives a replication in the form the kernel declares for its
event: a whole term is its value, such as an array, and a record whose
fields are the kernel's outputs is the mapping of its fields. A statistic
that JAX can trace is computed on every replication in one jax.vmap
call, and any other in a loop.
The replications are one workflow-owned random event of the enclosing
workflow scope. A call inside workflow_run(seed=...) therefore
reproduces them, and a call outside every scope draws fresh replications.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kernel
|
ConditionalDistribution
|
The law of the observations given the parameters, such as the
likelihood of a model |
required |
law
|
Distribution
|
A law over the kernel's inputs: the posterior for a posterior
predictive check, or the prior for a prior predictive check. A
|
required |
test_fns
|
callable or sequence of callables
|
One or more test statistics, each mapping a dataset to a scalar. A
statistic is named by its |
required |
observed_data
|
optional
|
The observed data, in the form of a replication, or as a mapping from
the kernel's outputs to their values, the form |
None
|
num_replications
|
int
|
The number of replications. |
500
|
Returns:
| Type | Description |
|---|---|
Record
|
For a single statistic, the record has the fields:
For a sequence of statistics, each statistic's fields are nested
under its name, so |
Raises:
| Type | Description |
|---|---|
TypeError
|
If kernel is not a |
ValueError
|
If law has no output for some input of kernel, naming the missing inputs; if law has an output of the same name as an output of kernel; if test_fns is empty or holds two statistics of the same name; or if num_replications is not positive. |
Notes
Each statistic's result is also recorded in law.annotations, as the
next child check_N of the group predictive_check: a dataset with
the variable replicated_statistics over the dimension
replication, and the attributes test_fn_name and, when
observed_data is given, observed_statistic and p_value.
Examples:
>>> import jax.numpy as jnp
>>> from probpipe import Normal, conditional_distribution, workflow_run
>>> prior = Normal("mu", 0.0, 1.0)
>>> likelihood = conditional_distribution(
... lambda mu: Normal("y", mu * jnp.ones(10), 1.0),
... label="y_given_mu",
... given_spec=prior.event_spec.outputs,
... )
>>> with workflow_run(seed=0):
... check = predictive_check(likelihood, prior, jnp.mean, jnp.zeros(10))
>>> check["replicated_statistics"].num_atoms
500
>>> 0.0 <= float(check["p_value"]) <= 1.0
True
Source code in probpipe/validation/_predictive_check.py
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 | |
Scores against a reference posterior¶
probpipe.validation.Reference(mean=None, cov=None, draws=None, score_fn=None)
dataclass
¶
A reference posterior to score an approximation against.
Carries whichever pieces are available so analytic, long-NUTS, and sandwich
references share one interface: high-precision moments (mean, cov) (for
the moment metrics), draws (for the sample-based distances), and a
score_fn = ∇ log π (for ksd).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
Array or None
|
Reference mean |
None
|
cov
|
Array or None
|
Reference covariance |
None
|
draws
|
Array or None
|
Reference draws, shape |
None
|
score_fn
|
callable or None
|
|
None
|
from_draws(draws, *, score_fn=None)
classmethod
¶
Build a reference from draws, deriving (mean, cov) from them.
Source code in probpipe/validation/_comparison.py
from_moments(mean, cov, *, draws=None, score_fn=None)
classmethod
¶
Build a reference from high-precision analytic/empirical moments.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mean
|
array - like
|
Reference mean |
required |
cov
|
array - like
|
Reference covariance |
required |
draws
|
array - like or EmpiricalDistribution
|
Reference draws for the sample-based distances: a raw |
None
|
score_fn
|
callable
|
|
None
|
Returns:
| Type | Description |
|---|---|
Reference
|
The reference, with mean and cov as JAX arrays and draws as an
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in probpipe/validation/_comparison.py
probpipe.validation.score_posterior(approx, reference, *, metrics=_DEFAULT_METRICS)
¶
Score approx against reference on the named metrics → a scorecard dict.
Metrics whose required reference pieces are absent (e.g. ksd without a
score_fn, or the sample distances without draws) are skipped rather
than erroring, so one call serves analytic, long-NUTS, and sandwich
references. Reused by the test suite and the probpipe-benchmark harness.
The random projections of sliced_wasserstein are one workflow-owned
random event of the enclosing workflow scope, which a call claims only when
it scores that metric. A call inside workflow_run(seed=...) therefore
reproduces the scorecard, and a call outside every scope draws fresh
projections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
approx
|
array - like or EmpiricalDistribution
|
The approximation's draws: an |
required |
reference
|
Reference
|
The reference posterior to score against. |
required |
metrics
|
str or sequence of str
|
The metrics to score, among |
_DEFAULT_METRICS
|
Returns:
| Type | Description |
|---|---|
dict of str to Array
|
The value of each scored metric under its name, in the order of
metrics: a 0-d array, or a |
Raises:
| Type | Description |
|---|---|
ValueError
|
If metrics names an unknown metric, or if the draws a scored metric
reads are not an |
RuntimeError
|
If sliced Wasserstein scoring claims workflow-owned randomness inside
a JAX transformation opened by the caller, such as |
TypeError
|
If metrics is not a str or a sequence of str. |
Notes
For JAX transformations, call sliced_wasserstein with an explicit key.
Sharing a key across mapped inputs shares their random projections;
passing a separate key to each input gives independent projections.
The random-event guard checks only metrics that claim workflow-owned randomness.
Source code in probpipe/validation/_comparison.py
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 | |
probpipe.validation.standardized_mean_error(approx, ref)
¶
Mean error in posterior-standard-deviation units: ‖Σ_ref^{-1/2}(μ̂ − μ_ref)‖₂.
The Mahalanobis distance between the approximate mean μ̂ and the
reference mean μ_ref under Σ_ref — scale- and rotation-invariant,
reported in units of reference posterior standard deviations. Computed as
‖L⁻¹(μ̂ − μ_ref)‖₂ with L = chol(Σ_ref).
Source code in probpipe/validation/_comparison.py
probpipe.validation.relative_cov_error(approx, ref)
¶
Operator-norm whitened covariance error: ‖I − Σ_ref^{-1/2} Σ̂ Σ_ref^{-1/2}‖₂.
The spectral norm of the symmetrically whitened covariance deviation from
identity. Because the whitened matrix is symmetric, this equals the
worst-direction variance-ratio error max_d |1 − λ_d|, where the λ_d
are the eigenvalues of Σ_ref⁻¹ Σ̂ (the generalized variance ratios) —
0 iff Σ̂ = Σ_ref. The whitening Σ_ref^{-1/2} Σ̂ Σ_ref^{-1/2} is
computed as L⁻¹ Σ̂ L⁻ᵀ via two triangular solves, L = chol(Σ_ref).
Source code in probpipe/validation/_comparison.py
probpipe.validation.std_ratios(approx, ref)
¶
Per-coordinate standard-deviation ratios σ̂_d / σ_{ref,d} (a (d,) array).
A coordinate-wise readout for reporting; the full-covariance
relative_cov_error subsumes it. A reference coordinate with zero
variance yields inf for that ratio.
Source code in probpipe/validation/_comparison.py
probpipe.validation.sliced_wasserstein(x, y, *, key, n_projections=128)
¶
Sliced 2-Wasserstein distance between two sets of draws.
Projects x and y onto n_projections random unit directions and
returns (mean_θ W₂²(P_θ x, P_θ y))^{1/2}. Each 1-D W₂² is computed
exactly from the order statistics — including unequal sample sizes, by
integrating (Q_x − Q_y)² over the union of the two empirical-CDF level
sets (no quantile-grid approximation).
Source code in probpipe/validation/_comparison.py
probpipe.validation.mmd(x, y, *, bandwidth='median')
¶
Unbiased squared MMD with an RBF kernel.
MMD²_u = mean_{i≠j} k(xᵢ,xⱼ) + mean_{i≠j} k(yᵢ,yⱼ) − 2·mean_{i,j} k(xᵢ,yⱼ),
k(a,b) = exp(−‖a−b‖² / ℓ²). With bandwidth="median" the length-scale
ℓ² is the median cross-pair squared distance (a fixed-shape, jit-safe
heuristic). The unbiased estimator can be slightly negative.
Source code in probpipe/validation/_comparison.py
probpipe.validation.ksd(x, score_fn, *, bandwidth='median')
¶
Kernel Stein discrepancy with the inverse-multiquadric (IMQ) kernel.
The U-statistic KSD = (mean_{i≠j} u_p(xᵢ,xⱼ))^{1/2} for the Stein kernel
u_p of the IMQ base kernel k(a,b) = (c² + ‖a−b‖²)^{-1/2} and score
sₚ = ∇ log π. With bandwidth="median", c² is the median
off-diagonal squared distance. Needs no reference draws — a gradient-based
goodness-of-fit to the target π; → 0 as the draws come to match
π.
Source code in probpipe/validation/_comparison.py
Calibration and coverage¶
probpipe.validation.simulation_based_calibration(model, *, observed, num_simulations, num_posterior_draws, posterior=None, method=None, method_options=None)
¶
Simulation-based calibration of a posterior (Talts et al. 2018).
Each of num_simulations replications draws the parameters θ★ and the
observed fields y from the joint model, forms the posterior at
y, draws from it, and ranks each entry of the flattened θ★ among the
draws. Under a calibrated posterior each rank is uniform on
{0, …, num_posterior_draws}. The result summarizes each parameter's
ranks by their KS distance from uniform and its p-value.
The posterior at y is formed in one of two ways:
- with posterior, it is the kernel's law at
y, whichcondition_on(posterior, {input_name: y})returns without a fit, as for an amortized posterior or a closed-form posterior; - otherwise, it is the fit of model at
ythatcondition_on.using(method=method, method_options=method_options)(model, y)returns.
posterior's inputs take the observed fields of their names, and a
kernel with one input, such as an amortized posterior's
observation, takes the one observed field. The draws are
sample(posterior_at_y, sample_shape=(num_posterior_draws,)) for every
kind of posterior: the atoms of a weighted empirical law, such as SMC-ABC's
particles, are resampled by weight, a network posterior is evaluated, and an
MCMC posterior's atoms are drawn at random.
The calibration takes its randomness from the enclosing workflow scope,
whose workflow-owned random events it claims in program order: one
sample(model, sample_shape=(num_simulations,)) draws the θ★ and
y of every replication, and then each replication forms its posterior
and draws from it. A call inside workflow_run(seed=...) therefore
reproduces its ranks, and an unscoped call draws afresh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Distribution
|
A joint that samples, over the parameters and the observed fields,
such as |
required |
observed
|
str or sequence of str
|
The fields of a draw that the posterior conditions on; the others are the parameters. A str names one field. |
required |
num_simulations
|
int
|
The number of replications. |
required |
num_posterior_draws
|
int
|
The number of draws of each replication's posterior, which is the largest rank. The ranks assume nearly independent draws, so for an empirical posterior, such as MCMC chains or weighted particles, it should not exceed the effective sample size of the atoms. For an MCMC method, set the chain length in method_options to make it so. |
required |
posterior
|
ConditionalDistribution
|
A posterior kernel from the observed fields to the parameters, such as
the amortized posterior that |
None
|
method
|
str
|
The inference method of each fit, by name; |
None
|
method_options
|
Mapping
|
The options of each fit's method, such as |
None
|
Returns:
| Type | Description |
|---|---|
SBCResult
|
The ranks, of shape |
Raises:
| Type | Description |
|---|---|
TypeError
|
If model does not sample; if posterior is not a
|
ValueError
|
If a count is not positive; if an observed name is not a field of a draw, or no parameter is left; if method or method_options is given with posterior; if posterior's inputs do not take the observed fields; or if the posterior's draw does not hold the parameters: a record draw whose fields are the posterior's outputs names other fields, or a whole-term draw meets several parameters. |
ResolutionError
|
If no route of |
ReplayCompatibilityError
|
If a |
Notes
The draws of θ★ and y are one event, which the call claims first,
so they do not depend on the posterior or the method. Two calls with the
same model and num_simulations, at the same position of scopes with the
same seed, therefore rank their posteriors' draws against the same θ★
and y.
Examples:
The exact posterior kernel of a conjugate normal model covers θ★ at
about the nominal rates:
>>> import jax.numpy as jnp
>>> from probpipe import Normal, NumericArraySpec, conditional_distribution, workflow_run
>>> prior = Normal("mu", 0.0, 2.0)
>>> likelihood = conditional_distribution(
... lambda mu: Normal("y", mu * jnp.ones(5), 1.0),
... label="y_given_mu",
... given_spec=prior.event_spec.outputs,
... )
>>> precision = 1 / 4 + 5
>>> exact = conditional_distribution(
... lambda y: Normal("mu", jnp.sum(y) / precision, precision**-0.5),
... label="posterior",
... given_spec={"y": NumericArraySpec((5,))},
... )
>>> with workflow_run(seed=0):
... result = simulation_based_calibration(
... (likelihood & prior),
... observed="y",
... posterior=exact,
... num_simulations=100,
... num_posterior_draws=99,
... )
>>> result.ranks.shape
(100, 1)
>>> result.coverage((0.5, 0.9))
{0.5: array([0.47]), 0.9: array([0.95])}
Source code in probpipe/validation/_calibration.py
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 | |
probpipe.validation.SBCResult(ranks, num_posterior_draws, param_names, ks_statistic, ks_pvalue)
dataclass
¶
Result of simulation_based_calibration.
Attributes:
| Name | Type | Description |
|---|---|---|
ranks |
ndarray
|
Integer ranks of |
num_posterior_draws |
int
|
|
param_names |
tuple[str, ...] or None
|
The name of each column of |
ks_statistic |
ndarray
|
Per-parameter KS distance of the normalized ranks from |
ks_pvalue |
ndarray
|
Per-parameter KS p-value against |
rank_histogram(num_bins=20)
¶
Rank histogram per parameter, shape (num_params, num_bins).
Bins the normalized ranks into num_bins equal-width bins over
[0, 1]; a calibrated method gives approximately flat histograms.
Source code in probpipe/validation/_calibration.py
coverage(levels=(0.5, 0.8, 0.9, 0.95))
¶
The share of replications whose θ★ lies in the central interval of each level.
θ★ lies in the central level interval of its posterior when its
normalized rank u = (r + 0.5) / (L + 1) lies in
[(1 − level) / 2, (1 + level) / 2], so the shares are computed from
the ranks alone. Under a calibrated posterior the expected share is the
level, within 1 / (L + 1). The shares match the mean of
interval_coverage over the replications' posterior draws, except
at a rank next to an end of the interval, where
interval_coverage interpolates between two draws.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
levels
|
sequence of float
|
The credible levels, each in |
(0.5, 0.8, 0.9, 0.95)
|
Returns:
| Type | Description |
|---|---|
dict of float to np.ndarray
|
For each level, the share of replications that cover |
Raises:
| Type | Description |
|---|---|
TypeError
|
If levels is not a sequence of numbers. |
ValueError
|
If a level is not in |
Source code in probpipe/validation/_calibration.py
probpipe.validation.interval_coverage(draws_or_dist, truth, *, levels=(0.5, 0.8, 0.9, 0.95))
¶
Central-credible-interval coverage of truth, per parameter.
For each level, checks whether each entry of truth lies in the
central level interval [q_{(1−level)/2}, q_{(1+level)/2}] of the
per-parameter posterior. Returns {level: covered} with covered a
boolean array over parameters. Averaging the indicators over many
(posterior, truth) pairs gives the frequentist coverage, which matches the
nominal level for a calibrated method.
draws_or_dist is an (n, d) (or 1-D (n,)) array of draws or an
empirical law, read as the flat coordinates of its atoms (treated as
equally weighted, as MCMC draws are); truth is the matching (d,).