Skip to content

Sampling from what you can't sample: rejection and importance sampling

Two ways to turn draws from an easy distribution into answers about a hard one: keep some draws (rejection) or weight all of them (importance). Learn what each needs, and how weights tell you they're failing.

Advanced ~14 min10 steps

What runs in CodeSplash

You will be able to

  • State the envelope condition rejection sampling needs, and its acceptance rate
  • Compute an importance-sampling estimate, plain and self-normalized
  • Read the weights' effective sample size and largest weight as warnings
  • Explain why more draws don't rescue a proposal that misses part of the target

Read first

01

The problem: a density you can evaluate but not sample

Read

A posterior is usually known only up to a constant: you can compute p~(θ)=p(y∣θ) p(θ)\tilde p(\theta)=p(y\mid\theta)\,p(\theta) at any θ\theta, but not draw from it. Every method in this track gets around that differently. The two oldest start from a proposal distributionProposal distributionThe easy distribution a sampler draws candidates from before correcting them toward the target by weights, rejection or an accept step. qq that you can draw from, then correct the draws:

  • Rejection sampling keeps some draws and throws the rest away.
  • Importance sampling keeps every draw and gives each a weight.

Both are exact in the right conditions, and both fail loudly or quietly when the proposal is a poor match.

02

Rejection sampling

Read

Rejection samplingRejection samplingDraws from an easy proposal and keeps each draw with probability target / (M × proposal); the kept draws follow the target exactly. needs an envelope: a constant MM with p~(x)≤M q(x)\tilde p(x)\le M\,q(x) everywhere. Draw x∼qx\sim q and u∼U(0,1)u\sim U(0,1), and keep xx when

u≤p~(x)M q(x),Pr⁡(keep)=ZM,Z=∫p~(x) dx.u\le\frac{\tilde p(x)}{M\,q(x)},\qquad \Pr(\text{keep})=\frac{Z}{M},\quad Z=\int\tilde p(x)\,dx.

The kept draws are independent and exactly from the target. The reference's example targets a Beta(2,2) density with a uniform proposal and M=1.5M=1.5, the density's peak; it kept a share of 0.663 of the proposals, close to the two thirds the formula predicts.

Reference · INF008 · Runs as a notebookRejection samplingConverts draws from a proposal into independent target draws by accepting each with a density-ratio probability. With a valid global envelope it is exact up to numerical and random-number implementation;
03

When the envelope is wrong

Read

The envelope must hold everywhere. Estimate MM from a grid, miss the true peak, and the sampler quietly under-samples the region above the envelope. "Fixing" ratios above one by capping them at one doesn't repair it; it samples a different distribution.

The cost is M/ZM/Z proposals per kept draw, and it explodes with dimension: an envelope that hugs a peak in one dimension wastes almost everything in twenty. That is why rejection sampling lives inside other algorithms (one-dimensional conditionals, simple priors) rather than on whole posteriors.

04

Importance sampling

Read

Importance samplingImportance samplingEstimates an average under a target from draws of another distribution, weighting each draw by target density over proposal density. keeps every draw xi∼qx_i\sim q and weights it by wi=p~(xi)/q(xi)w_i=\tilde p(x_i)/q(x_i):

μ^IS=1N∑ip(xi)q(xi)h(xi),μ^SN=∑iwi h(xi)∑iwi.\hat\mu_{IS}=\frac1N\sum_i\frac{p(x_i)}{q(x_i)}h(x_i),\qquad \hat\mu_{SN}=\frac{\sum_i w_i\,h(x_i)}{\sum_i w_i}.

The plain estimator needs the normalized target pp; the self-normalized one divides by the weights' sum, so the unknown constant cancels, at the cost of a small bias for finite NN. Estimating E[X2]=1E[X^2]=1 for a standard normal from wide normal proposals gave 0.994 (plain) and 0.988 (self-normalized).

Reference · INF007 · Runs in CodeSplashImportance sampling and self-normalized importance samplingEstimates target expectations using draws from a different, easier proposal distribution. Ordinary and self-normalized estimators are treated as one family because they share the same sampling mechanism;
05

Predict: does more sampling help?

Predict

Predict first

Your proposal is narrower than the target, so its tails almost never reach where the target still has mass. Will ten times more draws fix the estimate?

