Skip to content

Simulation-based inference: posteriors without a likelihood

When you can simulate a model but not write its likelihood, learn the posterior from simulations. Compare ABC with neural posterior estimation, see why sequential rounds need a correction, and check calibration before trusting any of it.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Write the NPE training objective and say what the network learns
  • Explain why sequential NPE must correct for its changing proposal
  • Tell amortized from local estimators, and what each one's calibration covers
  • Check an SBI posterior with simulated coverage and predictive checks

Read first

01

A simulator, no likelihood

Read

Many scientific and business models are simulators: given parameters θ\theta, they produce data xx, through queues, agents, censoring or physics. You can run them, but p(x∣θ)p(x\mid\theta) has no formula, so none of the samplers so far apply.

Simulation-based inference learns the posterior from pairs (θ,x)(\theta,x) drawn by running the simulator on parameters drawn from the prior. The oldest version, ABC rejection, keeps the parameters whose simulated summary statisticsObserved statistics (calibration targets)What was actually seen — a mean, SD, percentile or share above a threshold — that the calibrated model must reproduce. land near the observed ones. It is simple and wasteful: most simulations are thrown away, and the tolerance blurs the answer.

02

Neural posterior estimation

Read

Neural posterior estimationNeural posterior estimation (NPE)A neural network learns the posterior from simulated pairs of parameters and statistics, then reads it off at the observed data. (NPE) uses every simulation. A network qϕ(θ∣x)q_\phi(\theta\mid x), such as a mixture density network or a conditional flow, is trained to predict the parameters from the data:

LNPE(ϕ)=− Eθ∼p(θ), x∼p(x∣θ)[log⁡qϕ(θ∣x)].\mathcal L_{NPE}(\phi)=-\,E_{\theta\sim p(\theta),\,x\sim p(x\mid\theta)}\big[\log q_\phi(\theta\mid x)\big].

Minimizing it makes qϕ(θ∣x)q_\phi(\theta\mid x) approach the true posterior for every xx the simulations cover. Then you evaluate it at the observed data. Once trained, the same network gives a posterior for any new observation in seconds: it is amortized.

Reference · INF020 · Partly runs in CodeSplashNeural posterior estimation and sequential NPE (SNPE)Trains a conditional density estimator to approximate parameter posteriors from simulated observations when the simulator likelihood is intractable.
03

Sequential rounds need a correction

Read

Prior simulations land mostly far from the observed data. Sequential NPESequential neural posterior estimationNPE in rounds that simulate near the observed data; it must correct for the changed proposal or it learns the wrong posterior. (SNPE) spends later rounds near it, drawing θ\theta from a proposal r(θ)r(\theta), usually the current posterior estimate. But then the training pairs no longer come from the prior, and plain training learns the wrong target. One correction reweights each pair by p(θ)/r(θ)p(\theta)/r(\theta):

LSNPE-B=− Eθ∼r, x∼p(x∣θ)[p(θ)r(θ)log⁡qϕ(θ∣x)].\mathcal L_{SNPE\text{-}B}=-\,E_{\theta\sim r,\,x\sim p(x\mid\theta)}\Big[\tfrac{p(\theta)}{r(\theta)}\log q_\phi(\theta\mid x)\Big].

In the reference's one-step example the weighted loss is 0.527. Those weights can have huge variance, which is why later variants (SNPE-C) correct differently; keep each round's proposal on record. A sequential estimator is tuned to one observation, not amortized.

04

Three algorithms in CodeSplash

Read

Calibrate a scenario model to observed statistics offers rejection ABC, SMC-ABC and NPE (a mixture density network), on a censored-sales scenario here.

Scenario calibrationRecorded · Python and R agreeRecorded 2026-11-25 · 47 values compared
R

Calibrated 2 input(s) to 2 observed statistic(s) by neural posterior estimation (600 simulations of 30 scenario(s) each): base_demand 1110 (90% 954.6 to 1406); volatility 242.2 (90% 118.1 to 379.1).

base_demand (posterior mean)
1109.91
volatility (posterior mean)
242.23

Assumptions

  • Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
  • Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.70).
  • Calibrated algorithm — On 30 simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = 0.15, volatility).

Calibrated inputs

InputPrior meanPrior SDPosterior meanPosterior SD5%Median95%ShrinkageCalibration p
base_demand1012.14282.931109.91137.37954.641072.231406.1076.4%0.6025
volatility220.6598.269242.2383.568118.11235.25379.1027.7%0.1481

Observed statistics and the posterior predictive check

StatisticObservedPredicted mean5%95%Predictive pDistance scale
mean of sales930939.70860.95994.600.7000—
SD of sales110103.3425.353196.540.8667—

Posterior draws (500, equally weighted)

Drawbase_demandvolatility
11050.11123.47
21043.50138.80
31279.16357.57
41009.43151.09
51254.07357.72
61011.35238.06
71052.26131.95
81180.40355.57
91084.96333.08
101142.93130.40
111027.84176.95
121044.02334.17
131326.19396.47
141047.59282.71
15974.38184.37
161078.05252.42
171036.47192.65
181037.3692.367
191046.3892.087
201071.62227.32
211035.73198.07
221135.51145.82
231010.69184.65
241078.16350.52
251123.77346.87
261047.06302.54
271222.11352.06
281061.32155.17
291398.76347.91
301092.70196.06
311024.06177.36
32986.20205.84
33996.57255.64
341153.01308.00
35979.33147.99
361106.87293.43
371047.77345.19
381414.69352.29
391027.37118.14
401075.58297.10

First 40 of 500 rows.

  • The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
  • A mixture density network (2 components, two tanh layers of 12) learned the posterior from prior simulations; training stopped at epoch 40 (best held-out epoch 40).
  • The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
