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.
What runs in CodeSplash
- INF007Importance sampling and self-normalized importance sampling Runs in CodeSplash
- INF008Rejection sampling Runs as a notebook
- Off-policy evaluation of a decision policy Verified in Python and R
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
The problem: a density you can evaluate but not sample
ReadA posterior is usually known only up to a constant: you can compute at any , 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. 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.
Rejection sampling
ReadRejection 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 with everywhere. Draw and , and keep when
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 , 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;When the envelope is wrong
ReadThe envelope must hold everywhere. Estimate 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 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.
Importance sampling
ReadImportance samplingImportance samplingEstimates an average under a target from draws of another distribution, weighting each draw by target density over proposal density. keeps every draw and weights it by :
The plain estimator needs the normalized target ; the self-normalized one divides by the weights' sum, so the unknown constant cancels, at the cost of a small bias for finite . Estimating 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;Predict: does more sampling help?
PredictPredict 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?
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.
Weights as a diagnostic
ReadThe 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.,
equals 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.
The target is a normal with this mean and SD 1 in every dimension.
The proposal is a normal centered at 0 with this spread.
Weights multiply across dimensions, so mismatch compounds.
Draws from the proposal.
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.
- 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).
Importance sampling in CodeSplash
ReadOff-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.
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
View data
| Value | Upper | Estimator | Lower |
|---|---|---|---|
| 0.4272 | 0.4795 | IPS | 0.3794 |
| 0.4077 | 0.4501 | Self-normalized IPS | 0.3681 |
| 0.4272 | 0.4795 | Clipped IPS | 0.3794 |
| 0.4048 | 0.4086 | Direct method | 0.4010 |
| 0.4058 | 0.4489 | Doubly robust | 0.3648 |
| 0.3553 | 0.3773 | Logged policy | 0.3327 |
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
| Estimator | Estimate | SE | 95% CI low | 95% CI high | vs logged |
|---|---|---|---|---|---|
| IPS | 0.4272 | 0.0277 | 0.3794 | 0.4795 | 0.0719 |
| Self-normalized IPS | 0.4077 | 0.0218 | 0.3681 | 0.4501 | 0.0524 |
| Clipped IPS | 0.4272 | 0.0277 | 0.3794 | 0.4795 | 0.0719 |
| Direct method | 0.4048 | 0.0022 | 0.4010 | 0.4086 | 0.0495 |
| Doubly robust | 0.4058 | 0.0227 | 0.3648 | 0.4489 | 0.0505 |
Weight diagnostics
| Diagnostic | Value |
|---|---|
| Rows | 1,500 |
| Rows where target = logged action | 528 |
| Effective sample size | 512.15 |
| Mean weight (≈ 1 if propensities are right) | 1.048 |
| Largest weight | 4.986 |
| Smallest propensity | 0.1504 |
Actions: logged vs target policy
| offer | Logged share | Target share |
|---|---|---|
| A | 30.4% | 23.2% |
| B | 37.6% | 52.1% |
| C | 32.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)))
)
))
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
| Estimator | Estimate | SE | 95% CI low | 95% CI high | vs logged |
|---|---|---|---|---|---|
| IPS | 0.4272 | 0.0277 | 0.3794 | 0.4795 | 0.0719 |
| Self-normalized IPS | 0.4077 | 0.0218 | 0.3681 | 0.4501 | 0.0524 |
| Clipped IPS | 0.4272 | 0.0277 | 0.3794 | 0.4795 | 0.0719 |
| Direct method | 0.4048 | 0.0022 | 0.4010 | 0.4086 | 0.0495 |
| Doubly robust | 0.4058 | 0.0227 | 0.3648 | 0.4489 | 0.0505 |
Weight diagnostics
| Diagnostic | Value |
|---|---|
| Rows | 1,500 |
| Rows where target = logged action | 528 |
| Effective sample size | 512.15 |
| Mean weight (≈ 1 if propensities are right) | 1.048 |
| Largest weight | 4.986 |
| Smallest propensity | 0.1504 |
Actions: logged vs target policy
| offer | Logged share | Target share |
|---|---|---|
| A | 30.4% | 23.2% |
| B | 37.6% | 52.1% |
| C | 32.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.
Where each idea stands in CodeSplash
Read| Entry | In 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.) |
Check your understanding
CheckpointCheck 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, .
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 proposals per kept draw, and 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, ?
Show the answer
Answer: 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.
Recap
Recap- Rejection sampling: exact independent draws, if covers the target everywhere; cost 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