Yes, the estimate converges, so more draws fix itNo, a region the proposal almost never reaches stays almost unvisited
Reveal

Not reliably. The estimator is still consistent, but its variance can be infinite: most runs look stable and wrong, and once in a while one huge weight jumps the answer. Several runs agreeing can't reveal a region none of them visited. Use a proposal with heavier tails than the target.

06

Weights as a diagnostic

Read

The weights say how much of the sample is doing the work. Their effective sample sizeEffective sample sizeHow many equally weighted units a weighted sample is worth. Unequal weights make it smaller than the real count.,

ESS=(∑iwi)2∑iwi2,\text{ESS}=\frac{\left(\sum_i w_i\right)^2}{\sum_i w_i^2},

equals NN for equal weights and falls toward 1 when one weight dominates: weight degeneracyWeight degeneracyWhen a few importance weights dominate, so most draws or particles count for nothing and the effective sample size collapses.. In the normal example ESS was 6,632 from 10,000 draws. Also look at the largest normalized weight and a histogram of log weights. A healthy ESS still isn't a certificate: it describes the weights, not the regions the proposal never reached.

Watch the weights collapse as the proposal narrows or the dimensions grow, and how tempering with resampling keeps them useful:

EExplorable · Importance weights and SMC

When do importance weights collapse onto a few particles, and how does tempering with resampling keep them useful?

Method

Weight once, or move from the proposal to the target in small steps, resampling as needed.

1.00

The target is a normal with this mean and SD 1 in every dimension.

1.50

The proposal is a normal centered at 0 with this spread.

1

Weights multiply across dimensions, so mismatch compounds.

300

Draws from the proposal.

10

SMC only: how many small steps from proposal to target.

  • Target (one coordinate)
  • Proposal

Effective sample size

64.1%

of 300 particles, from one round of weighting.

dotted line: equal share 1/Nlargest weights, biggest first
ESS share (lowest)
0.641
Largest weight
0.007
Estimate of the mean
1.011
Log evidence (truth 0)
0.044
Resampling steps
0
  • Puzzle: In 10 or more dimensions, keep the lowest ESS above 20% of the particles.
  • Puzzle: In one dimension, find a proposal that leaves plain importance sampling with an ESS under 10% of the particles.
Plain importance sampling with 300 particles in 1 dimension: the effective sample size is 64.1% of the particles, the largest weight is 0.007, the estimate of the mean is 1.01 (truth 1.00) and the log evidence is 0.04 (truth 0).

Plain importance sampling with 300 particles in 1 dimension: the effective sample size is 64.1% of the particles, the largest weight is 0.007, the estimate of the mean is 1.01 (truth 1.00) and the log evidence is 0.04 (truth 0).

07

Importance sampling in CodeSplash

Read

Off-policy evaluation of a decision policy estimates how a new policy would have done from decisions logged under an old one. It is importance sampling: each logged row is weighted by the new policy's probability of that action over the logging policy's.

Off-policy evaluationRecorded · Python and R agreeRecorded 2026-11-17 · 30 values compared · largest relative difference 2.7e-15
R

The doubly robust estimate says the target policy would earn 0.406 per decision, 95% CI [0.365, 0.449], more than the 0.355 the logged policy earned (+0.050). 528 of 1,500 logged decisions agree with the target policy; the effective sample size of the importance weights is 512.

Target policy value (doubly robust)
0.4058
95% CI
[0.3648, 0.4489]
Logged policy value
0.3553
Effective sample size
512.15

Plots

Estimated value per decisionHow large are several estimates, how precise, and which exclude the null?
View data
ValueUpperEstimatorLower
0.42720.4795IPS0.3794
0.40770.4501Self-normalized IPS0.3681
0.42720.4795Clipped IPS0.3794
0.40480.4086Direct method0.4010
0.40580.4489Doubly robust0.3648
0.35530.3773Logged policy0.3327
Importance weights (rows where target = logged action)How is one numeric variable distributed?
View data
Weight
2.738
2.599
2.539
3.901
2.743
2.452
3.771
2.856
2.771
2.367
3.006
4.434
3.892
2.665
3.166
2.663
3.958
2.659
2.929
2.788
2.925
2.666
4.537
3.740
3.866
2.982
2.762
2.823
3.090
2.325
3.121
3.025
2.500
2.847
2.877
2.344
2.664
2.845
2.400
1.957
2.266
4.013
2.682
2.747
2.821
2.806
2.310
2.872
2.789
2.520
2.506
2.852
2.633
2.527
2.925
2.540
3.654
2.946
3.399
2.856