The exact R script · R R version 4.5.1 (2025-06-13)
# Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.calibrate 1.1.0 · spec 82175d8e725ac640
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Model, inputs to calibrate and observed statistics
ALGORITHM <- "npe"
REPLICATES <- as.integer(30)
SEED <- as.integer(7)
COVERAGE <- TRUE && ALGORITHM %in% c("rejection", "npe")
COVERAGE_N <- as.integer(30)
PRED_DRAWS <- as.integer(60)
warnings <- list()
ctx <- tryCatch(cs_calib_setup("{\"inputs\":[{\"name\":\"base_demand\",\"dist\":\"uniform\",\"params\":{\"min\":500,\"max\":1500}},{\"name\":\"volatility\",\"dist\":\"uniform\",\"params\":{\"min\":50,\"max\":400}},{\"name\":\"shock\",\"dist\":\"normal\",\"params\":{\"mean\":0,\"sd\":1}}],\"decisions\":[{\"name\":\"order\",\"value\":1000,\"min\":0,\"max\":3000}],\"formulas\":[{\"name\":\"demand\",\"expr\":\"max(base_demand + volatility * shock, 0)\"},{\"name\":\"sales\",\"expr\":\"min(demand, order)\"}],\"kpis\":[{\"name\":\"sales\",\"label\":\"Sales\"}],\"correlations\":[]}", "base_demand, volatility", "[{\"name\":\"sales\",\"stat\":\"mean\",\"value\":930},{\"name\":\"sales\",\"stat\":\"sd\",\"value\":110}]", REPLICATES),
                error = function(e) cs_error("CS_E_INVALID_OPTION", option = "Calibration setup", allowed = "a valid model, inputs to calibrate and observed statistics",
                                             value = conditionMessage(e)))
params <- ctx$params
targets <- ctx$targets
K <- length(params)
J <- length(targets)

# The neural posterior's network trains on the shared trainer: training options, live progress and checkpoints.
# Training options, live progress and checkpoints (twin: codesplash.deep.trainer.configure).
cs_deep_trainer_configure(list(
  optimizer = "default",
  lr_schedule = "none",
  warmup_epochs = 0,
  grad_clip = 0,
  ema_decay = 0,
  swa_start = 0,
  history_every_step = FALSE,
  profile = "parity",
  checkpoint_every = NULL
), out_dir = "target/academy-parity/run-8142/simulate.calibrate/censored-sales-npe/out-r")

# %% Posterior
# Every algorithm works on normal scores z = qnorm(F(theta)), where any prior is a standard normal, and maps back
# through each input's quantile function (Monte Carlo's twin), so bounds and clipping hold.
values <- list(algorithm = ALGORITHM, n_params = K, n_targets = J, replicates = REPLICATES)
for (key in c("n_accepted", "epsilon", "adjusted", "generations", "stop_reason", "acceptance_rate", "epochs_run", "valid_loss", "coverage_p_min")) values[key] <- list(NULL)
ranks <- NULL
gens <- list()
history <- list()
res <- tryCatch({
  if (ALGORITHM == "rejection") {
    S <- as.integer(10000)
    r <- cs_calib_rejection(ctx, S, 0.01, FALSE, SEED)
    r$S <- S
    r
  } else if (ALGORITHM == "smc") {
    cs_calib_smc(ctx, as.integer(500), as.integer(6), 0.5, as.integer(100000), 0.02, SEED)
  } else {
    cs_calib_npe(ctx, as.integer(600), as.integer(2), as.integer(12), as.integer(40),
                 0.01, as.integer(800), SEED, if (COVERAGE) COVERAGE_N else 0)
  }
}, error = function(e) cs_error("CS_E_UNDEFINED", what = "The calibration", reason = conditionMessage(e)))
if (ALGORITHM == "rejection") {
  S <- res$S
  k_acc <- length(res$accepted)
  values$n_simulations <- S
  values$n_accepted <- k_acc
  values$epsilon <- res$epsilon
  values$adjusted <- as.integer(res$adjusted)
  values$acceptance_rate <- k_acc / S
  if (!is.null(res$note)) warnings[[length(warnings) + 1]] <- res$note
  if (res$n_finite < S) warnings[[length(warnings) + 1]] <- sprintf("%s of %s simulations gave no number for some statistic (division by zero or an invalid function argument) and were never kept.",
                                                                    formatC(S - res$n_finite, big.mark = ",", format = "d"), formatC(S, big.mark = ",", format = "d"))
  if (COVERAGE) ranks <- cs_calib_coverage_rejection(ctx, res, COVERAGE_N)
} else if (ALGORITHM == "smc") {
  gens <- res$generations
  values$n_simulations <- res$n_sims
  values$n_accepted <- as.integer(500)
  values$epsilon <- res$epsilon
  values$generations <- length(gens) - 1L
  values$stop_reason <- res$stop
  values$acceptance_rate <- gens[[length(gens)]]$rate
  if (res$stop == "budget") warnings[[length(warnings) + 1]] <- sprintf("The simulation budget ran out during generation %d; the posterior is generation %d's.", length(gens), length(gens) - 1L)
} else {
  history <- res$history
  values$n_simulations <- res$n_sims
  values$epochs_run <- res$epochs_run
  values$valid_loss <- res$valid_loss
  ranks <- res$ranks
}
post <- res$post_theta
w <- res$weights / sum(res$weights)
prior <- res$prior_theta
values$ess <- 1 / sum(w * w)
prior_w <- rep(1 / nrow(prior), nrow(prior))

post_rows <- list()
cov_p <- list()
if (!is.null(ranks) && nrow(ranks)) {
  for (k in seq_along(params)) cov_p[[params[k]]] <- cs_calib_rank_test(ranks[, k], 100)$p
  values$coverage_p_min <- min(unlist(cov_p))
}
for (k in seq_along(params)) {
  nm <- params[k]
  ps <- cs_calib_summarize(post[, k], w)
  pr <- cs_calib_summarize(prior[, k], prior_w)
  shrink <- if (pr$sd > 0) 1 - (ps$sd / pr$sd)^2 else NULL
  values[sprintf("post_mean[%s]", nm)] <- list(ps$mean)
  values[sprintf("post_sd[%s]", nm)] <- list(ps$sd)
  values[sprintf("post_lo[%s]", nm)] <- list(ps$lo)
  values[sprintf("post_median[%s]", nm)] <- list(ps$median)
  values[sprintf("post_hi[%s]", nm)] <- list(ps$hi)
  values[sprintf("prior_mean[%s]", nm)] <- list(pr$mean)
  values[sprintf("prior_sd[%s]", nm)] <- list(pr$sd)
  values[sprintf("shrinkage[%s]", nm)] <- list(shrink)
  if (!is.null(cov_p[[nm]])) values[sprintf("coverage_p[%s]", nm)] <- list(cov_p[[nm]])
  post_rows[[k]] <- list(input = nm, prior_mean = pr$mean, prior_sd = pr$sd, mean = ps$mean, sd = ps$sd, lo = ps$lo,
                         median = ps$median, hi = ps$hi, shrinkage = shrink, coverage_p = cov_p[[nm]])
}
values$primary <- params[1]
values$primary_mean <- values[[sprintf("post_mean[%s]", params[1])]]
values$primary_lo <- values[[sprintf("post_lo[%s]", params[1])]]
values$primary_hi <- values[[sprintf("post_hi[%s]", params[1])]]

# %% Posterior predictive check: fresh simulations at posterior draws
pred <- cs_calib_predictive(ctx, post, w, PRED_DRAWS, SEED + 17)
target_rows <- list()
ppc_ps <- list()
for (j in seq_along(targets)) {
  t <- targets[[j]]
  x <- pred[is.finite(pred[, j]), j]
  lab <- t$key
  obs <- t$value
  values[sprintf("observed[%s]", lab)] <- list(obs)
  if (ALGORITHM != "npe") values[sprintf("scale[%s]", lab)] <- list(res$scale[j])
  if (length(x)) {
    m_ <- sum(x) / length(x)
    lo_ <- cs_calib_quantile7(x, 0.05)
    hi_ <- cs_calib_quantile7(x, 0.95)
    p_ <- min(1, 2 * min(sum(x >= obs) / length(x), sum(x <= obs) / length(x)))
    ppc_ps[[t$label]] <- p_
  } else {
    m_ <- NULL; lo_ <- NULL; hi_ <- NULL; p_ <- NULL
  }
  values[sprintf("ppc_mean[%s]", lab)] <- list(m_)
  values[sprintf("ppc_lo[%s]", lab)] <- list(lo_)
  values[sprintf("ppc_hi[%s]", lab)] <- list(hi_)
  values[sprintf("ppc_p[%s]", lab)] <- list(p_)
  target_rows[[j]] <- list(statistic = t$label, observed = obs, ppc_mean = m_, ppc_lo = lo_, ppc_hi = hi_, ppc_p = p_,
                           scale = if (ALGORITHM != "npe") res$scale[j] else NULL)
}

# %% Assumptions
assumptions <- list(list(key = "priors", label = "Priors", status = "info",
                         detail = "Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight."))
bad <- names(ppc_ps)[unlist(ppc_ps) < 0.05]
if (length(ppc_ps) < J) {
  assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "warn",
                           detail = "Some statistics gave no number in the posterior predictive simulations.")
} else if (length(bad)) {
  assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "warn",
                           detail = paste0("Posterior simulations rarely bring back ", paste(bad, collapse = ", "),
                                           " (p < 0.05): the model may be unable to produce what was observed, or the targets conflict."))
} else {
  assumptions[[2]] <- list(key = "reproduces_targets", label = "Reproduces the observed statistics", status = "pass",
                           detail = sprintf("Simulations from the posterior bring back every observed statistic (smallest p = %.2f).", min(unlist(ppc_ps))))
}
if (length(cov_p)) {
  cp <- unlist(cov_p)
  worst <- names(cp)[which.min(cp)]
  if (cp[[worst]] >= 0.01) {
    assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "pass",
                             detail = sprintf("On %d simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = %.2f, %s).", nrow(ranks), cp[[worst]], worst))
  } else {
    assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "warn",
                             detail = paste0(sprintf("On %d simulated data sets the true values of %s fall unevenly across the posteriors (rank-test p = %.3f): ", nrow(ranks), worst, cp[[worst]]),
                                             "intervals may be too narrow or shifted; keep fewer simulations, add some, or train longer."))
  }
} else {
  assumptions[[3]] <- list(key = "calibrated", label = "Calibrated algorithm", status = "info",
                           detail = paste0("Not checked: ", if (ALGORITHM == "smc") "SMC-ABC has no cheap calibration check." else "the calibration check is off."))
}

# %% Charts
charts <- list()
for (k in seq_len(min(K, 6))) {
  nm <- params[k]
  h <- cs_pf_bandwidth(post[, k], w)
  q <- cs_pf_weighted_quantiles(prior[, k], prior_w, c(0.01, 0.99))
  lo_g <- min(q[1], min(post[, k]) - 3 * h)
  hi_g <- max(q[2], max(post[, k]) + 3 * h)
  grid <- seq(lo_g, hi_g, length.out = 150)
  charts[[length(charts) + 1]] <- cs_chart(paste0("posterior_", nm), "prior-posterior", sprintf("%s: prior and posterior", nm), list(
    x = cs_col(nm, c(grid, grid)),
    density = cs_col("density", c(cs_pf_kde(prior[, k], grid, prior_w), cs_pf_kde(post[, k], grid, w))),
    curve = cs_col("curve", c(rep("prior", length(grid)), rep("posterior", length(grid))), kind = "categorical")))
}
for (j in seq_along(targets)) {
  t <- targets[[j]]
  hst <- cs_sim_histogram(pred[, j], 30)
  charts[[length(charts) + 1]] <- cs_chart(sprintf("ppc_%d", j), "mc-distribution", sprintf("Posterior predictive: %s (observed %s)", t$label, sprintf("%.4g", t$value)), list(
    bin_low = cs_col(t$label, hst$bin_low), bin_high = cs_col("Bin end", hst$bin_high), count = cs_col("Simulations", hst$count)),
    controls = list(percentiles = c(5, 50, 95), target = t$value))
}
if (length(gens)) {
  charts[[length(charts) + 1]] <- cs_chart("tolerance", "series-line", "SMC-ABC tolerance by generation", list(
    x = cs_col("generation", as.numeric(vapply(gens, function(g) g$generation, numeric(1)))),
    y = cs_col("tolerance", vapply(gens, function(g) g$epsilon, numeric(1))),
    group = cs_col("series", rep("tolerance", length(gens)), kind = "categorical")))
}
if (!is.null(ranks) && nrow(ranks)) {
  charts[[length(charts) + 1]] <- cs_chart("coverage", "pit-histogram", "Calibration check: where the true values fell in their posteriors (all inputs)", list(
    share = cs_col("share", cs_calib_rank_test(ranks, 100)$shares)))
}
if (length(history)) {
  ep <- as.numeric(vapply(history, function(h_) h_$epoch, numeric(1)))
  charts[[length(charts) + 1]] <- cs_chart("training", "series-line", "Network training: loss on training and held-out simulations", list(
    x = cs_col("epoch", c(ep, ep)),
    y = cs_col("negative log-likelihood", c(vapply(history, function(h_) h_$loss, numeric(1)), vapply(history, function(h_) h_$valid_loss, numeric(1)))),
    group = cs_col("set", c(rep("training", length(ep)), rep("held out", length(ep))), kind = "categorical")))
}