First 60 of 528 rows.

Estimated value of the target policy

EstimatorEstimateSE95% CI low95% CI highvs logged
IPS0.42720.02770.37940.47950.0719
Self-normalized IPS0.40770.02180.36810.45010.0524
Clipped IPS0.42720.02770.37940.47950.0719
Direct method0.40480.00220.40100.40860.0495
Doubly robust0.40580.02270.36480.44890.0505

Weight diagnostics

DiagnosticValue
Rows1,500
Rows where target = logged action528
Effective sample size512.15
Mean weight (≈ 1 if propensities are right)1.048
Largest weight4.986
Smallest propensity0.1504

Actions: logged vs target policy

offerLogged shareTarget share
A30.4%23.2%
B37.6%52.1%
C32.0%24.7%
  • Weights w = 1[target = logged action] / propensity. Reward model: linear in x1, spend ($), segment, cross-fitted over 2 folds; 400 bootstrap resamples of the per-row contributions (seed 42).
The exact R script · R R version 4.5.1 (2025-06-13)
# Off-policy evaluation of a decision policy
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.ope 1.0.1 · spec 7ba9eba7d39215ad
# Dataset: o2_logged (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_bandit_ope(): twin of codesplash.decide.ope (shared-RNG folds and bootstrap)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/o2_logged.parquet", col_select = c("offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment")))
n_input <- nrow(df)
df[["offer"]] <- factor(df[["offer"]], levels = c("A", "B", "C"))  # stored level order
df[["new policy"]] <- factor(df[["new policy"]], levels = c("A", "B", "C"))  # stored level order
df[["segment"]] <- factor(df[["segment"]], levels = c("new", "returning", "loyal"))  # stored level order
df <- df[stats::complete.cases(df[c("offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment"))  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
a_col <- "offer"
r_col <- "converted"
p_col <- "propensity"
t_col <- "new policy"
features <- c("x1", "spend ($)", "segment")
model <- "linear" # linear | mean
folds <- as.integer(2)
clip <- 10 # NULL = no clipped IPS
n_boot <- as.integer(400)
conf <- 0.95
seed <- 42
lv <- levels(df[[a_col]])
action <- as.character(df[[a_col]])
target <- as.character(df[[t_col]])
# Yes/no rewards count as 1/0.
reward <- if (is.factor(df[[r_col]])) as.numeric(as.character(df[[r_col]]) == "true") else as.numeric(df[[r_col]])
propensity <- as.numeric(df[[p_col]])
is_cat <- vapply(features, function(c) is.factor(df[[c]]), logical(1))
numeric_f <- features[!is_cat]
categorical_f <- lapply(stats::setNames(features[is_cat], features[is_cat]), function(c) levels(df[[c]]))
x <- if (length(features) && model == "linear") cs_bandit_design(df, numeric_f, categorical_f) else NULL

# Every action the target policy picks must be among the logged actions (first unknown one, in sorted order).
unknown <- sort(setdiff(unique(target), lv), method = "radix")
if (length(unknown)) cs_error("CS_E_NOT_A_LEVEL", level = unknown[1], column = a_col)

# %% Estimate
res <- cs_bandit_ope(action, reward, propensity, target, lv, x = x, model = if (length(features)) model else "mean", folds = folds,
                     clip = clip, boot = n_boot, conf = conf, seed = seed)
warnings <- c(warnings, as.list(res$warnings))
n <- res$n
if (abs(res$mean_weight - 1) > 0.1) {
  warnings <- c(warnings, sprintf("The importance weights average %.2f, not 1: the propensities may be wrong, or the logging policy rarely takes the target's actions.", res$mean_weight))
}
if (res$ess < 0.1 * n) {
  warnings <- c(warnings, sprintf("Effective sample size %.0f is under 10%% of the %d rows: IPS-type estimates are noisy; prefer the doubly robust estimate.", res$ess, n))
}
if (res$max_weight > 50) warnings <- c(warnings, sprintf("The largest weight is %.0f: a few rows dominate IPS; compare with clipped IPS and DR.", res$max_weight))
if (!length(features)) warnings <- c(warnings, "No context features: the direct method uses each action's mean reward.")

# %% Result
lab <- cs_bandit_ope_labels()
pct <- sprintf("%.0f%%", conf * 100)
dr <- res$estimate$dr
dr_ci <- res$ci$dr
logged <- res$logged
summary <- sprintf(
  "The doubly robust estimate says the target policy would earn %.3f per decision, %s CI [%.3f, %.3f], %s than the %.3f the logged policy earned (%+.3f). %s of %s logged decisions agree with the target policy; the effective sample size of the importance weights is %.0f.",
  dr, pct, dr_ci[1], dr_ci[2], if (dr > logged) "more" else "less", logged, dr - logged, format(res$matched, big.mark = ","),
  format(n, big.mark = ","), res$ess
)
rows <- do.call(rbind, lapply(res$estimators, function(e) {
  data.frame(estimator = lab[[e]], estimate = res$estimate[[e]], se = res$se[[e]], low = res$ci[[e]][1], high = res$ci[[e]][2],
             diff = res$estimate[[e]] - logged)
}))
values <- list(logged_value = logged, logged_ci_low = res$logged_ci[1], logged_ci_high = res$logged_ci[2], n = n,
               matched = res$matched, ess = res$ess, mean_weight = res$mean_weight, max_weight = res$max_weight,
               min_propensity = res$min_propensity, improvement_dr = dr - logged)
for (e in res$estimators) {
  values[[sprintf("value[%s]", e)]] <- res$estimate[[e]]
  values[[sprintf("se[%s]", e)]] <- res$se[[e]]
  values[[sprintf("ci_low[%s]", e)]] <- res$ci[[e]][1]
  values[[sprintf("ci_high[%s]", e)]] <- res$ci[[e]][2]
}
forest_labels <- c(unname(lab[res$estimators]), "Logged policy")
matched_w <- res$weights[res$weights > 0]
fit_note <- if (!is.null(x)) paste("linear in", paste(features, collapse = ", ")) else "mean reward per action"
cs_publish(list(
  method = "bandit.ope",
  methodVersion = "1.0.1",
  title = "Off-policy evaluation",
  engine = cs_engine_info("stats", "codesplashr"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "dr", label = "Target policy value (doubly robust)", value = dr),
    list(key = "ci", label = paste(pct, "CI"), value = dr_ci),
    list(key = "logged", label = "Logged policy value", value = logged),
    list(key = "ess", label = "Effective sample size", value = res$ess)
  ),
  tables = list(
    list(key = "estimates", title = "Estimated value of the target policy",
         columns = list(list(key = "estimator", label = "Estimator", type = "string"), list(key = "estimate", label = "Estimate", type = "number"),
                        list(key = "se", label = "SE", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
                        list(key = "high", label = paste(pct, "CI high"), type = "number"), list(key = "diff", label = "vs logged", type = "number")),
         rows = rows),
    list(key = "diagnostics", title = "Weight diagnostics",
         columns = list(list(key = "metric", label = "Diagnostic", type = "string"), list(key = "value", label = "Value", type = "number")),
         rows = data.frame(metric = c("Rows", "Rows where target = logged action", "Effective sample size",
                                      "Mean weight (≈ 1 if propensities are right)", "Largest weight", "Smallest propensity"),
                           value = c(n, res$matched, res$ess, res$mean_weight, res$max_weight, res$min_propensity))),
    list(key = "actions", title = "Actions: logged vs target policy",
         columns = list(list(key = "action", label = a_col, type = "string"), list(key = "logged", label = "Logged share", type = "percent"),
                        list(key = "target", label = "Target share", type = "percent")),
         rows = data.frame(action = lv, logged = unname(res$logged_share[lv]), target = unname(res$target_share[lv])))
  ),
  warnings = warnings,
  notes = list(paste0("Weights w = 1[target = logged action] / propensity. Reward model: ", fit_note,
                      if (folds > 1) sprintf(", cross-fitted over %d folds", folds) else ", fit in-sample",
                      sprintf("; %d bootstrap resamples of the per-row contributions (seed %s).", n_boot, seed))),
  values = values,
  charts = list(
    cs_chart("estimates", "forest", "Estimated value per decision", list(
      label = cs_col("Estimator", forest_labels, levels = forest_labels),
      estimate = cs_col("Value", c(rows$estimate, logged)),
      low = cs_col("Lower", c(rows$low, res$logged_ci[1])),
      high = cs_col("Upper", c(rows$high, res$logged_ci[2]))
    ), controls = list(reference = logged)),
    cs_chart("weights", "histogram", "Importance weights (rows where target = logged action)", list(x = cs_col("Weight", matched_w)))
  )
))
Python

The doubly robust estimate says the target policy would earn 0.406 per decision, 95% CI [0.365, 0.449], more than the 0.355 the logged policy earned (+0.050). 528 of 1,500 logged decisions agree with the target policy; the effective sample size of the importance weights is 512.

Target policy value (doubly robust)
0.4058
95% CI
[0.3648, 0.4489]
Logged policy value
0.3553
Effective sample size
512.15

To keep this page light, the plots are shown once, under the R tab.

Estimated value of the target policy

EstimatorEstimateSE95% CI low95% CI highvs logged
IPS0.42720.02770.37940.47950.0719
Self-normalized IPS0.40770.02180.36810.45010.0524
Clipped IPS0.42720.02770.37940.47950.0719
Direct method0.40480.00220.40100.40860.0495
Doubly robust0.40580.02270.36480.44890.0505

Weight diagnostics

DiagnosticValue
Rows1,500
Rows where target = logged action528
Effective sample size512.15
Mean weight (≈ 1 if propensities are right)1.048
Largest weight4.986
Smallest propensity0.1504

Actions: logged vs target policy

offerLogged shareTarget share
A30.4%23.2%
B37.6%52.1%
C32.0%24.7%
  • Weights w = 1[target = logged action] / propensity. Reward model: linear in x1, spend ($), segment, cross-fitted over 2 folds; 400 bootstrap resamples of the per-row contributions (seed 42).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Off-policy evaluation of a decision policy
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method bandit.ope 1.0.1 · spec 7ba9eba7d39215ad
# Dataset: o2_logged (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.decide import ope  # twin of codesplashr::cs_bandit_ope (shared-RNG folds and bootstrap)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/o2_logged.parquet", columns=["offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment"])
n_input = len(df)
df["offer"] = pd.Categorical(df["offer"], categories=["A", "B", "C"])  # stored level order
df["new policy"] = pd.Categorical(df["new policy"], categories=["A", "B", "C"])  # stored level order
df["segment"] = pd.Categorical(df["segment"], categories=["new", "returning", "loyal"])  # stored level order
df = df.dropna(subset=["offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment"])  # listwise deletion over the analysis columns
df["offer"] = df["offer"].cat.remove_unused_categories()
df["new policy"] = df["new policy"].cat.remove_unused_categories()
df["segment"] = df["segment"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["offer", "converted", "propensity", "new policy", "x1", "spend ($)", "segment"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
a_col, r_col, p_col, t_col = "offer", "converted", "propensity", "new policy"
features = ["x1", "spend ($)", "segment"]
model = "linear"  # linear | mean
folds = int(2)
clip = 10  # None = no clipped IPS
n_boot = int(400)
conf = 0.95
seed = 42
levels = [str(x) for x in df[a_col].cat.categories]
action = df[a_col].astype(str).to_numpy()
target = df[t_col].astype(str).to_numpy()
# Yes/no rewards count as 1/0.
reward = (df[r_col].astype(str) == "true").astype(float).to_numpy() if isinstance(df[r_col].dtype, pd.CategoricalDtype) else df[r_col].to_numpy(dtype=float)
propensity = df[p_col].to_numpy(dtype=float)
numeric = [c for c in features if not isinstance(df[c].dtype, pd.CategoricalDtype)]
categorical = {c: [str(x) for x in df[c].cat.categories] for c in features if isinstance(df[c].dtype, pd.CategoricalDtype)}
x = ope.design(df, numeric, categorical) if features and model == "linear" else None

# Every action the target policy picks must be among the logged actions (first unknown one, in sorted order).
unknown = sorted(set(target) - set(levels))
if unknown:
    cs.cs_error("CS_E_NOT_A_LEVEL", level=unknown[0], column=a_col)

# %% Estimate
res = ope.ope(action, reward, propensity, target, levels, x=x, model=model if features else "mean", folds=folds, clip=clip,
              boot=n_boot, conf=conf, seed=seed)
warnings += res["warnings"]
n = res["n"]
if abs(res["mean_weight"] - 1) > 0.1:
    warnings.append(f"The importance weights average {res['mean_weight']:.2f}, not 1: the propensities may be wrong, or the logging policy rarely takes the target's actions.")
if res["ess"] < 0.1 * n:
    warnings.append(f"Effective sample size {res['ess']:.0f} is under 10% of the {n} rows: IPS-type estimates are noisy; prefer the doubly robust estimate.")
if res["max_weight"] > 50:
    warnings.append(f"The largest weight is {res['max_weight']:.0f}: a few rows dominate IPS; compare with clipped IPS and DR.")
if not features:
    warnings.append("No context features: the direct method uses each action's mean reward.")

# %% Result
lab = ope.LABELS
pct = f"{conf:.0%}"
dr, (dr_lo, dr_hi) = res["estimate"]["dr"], res["ci"]["dr"]
logged = res["logged"]
direction = "more" if dr > logged else "less"
summary = (
    f"The doubly robust estimate says the target policy would earn {dr:.3f} per decision, {pct} CI [{dr_lo:.3f}, {dr_hi:.3f}], "
    f"{direction} than the {logged:.3f} the logged policy earned ({dr - logged:+.3f}). {res['matched']:,} of {n:,} logged decisions agree with "
    f"the target policy; the effective sample size of the importance weights is {res['ess']:.0f}."
)
rows = [
    {"estimator": lab[e], "estimate": res["estimate"][e], "se": res["se"][e], "low": res["ci"][e][0], "high": res["ci"][e][1],
     "diff": res["estimate"][e] - logged}
    for e in res["estimators"]
]
values = {"logged_value": logged, "logged_ci_low": res["logged_ci"][0], "logged_ci_high": res["logged_ci"][1], "n": n,
          "matched": res["matched"], "ess": res["ess"], "mean_weight": res["mean_weight"], "max_weight": res["max_weight"],
          "min_propensity": res["min_propensity"], "improvement_dr": dr - logged}
for e in res["estimators"]:
    values[f"value[{e}]"] = res["estimate"][e]
    values[f"se[{e}]"] = res["se"][e]
    values[f"ci_low[{e}]"] = res["ci"][e][0]
    values[f"ci_high[{e}]"] = res["ci"][e][1]
forest_labels = [lab[e] for e in res["estimators"]] + ["Logged policy"]
matched_w = res["weights"][res["weights"] > 0]
cs.publish({
    "method": "bandit.ope",
    "methodVersion": "1.0.1",
    "title": "Off-policy evaluation",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "dr", "label": "Target policy value (doubly robust)", "value": dr},
        {"key": "ci", "label": f"{pct} CI", "value": [dr_lo, dr_hi]},
        {"key": "logged", "label": "Logged policy value", "value": logged},
        {"key": "ess", "label": "Effective sample size", "value": res["ess"]},
    ],
    "tables": [
        {"key": "estimates", "title": "Estimated value of the target policy",
         "columns": [{"key": "estimator", "label": "Estimator", "type": "string"}, {"key": "estimate", "label": "Estimate", "type": "number"},
                     {"key": "se", "label": "SE", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
                     {"key": "high", "label": f"{pct} CI high", "type": "number"}, {"key": "diff", "label": "vs logged", "type": "number"}],
         "rows": rows},
        {"key": "diagnostics", "title": "Weight diagnostics",
         "columns": [{"key": "metric", "label": "Diagnostic", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
         "rows": [{"metric": "Rows", "value": n}, {"metric": "Rows where target = logged action", "value": res["matched"]},
                  {"metric": "Effective sample size", "value": res["ess"]}, {"metric": "Mean weight (≈ 1 if propensities are right)", "value": res["mean_weight"]},
                  {"metric": "Largest weight", "value": res["max_weight"]}, {"metric": "Smallest propensity", "value": res["min_propensity"]}]},
        {"key": "actions", "title": "Actions: logged vs target policy",
         "columns": [{"key": "action", "label": a_col, "type": "string"}, {"key": "logged", "label": "Logged share", "type": "percent"},
                     {"key": "target", "label": "Target share", "type": "percent"}],
         "rows": [{"action": lv, "logged": res["logged_share"][lv], "target": res["target_share"][lv]} for lv in levels]},
    ],
    "warnings": warnings,
    "notes": [
        "Weights w = 1[target = logged action] / propensity. Reward model: " + f"{'linear in ' + ', '.join(features) if x is not None else 'mean reward per action'}"
        + (f", cross-fitted over {folds} folds" if folds > 1 else ", fit in-sample") + f"; {n_boot} bootstrap resamples of the per-row contributions (seed {seed}).",
    ],
    "values": values,
    "charts": [
        cs.chart("estimates", "forest", "Estimated value per decision", {
            "label": cs.col("Estimator", forest_labels, levels=forest_labels),
            "estimate": cs.col("Value", [r["estimate"] for r in rows] + [logged]),
            "low": cs.col("Lower", [r["low"] for r in rows] + [res["logged_ci"][0]]),
            "high": cs.col("Upper", [r["high"] for r in rows] + [res["logged_ci"][1]]),
        }, controls={"reference": logged}),
        cs.chart("weights", "histogram", "Importance weights (rows where target = logged action)", {"x": cs.col("Weight", matched_w)}),
    ],
})

From 1,500 logged rows, the weights are worth an ESS of 512, and the largest weight is 4.99. The plain (IPS) estimate is 0.427 with SE 0.028; self-normalized (SNIPS) gives 0.408 with a smaller SE, 0.022. The Bayesian models studio uses the same idea for leave-one-out (PSIS-LOO), where Pareto k̂ flags rows whose weights are too heavy-tailed.

08

Where each idea stands in CodeSplash

Read
EntryIn CodeSplash
Importance sampling (INF007)Runs in CodeSplash: IPS and self-normalized IPS in Off-policy evaluation of a decision policy; Pareto-smoothed weights inside PSIS-LOO in Bayesian regression model (Stan)
Rejection sampling (INF008)Runs as a notebook: the reference's Beta(2,2) program is verified in Python and R; there is no method. (The ABC rejection in Calibrate a scenario model is a different idea: it keeps simulations close to the data, not draws under an envelope.)
09

Check your understanding

Checkpoint

Check yourself

What condition makes rejection sampling exact?

Show the answer

Answer: b

The envelope must cover the target at every point. The target's normalizing constant isn't needed; it only sets the acceptance rate, Z/MZ/M.

Check yourself

Your envelope was estimated on a grid and turns out to be too low near the peak, so some ratios exceed 1. A colleague caps them at 1. What happens?

Show the answer

Answer: b

Above the envelope, the sampler keeps too few draws, and capping can't add them back. Derive a valid global bound instead.

Check yourself

Why is plain rejection sampling rarely used on a whole 20-parameter posterior?

Show the answer

Answer: c

The cost is M/ZM/Z proposals per kept draw, and M/ZM/Z grows very fast with dimension. Rejection sampling earns its place on one-dimensional pieces inside bigger algorithms.

Check yourself

Why use the self-normalized importance estimator on a posterior?

Show the answer

Answer: b

Posteriors are known up to the evidence. Self-normalizing trades a small finite-sample bias for not needing that constant.

Check yourself

Four importance weights are 1, 1, 0 and 0. What is their effective sample size, (∑w)2/∑w2(\sum w)^2/\sum w^2?

Show the answer

Answer: 2

(1+1)2/(1+1)=2(1+1)^2/(1+1)=2. Two of the four draws carry all the weight.

Check yourself

An off-policy estimate rests on 1,500 logged rows, but one row's weight is half of the total. What should you conclude?

Show the answer

Answer: b

Weight degeneracy makes the nominal sample size meaningless. Look at ESS and the largest weight before the estimate; clipping trades bias for stability and must be reported as such.

10

Recap

Recap
  • Rejection sampling: exact independent draws, if M qM\,q covers the target everywhere; cost M/ZM/Z per draw.
  • Importance sampling: weight every draw by target over proposal; self-normalizing removes the unknown constant.
  • Weight ESS and the largest weight are warnings, not certificates.
  • A proposal must have heavier tails than the target; more draws can't fix missed regions.

Concepts in this lesson