# %% Tables
tables <- list(
  list(key = "posterior", title = "Calibrated inputs",
       columns = list(list(key = "input", label = "Input", type = "string"), list(key = "prior_mean", label = "Prior mean", type = "number"),
                      list(key = "prior_sd", label = "Prior SD", type = "number"), list(key = "mean", label = "Posterior mean", type = "number"),
                      list(key = "sd", label = "Posterior SD", type = "number"), list(key = "lo", label = "5%", type = "number"),
                      list(key = "median", label = "Median", type = "number"), list(key = "hi", label = "95%", type = "number"),
                      list(key = "shrinkage", label = "Shrinkage", type = "percent"), list(key = "coverage_p", label = "Calibration p", type = "number")),
       rows = post_rows),
  list(key = "targets", title = "Observed statistics and the posterior predictive check",
       columns = list(list(key = "statistic", label = "Statistic", type = "string"), list(key = "observed", label = "Observed", type = "number"),
                      list(key = "ppc_mean", label = "Predicted mean", type = "number"), list(key = "ppc_lo", label = "5%", type = "number"),
                      list(key = "ppc_hi", label = "95%", type = "number"), list(key = "ppc_p", label = "Predictive p", type = "number"),
                      list(key = "scale", label = "Distance scale", type = "number")),
       rows = target_rows))
if (length(gens)) {
  tables[[length(tables) + 1]] <- list(key = "generations", title = "SMC-ABC generations",
    columns = list(list(key = "generation", label = "Generation", type = "integer"), list(key = "epsilon", label = "Tolerance", type = "number"),
                   list(key = "sims", label = "Simulations", type = "integer"), list(key = "rate", label = "Acceptance", type = "percent"),
                   list(key = "ess", label = "Effective particles", type = "number")),
    rows = lapply(gens, function(g) list(generation = g$generation, epsilon = g$epsilon, sims = g$sims, rate = g$rate, ess = g$ess)))
}
n_show <- min(500L, nrow(post))
idx <- cs_calib_resample(nrow(post), w, n_show, cs_runif(cs_rng(SEED + 19), 1))
sample_cols <- c(list(list(key = "draw", label = "Draw", type = "integer")), lapply(seq_along(params), function(k) list(key = sprintf("p%d", k), label = params[k], type = "number")))
tables[[length(tables) + 1]] <- list(key = "sample", title = sprintf("Posterior draws (%d, equally weighted)", n_show), columns = sample_cols,
  rows = lapply(seq_len(n_show), function(i) c(list(draw = i), stats::setNames(as.list(post[idx[i], ]), sprintf("p%d", seq_len(K))))))

# %% Posterior draws
artifacts <- list()
if (TRUE) {
  out <- cs_ml_out_dir("target/academy-parity/run-8142/simulate.calibrate/censored-sales-npe/out-r")
  path <- file.path(out, "posterior.parquet")
  dfp <- as.data.frame(c(list(draw = seq_len(nrow(post))), stats::setNames(lapply(seq_len(K), function(k) post[, k]), params), list(weight = w)), check.names = FALSE)
  nanoparquet::write_parquet(dfp, path)
  artifacts <- list(list(key = "posterior", path = path, format = "parquet", title = "Posterior draws"))
}

# %% Result
g4 <- function(v) sprintf("%.4g", v)
ALG <- c(rejection = "rejection ABC", smc = "SMC-ABC", npe = "neural posterior estimation")[[ALGORITHM]]
values$algorithm <- ALG
desc <- paste(vapply(params, function(nm) sprintf("%s %s (90%% %s to %s)", nm, g4(values[[sprintf("post_mean[%s]", nm)]]),
                                                  g4(values[[sprintf("post_lo[%s]", nm)]]), g4(values[[sprintf("post_hi[%s]", nm)]])), ""), collapse = "; ")
summary <- sprintf("Calibrated %d input(s) to %d observed statistic(s) by %s (%s simulations of %d scenario(s) each): %s.",
                   K, J, ALG, formatC(values$n_simulations, big.mark = ",", format = "d"), REPLICATES, desc)
notes <- c(paste0("The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. ",
                  "Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation)."))
if (ALGORITHM == "rejection") {
  notes <- c(notes, paste0(sprintf("Rejection ABC kept the %s simulations closest to the observed statistics (tolerance %s)", formatC(values$n_accepted, big.mark = ",", format = "d"), g4(res$epsilon)),
                           if (res$adjusted) ", then shifted them by a weighted local-linear regression on the statistics (Beaumont et al. 2002)." else "."))
} else if (ALGORITHM == "smc") {
  notes <- c(notes, paste0(sprintf("SMC-ABC ran %d generation(s) after the prior one (stop: %s); each tolerance is the 0.5 quantile of the previous distances, ", length(gens) - 1L, res$stop),
                           "particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009)."))
} else {
  notes <- c(notes, sprintf("A mixture density network (2 components, two tanh layers of 12) learned the posterior from prior simulations; training stopped at epoch %d (best held-out epoch %d).",
                            res$epochs_run, res$best_epoch))
}
notes <- c(notes, "The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.")
statistics <- lapply(params, function(nm) list(key = sprintf("post_mean[%s]", nm), label = sprintf("%s (posterior mean)", nm), value = values[[sprintf("post_mean[%s]", nm)]]))
cs_publish(list(
  method = "simulate.calibrate",
  methodVersion = "1.1.0",
  title = "Scenario calibration",
  engine = if (ALGORITHM != "npe") cs_engine_info("jsonlite", "nanoparquet") else cs_engine_info("jsonlite", "nanoparquet", "torch"),
  n = values$n_simulations,
  summary = summary,
  statistics = statistics,
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = charts,
  values = values,
  artifacts = artifacts
))
Python

Calibrated 2 input(s) to 2 observed statistic(s) by neural posterior estimation (600 simulations of 30 scenario(s) each): base_demand 1110 (90% 954.6 to 1406); volatility 242.2 (90% 118.1 to 379.1).

base_demand (posterior mean)
1109.91
volatility (posterior mean)
242.23

Assumptions

  • Priors — Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight.
  • Reproduces the observed statistics — Simulations from the posterior bring back every observed statistic (smallest p = 0.70).
  • Calibrated algorithm — On 30 simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = 0.15, volatility).

Calibrated inputs

InputPrior meanPrior SDPosterior meanPosterior SD5%Median95%ShrinkageCalibration p
base_demand1012.14282.931109.91137.37954.641072.231406.1076.4%0.6025
volatility220.6598.269242.2383.568118.11235.25379.1027.7%0.1481

Observed statistics and the posterior predictive check

StatisticObservedPredicted mean5%95%Predictive pDistance scale
mean of sales930939.70860.95994.600.7000—
SD of sales110103.3425.353196.540.8667—

Posterior draws (500, equally weighted)

Drawbase_demandvolatility
11050.11123.47
21043.50138.80
31279.16357.57
41009.43151.09
51254.07357.72
61011.35238.06
71052.26131.95
81180.40355.57
91084.96333.08
101142.93130.40
111027.84176.95
121044.02334.17
131326.19396.47
141047.59282.71
15974.38184.37
161078.05252.42
171036.47192.65
181037.3692.367
191046.3892.087
201071.62227.32
211035.73198.07
221135.51145.82
231010.69184.65
241078.16350.52
251123.77346.87
261047.06302.54
271222.11352.06
281061.32155.17
291398.76347.91
301092.70196.06
311024.06177.36
32986.20205.84
33996.57255.64
341153.01308.00
35979.33147.99
361106.87293.43
371047.77345.19
381414.69352.29
391027.37118.14
401075.58297.10

First 40 of 500 rows.

  • The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation).
  • A mixture density network (2 components, two tanh layers of 12) learned the posterior from prior simulations; training stopped at epoch 40 (best held-out epoch 40).
  • The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Calibrate a scenario model to observed statistics (ABC, SMC-ABC, neural posterior)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method simulate.calibrate 1.1.0 · spec 82175d8e725ac640
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math
import os

import numpy as np
import pandas as pd

import codesplash as cs
from codesplash import ml as csml
from codesplash.sim import calibrate as cb  # ABC, SMC-ABC and NPE on the scenario-model twins (twin of codesplashr cs_calib_*)
from codesplash.sim import mc
from codesplash.stats import particle as pf  # weighted quantiles and kernel densities
from codesplash.stats.rng import Rng

# %% Model, inputs to calibrate and observed statistics
ALGORITHM = "npe"
REPLICATES = int(30)
SEED = int(7)
COVERAGE = True and ALGORITHM in ("rejection", "npe")
COVERAGE_N = int(30)
PRED_DRAWS = int(60)
warnings = []
try:
    ctx = cb.setup("{\"inputs\":[{\"name\":\"base_demand\",\"dist\":\"uniform\",\"params\":{\"min\":500,\"max\":1500}},{\"name\":\"volatility\",\"dist\":\"uniform\",\"params\":{\"min\":50,\"max\":400}},{\"name\":\"shock\",\"dist\":\"normal\",\"params\":{\"mean\":0,\"sd\":1}}],\"decisions\":[{\"name\":\"order\",\"value\":1000,\"min\":0,\"max\":3000}],\"formulas\":[{\"name\":\"demand\",\"expr\":\"max(base_demand + volatility * shock, 0)\"},{\"name\":\"sales\",\"expr\":\"min(demand, order)\"}],\"kpis\":[{\"name\":\"sales\",\"label\":\"Sales\"}],\"correlations\":[]}", "base_demand, volatility", "[{\"name\":\"sales\",\"stat\":\"mean\",\"value\":930},{\"name\":\"sales\",\"stat\":\"sd\",\"value\":110}]", REPLICATES)
except ValueError as e:
    cs.cs_error("CS_E_INVALID_OPTION", option="Calibration setup", allowed="a valid model, inputs to calibrate and observed statistics", value=str(e))
params = ctx["params"]
targets = ctx["targets"]
K, J = len(params), len(targets)

# The neural posterior's network trains on the shared trainer: training options, live progress and checkpoints.
from codesplash.deep import trainer as deep_trainer  # training options, live progress, checkpoints (twin: cs_deep_trainer_*)

deep_trainer.configure(
    {
        "optimizer": "default",
        "lr_schedule": "none",
        "warmup_epochs": 0,
        "grad_clip": 0,
        "ema_decay": 0,
        "swa_start": 0,
        "history_every_step": False,
        "profile": "parity",
        "checkpoint_every": None,
    },
    out_dir="target/academy-parity/run-8142/simulate.calibrate/censored-sales-npe/out-python",
)

# %% Posterior
# Every algorithm works on normal scores z = Φ⁻¹(F(θ)), where any prior is a standard normal, and maps back
# through each input's quantile function (Monte Carlo's twin), so bounds and clipping hold.
values = {"algorithm": ALGORITHM, "n_params": K, "n_targets": J, "replicates": REPLICATES}
for key in ("n_accepted", "epsilon", "adjusted", "generations", "stop_reason", "acceptance_rate", "epochs_run", "valid_loss", "coverage_p_min"):
    values[key] = None
ranks = None
gens = []
history = []
try:
    if ALGORITHM == "rejection":
        S = int(10000)
        res = cb.rejection(ctx, S, 0.01, False, SEED)
        k_acc = len(res["accepted"])
        values.update({"n_simulations": S, "n_accepted": k_acc, "epsilon": res["epsilon"], "adjusted": int(res["adjusted"]), "acceptance_rate": k_acc / S})
        if res["note"]:
            warnings.append(res["note"])
        if res["n_finite"] < S:
            warnings.append(f"{S - res['n_finite']:,} of {S:,} simulations gave no number for some statistic (division by zero or an invalid function argument) and were never kept.")
        if COVERAGE:
            ranks = cb.coverage_rejection(ctx, res, COVERAGE_N)
    elif ALGORITHM == "smc":
        res = cb.smc(ctx, int(500), int(6), 0.5, int(100000), 0.02, SEED)
        gens = res["generations"]
        values.update({"n_simulations": res["n_sims"], "n_accepted": int(500), "epsilon": res["epsilon"], "generations": len(gens) - 1,
                       "stop_reason": res["stop"], "acceptance_rate": gens[-1]["rate"]})
        if res["stop"] == "budget":
            warnings.append(f"The simulation budget ran out during generation {len(gens)}; the posterior is generation {len(gens) - 1}'s.")
    else:
        res = cb.npe(ctx, int(600), int(2), int(12), int(40),
                     0.01, int(800), SEED, COVERAGE_N if COVERAGE else 0)
        history = res["history"]
        values.update({"n_simulations": res["n_sims"], "epochs_run": res["epochs_run"], "valid_loss": res["valid_loss"]})
        ranks = res["ranks"]
except ValueError as e:
    cs.cs_error("CS_E_UNDEFINED", what="The calibration", reason=str(e))
post, w, prior = res["post_theta"], res["weights"], res["prior_theta"]
w = w / float(np.sum(w))
values["ess"] = 1.0 / float(np.sum(w * w))
prior_w = np.full(prior.shape[0], 1.0 / prior.shape[0])

post_rows = []
cov_p = {}
if ranks is not None and len(ranks):
    for k, nm in enumerate(params):
        cov_p[nm] = cb.rank_test(ranks[:, k], 100.0)[2]
    values["coverage_p_min"] = float(min(cov_p.values()))
for k, nm in enumerate(params):
    ps = cb.summarize(post[:, k], w)
    pr = cb.summarize(prior[:, k], prior_w)
    shrink = 1.0 - (ps["sd"] / pr["sd"]) ** 2 if pr["sd"] > 0 else None
    values[f"post_mean[{nm}]"], values[f"post_sd[{nm}]"] = ps["mean"], ps["sd"]
    values[f"post_lo[{nm}]"], values[f"post_median[{nm}]"], values[f"post_hi[{nm}]"] = ps["lo"], ps["median"], ps["hi"]
    values[f"prior_mean[{nm}]"], values[f"prior_sd[{nm}]"], values[f"shrinkage[{nm}]"] = pr["mean"], pr["sd"], shrink
    if nm in cov_p:
        values[f"coverage_p[{nm}]"] = cov_p[nm]
    post_rows.append({"input": nm, "prior_mean": pr["mean"], "prior_sd": pr["sd"], "mean": ps["mean"], "sd": ps["sd"], "lo": ps["lo"],
                      "median": ps["median"], "hi": ps["hi"], "shrinkage": shrink, "coverage_p": cov_p.get(nm)})
values.update({"primary": params[0], "primary_mean": values[f"post_mean[{params[0]}]"], "primary_lo": values[f"post_lo[{params[0]}]"],
               "primary_hi": values[f"post_hi[{params[0]}]"]})

# %% Posterior predictive check: fresh simulations at posterior draws
pred = cb.predictive(ctx, post, w, PRED_DRAWS, SEED + 17)
target_rows = []
ppc_ps = []
for j, t in enumerate(targets):
    x = pred[np.isfinite(pred[:, j]), j]
    lab = t["key"]
    obs = t["value"]
    values[f"observed[{lab}]"] = obs
    if ALGORITHM != "npe":
        values[f"scale[{lab}]"] = float(res["scale"][j])
    if len(x):
        m_ = float(np.sum(x)) / len(x)
        lo_, hi_ = cb.quantile7(x, 0.05), cb.quantile7(x, 0.95)
        p_ = min(1.0, 2.0 * min(float(np.sum(x >= obs)) / len(x), float(np.sum(x <= obs)) / len(x)))
    else:
        m_ = lo_ = hi_ = p_ = None
    values[f"ppc_mean[{lab}]"], values[f"ppc_lo[{lab}]"], values[f"ppc_hi[{lab}]"], values[f"ppc_p[{lab}]"] = m_, lo_, hi_, p_
    if p_ is not None:
        ppc_ps.append((t["label"], p_))
    target_rows.append({"statistic": t["label"], "observed": obs, "ppc_mean": m_, "ppc_lo": lo_, "ppc_hi": hi_, "ppc_p": p_,
                        "scale": float(res["scale"][j]) if ALGORITHM != "npe" else None})

# %% Assumptions
assumptions = [{"key": "priors", "label": "Priors", "status": "info",
                "detail": "Assumed, not checked from the data: each calibrated input's distribution in the model is its prior, so the posterior can't move where the prior has no weight."}]
bad = [lab for lab, p_ in ppc_ps if p_ < 0.05]
if len(ppc_ps) < J:
    assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "warn",
                        "detail": "Some statistics gave no number in the posterior predictive simulations."})
elif bad:
    assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "warn",
                        "detail": "Posterior simulations rarely bring back " + ", ".join(bad) + " (p < 0.05): the model may be unable to produce what was observed, or the targets conflict."})
else:
    assumptions.append({"key": "reproduces_targets", "label": "Reproduces the observed statistics", "status": "pass",
                        "detail": f"Simulations from the posterior bring back every observed statistic (smallest p = {min(p_ for _, p_ in ppc_ps):.2f})."})
if cov_p:
    worst = min(cov_p, key=lambda nm: cov_p[nm])
    if cov_p[worst] >= 0.01:
        assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "pass",
                            "detail": f"On {len(ranks)} simulated data sets the true values spread evenly across the posteriors (smallest rank-test p = {cov_p[worst]:.2f}, {worst})."})
    else:
        assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "warn",
                            "detail": f"On {len(ranks)} simulated data sets the true values of {worst} fall unevenly across the posteriors (rank-test p = {cov_p[worst]:.3f}): "
                                      "intervals may be too narrow or shifted; keep fewer simulations, add some, or train longer."})
else:
    assumptions.append({"key": "calibrated", "label": "Calibrated algorithm", "status": "info",
                        "detail": "Not checked: " + ("SMC-ABC has no cheap calibration check." if ALGORITHM == "smc" else "the calibration check is off.")})

# %% Charts
charts = []
for k, nm in enumerate(params[:6]):
    pw = prior_w
    h = pf.bandwidth(post[:, k], w)
    q01, q99 = pf.weighted_quantiles(prior[:, k], pw, (0.01, 0.99))
    lo_g = min(q01, float(np.min(post[:, k])) - 3.0 * h)
    hi_g = max(q99, float(np.max(post[:, k])) + 3.0 * h)
    grid = np.linspace(lo_g, hi_g, 150)
    charts.append(cs.chart(f"posterior_{nm}", "prior-posterior", f"{nm}: prior and posterior", {
        "x": cs.col(nm, np.concatenate([grid, grid])),
        "density": cs.col("density", np.concatenate([pf.kde(prior[:, k], grid, pw), pf.kde(post[:, k], grid, w)])),
        "curve": cs.col("curve", ["prior"] * len(grid) + ["posterior"] * len(grid), kind="categorical")}))
for j, t in enumerate(targets):
    hst = mc.histogram(pred[:, j], 30)
    charts.append(cs.chart(f"ppc_{j + 1}", "mc-distribution", f"Posterior predictive: {t['label']} (observed {t['value']:.4g})", {
        "bin_low": cs.col(t["label"], hst["bin_low"]), "bin_high": cs.col("Bin end", hst["bin_high"]), "count": cs.col("Simulations", hst["count"])},
        controls={"percentiles": [5, 50, 95], "target": float(t["value"])}))
if gens:
    charts.append(cs.chart("tolerance", "series-line", "SMC-ABC tolerance by generation", {
        "x": cs.col("generation", [float(g["generation"]) for g in gens]), "y": cs.col("tolerance", [g["epsilon"] for g in gens]),
        "group": cs.col("series", ["tolerance"] * len(gens), kind="categorical")}))
if ranks is not None and len(ranks):
    shares = cb.rank_test(ranks, 100.0)[0]
    charts.append(cs.chart("coverage", "pit-histogram", "Calibration check: where the true values fell in their posteriors (all inputs)", {
        "share": cs.col("share", shares)}))
if history:
    ep = [float(h_["epoch"]) for h_ in history]
    charts.append(cs.chart("training", "series-line", "Network training: loss on training and held-out simulations", {
        "x": cs.col("epoch", ep + ep), "y": cs.col("negative log-likelihood", [h_["loss"] for h_ in history] + [h_["valid_loss"] for h_ in history]),
        "group": cs.col("set", ["training"] * len(ep) + ["held out"] * len(ep), kind="categorical")}))

# %% Tables
tables = [{"key": "posterior", "title": "Calibrated inputs",
           "columns": [{"key": "input", "label": "Input", "type": "string"}, {"key": "prior_mean", "label": "Prior mean", "type": "number"},
                       {"key": "prior_sd", "label": "Prior SD", "type": "number"}, {"key": "mean", "label": "Posterior mean", "type": "number"},
                       {"key": "sd", "label": "Posterior SD", "type": "number"}, {"key": "lo", "label": "5%", "type": "number"},
                       {"key": "median", "label": "Median", "type": "number"}, {"key": "hi", "label": "95%", "type": "number"},
                       {"key": "shrinkage", "label": "Shrinkage", "type": "percent"}, {"key": "coverage_p", "label": "Calibration p", "type": "number"}],
           "rows": post_rows},
          {"key": "targets", "title": "Observed statistics and the posterior predictive check",
           "columns": [{"key": "statistic", "label": "Statistic", "type": "string"}, {"key": "observed", "label": "Observed", "type": "number"},
                       {"key": "ppc_mean", "label": "Predicted mean", "type": "number"}, {"key": "ppc_lo", "label": "5%", "type": "number"},
                       {"key": "ppc_hi", "label": "95%", "type": "number"}, {"key": "ppc_p", "label": "Predictive p", "type": "number"},
                       {"key": "scale", "label": "Distance scale", "type": "number"}],
           "rows": target_rows}]
if gens:
    tables.append({"key": "generations", "title": "SMC-ABC generations",
                   "columns": [{"key": "generation", "label": "Generation", "type": "integer"}, {"key": "epsilon", "label": "Tolerance", "type": "number"},
                               {"key": "sims", "label": "Simulations", "type": "integer"}, {"key": "rate", "label": "Acceptance", "type": "percent"},
                               {"key": "ess", "label": "Effective particles", "type": "number"}],
                   "rows": [{"generation": g["generation"], "epsilon": g["epsilon"], "sims": g["sims"], "rate": g["rate"], "ess": g["ess"]} for g in gens]})
n_show = min(500, post.shape[0])
idx = cb.resample(post.shape[0], w, n_show, float(Rng(SEED + 19).uniform(1)[0]))
tables.append({"key": "sample", "title": f"Posterior draws ({n_show}, equally weighted)",
               "columns": [{"key": "draw", "label": "Draw", "type": "integer"}] + [{"key": f"p{k + 1}", "label": nm, "type": "number"} for k, nm in enumerate(params)],
               "rows": [{"draw": i + 1, **{f"p{k + 1}": float(post[idx[i], k]) for k in range(K)}} for i in range(n_show)]})

# %% Posterior draws
artifacts = []
if True:
    out = csml.out_dir("target/academy-parity/run-8142/simulate.calibrate/censored-sales-npe/out-python")
    path = os.path.join(out, "posterior.parquet")
    pd.DataFrame({"draw": np.arange(1, post.shape[0] + 1), **{nm: post[:, k] for k, nm in enumerate(params)}, "weight": w}).to_parquet(path, index=False)
    artifacts.append({"key": "posterior", "path": path, "format": "parquet", "title": "Posterior draws"})

# %% Result
ALG = {"rejection": "rejection ABC", "smc": "SMC-ABC", "npe": "neural posterior estimation"}[ALGORITHM]
values["algorithm"] = ALG
desc = "; ".join(f"{nm} {values[f'post_mean[{nm}]']:.4g} (90% {values[f'post_lo[{nm}]']:.4g} to {values[f'post_hi[{nm}]']:.4g})" for nm in params)
summary = f"Calibrated {K} input(s) to {J} observed statistic(s) by {ALG} ({values['n_simulations']:,} simulations of {REPLICATES} scenario(s) each): {desc}."
notes = ["The calibrated inputs' distributions in the model are the priors; other uncertain inputs keep varying as in Monte Carlo. "
         "Statistics are compared on a scale set by their spread across simulations (1.4826 × the median absolute deviation)."]
if ALGORITHM == "rejection":
    notes.append(f"Rejection ABC kept the {values['n_accepted']:,} simulations closest to the observed statistics (tolerance {res['epsilon']:.4g})"
                 + (", then shifted them by a weighted local-linear regression on the statistics (Beaumont et al. 2002)." if res["adjusted"] else "."))
elif ALGORITHM == "smc":
    notes.append(f"SMC-ABC ran {len(gens) - 1} generation(s) after the prior one (stop: {res['stop']}); each tolerance is the 0.5 quantile of the previous distances, "
                 "particles move by a Gaussian kernel with twice the weighted covariance, and weights are prior over the kernel mixture (Beaumont et al. 2009).")
else:
    notes.append(f"A mixture density network (2 components, two tanh layers of 12) learned the posterior from prior simulations; "
                 f"training stopped at epoch {res['epochs_run']} (best held-out epoch {res['best_epoch']}).")
notes.append("The posterior predictive p is two-sided: how often posterior simulations land at least as far out as the observed statistic.")
statistics = [{"key": f"post_mean[{nm}]", "label": f"{nm} (posterior mean)", "value": values[f"post_mean[{nm}]"]} for nm in params]
cs.publish({
    "method": "simulate.calibrate",
    "methodVersion": "1.1.0",
    "title": "Scenario calibration",
    "engine": cs.engine_info("numpy", "scipy", "pandas") if ALGORITHM != "npe" else cs.engine_info("numpy", "scipy", "pandas", "torch"),
    "n": values["n_simulations"],
    "summary": summary,
    "statistics": statistics,
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": charts,
    "values": values,
    "artifacts": artifacts,
})

Shortened for the Academy: 6 chart(s) dropped to stay under 100 KB; 6 chart(s) dropped to stay under 100 KB.

AlgorithmSimulationsBase demand: mean (interval)
Rejection ABC3,0001,080 (960–1,254)
SMC-ABC2,0001,124 (921–1,394)
NPE6001,110 (955–1,406)

Rejection kept only 60 of its simulations; NPE learned from all of its fewer ones.

05

Predict: a precise answer

Predict

Predict first

An NPE network gives a narrow interval and a low validation loss. Can you report it?

Yes, a narrow interval from a validated network is trustworthyNot yet: precision says nothing about whether the posterior is calibrated or the simulator is right
Reveal

Not yet. A low loss says the network fits the simulations; it doesn't say its intervals have the coverage they claim, and a narrow interval can be precisely wrong if the simulator misrepresents the real process. Check coverage on simulated data, then check the simulator against the real data.

06

Check calibration, then the simulator

Read

Two checks, two questions (lesson 1 again):

  • Is the inference calibrated? Simulate datasets with known θ\theta, run the whole inference on each, and test whether the true values' ranks are uniform. This is SBC for simulators. The method's calibration check does it for rejection and NPE: the smallest p-value across inputs is 0.15 for NPE and 0.74 for rejection, both with few check simulations here.
  • Is the simulator right? Posterior predictive checks: simulate from fitted parameters and compare with the observed statistics. A calibrated posterior of a wrong simulator is precisely wrong.

Summary statistics matter too: if they drop information, every method above conditions on less than the data.

07

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
NPE and sequential NPE (INF020)Partly runs in CodeSplash: amortized NPE with a mixture density network (plus rejection ABC and SMC-ABC) in Calibrate a scenario model to observed statistics, with a calibration check; sequential rounds (SNPE) and flow posteriors aren't offered
08

The whole chapter at a glance

Read
Runs in CodeSplashPartly runsRuns as a notebookExplained here
EM, CAVI, black-box VI, Laplace, importance sampling, SMCSVI, HMC, NUTS, particle MCMC, NPERejection sampling, Metropolis–Hastings, GibbsEP, SGLD, SGHMC, AIS, SVGD, nested sampling

"Partly" for HMC and NUTS means Stan's adaptive sampler runs every Bayesian fit, but you can't write your own model or pick a fixed path length.

09

Check your understanding

Checkpoint

Check yourself

What does NPE's network learn?

Show the answer

Answer: b

Training on prior simulations to predict θ\theta from xx makes the network a posterior estimator; evaluating it at the observed data gives your posterior.

Check yourself

A second NPE round draws parameters from the first round's posterior, not the prior, and trains as usual. What goes wrong?

Show the answer

Answer: b

Sequential variants reweight by p(θ)/r(θ)p(\theta)/r(\theta) or use a different loss (SNPE-C) to undo the proposal's influence.

Check yourself

A sequential NPE estimator passed a coverage check at your observed data. A colleague reuses it for a new observation far from the first. Is that safe?

Show the answer

Answer: b

Amortized NPE (trained on prior simulations) covers the range those simulations cover. Sequential rounds trade that range for accuracy near one observation.

Check yourself

An SBI posterior passes its simulated calibration check, but the posterior predictive simulations don't resemble the observed statistics. What does this suggest?

Show the answer

Answer: b

Calibration checks use the simulator's own data, so they can't see misspecification. Predictive checks against real data can.

10

Recap

Recap
  • SBI learns posteriors from simulations when the likelihood has no formula.
  • NPE trains qϕ(θ∣x)q_\phi(\theta\mid x) on prior simulations; it is amortized across observations.
  • Sequential rounds must correct for their proposal and are tuned to one observation.
  • Check calibration on simulations, then check the simulator with predictive checks.

Concepts in this lesson