Judge a policy over whole episodes
Estimate a new policy's return per episode from logged episodes with per-decision importance sampling, fitted Q evaluation and the weighted doubly robust estimator, and read the episode weights as a warning.
What runs in CodeSplash
- Off-policy evaluation of a sequential policy Verified in Python and R
You will be able to
- Compute a per-decision importance-sampling estimate by hand
- Say why weights collapse on long episodes and what the effective sample size shows
- Choose between importance sampling, fitted Q evaluation and weighted doubly robust from the diagnostics
One weight per episode, built step by step
ReadIn one-step off-policy evaluationOff-policy evaluationEstimates how a new decision policy would have done, using only logs from the current policy. each logged row gets the weight 1 / propensity when the new policy agrees with it. Over an episode the new policy has to agree at every step to reach a later reward, so the weights multiply. After step t the episode's weight is
and it drops to 0 for good at the first step where the new policy would have done something else.
Per-decision importance samplingPer-decision importance samplingWeights each reward by the product of 1 / propensity over the steps so far where the new policy agrees with the log; 0 after a mismatch. weights each reward by the weight reached at its own step, then averages the episodes:
Compute it
CheckpointCheck yourself
Two logged episodes, no discount. Episode A: the new policy agrees at both steps, each logged with propensity 0.5; rewards 0 then 1. Episode B: the new policy disagrees at the first step; reward 1, then the episode ends. What is the per-decision importance-sampling estimate?
Show the answer
Answer: 2
Episode A: after step 1 the weight is 1 / 0.5 = 2 (reward 0); after step 2 it is 2 / 0.5 = 4, times reward 1 = 4. Episode B: the weight is 0 from the first step, so it adds 0. Average over the two episodes: (4 + 0) / 2 = 2.
Check yourself
A new policy agrees with five logged steps in a row, each logged with probability 0.5. What is the episode's weight after the fifth step?
Show the answer
Answer: 32
2 × 2 × 2 × 2 × 2 = 32. One matching five-step episode counts as much as 32 ordinary ones, and most other episodes get 0: that is why long episodes make importance sampling noisy.
When the weights collapse
In the appThe weighted doubly robust estimate says the target policy would earn 0.709 per episode (discount 1), 90% CI [0.641, 0.744], more than the 0.167 the logged policy earned (+0.542), from 60 episodes and 640 decisions. The target policy agrees with every logged action in 3 episodes; the effective sample size of the episode weights is 2.5.
- Target policy value (weighted doubly robust)
- 0.7090
- 90% CI
- [0.6408, 0.7441]
- Logged policy value
- 0.1667
- Effective sample size (episodes)
- 2.514
Plots
View data
| Value | Upper | Estimator | Lower |
|---|---|---|---|
| 0.7239 | 1.626 | Trajectory IS | 0.1388 |
| 0.7385 | 1.872 | Per-decision IS | −0.0395 |
| 0.7134 | 0.7500 | Weighted IS | 0.7000 |
| 0.6991 | 0.8433 | Weighted per-decision IS | 0.0682 |
| 0.5325 | 0.5450 | Fitted Q evaluation | 0.5193 |
| 0.7055 | 0.8572 | Doubly robust | 0.6023 |
| 0.7090 | 0.7441 | Weighted doubly robust | 0.6408 |
| 0.1667 | 0.2751 | Logged policy | 0.0516 |
View data
| Policy | Weight | Episode return |
|---|---|---|
| Logged policy | 1 | 0.7500 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.3500 |
| Logged policy | 1 | 0.5500 |
| Logged policy | 1 | 0.7000 |
| Logged policy | 1 | 0.4000 |
| Logged policy | 1 | 0.4500 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.5000 |
| Logged policy | 1 | 0.5500 |
| Logged policy | 1 | 0.4500 |
| Logged policy | 1 | 0.5000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.3000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.7000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.7000 |
| Logged policy | 1 | 0.6500 |
| Logged policy | 1 | 0.4000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.3000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.5500 |
| Logged policy | 1 | 0.7000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.7500 |
| Logged policy | 1 | 0.4500 |
| Logged policy | 1 | 0.5500 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.5000 |
| Logged policy | 1 | 0.7000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.6500 |
| Logged policy | 1 | 0.4500 |
| Logged policy | 1 | 0.5000 |
| Logged policy | 1 | 0.6500 |
| Logged policy | 1 | 0.5000 |
| Logged policy | 1 | 0.7000 |
| Logged policy | 1 | 0.7500 |
| Logged policy | 1 | 0.5000 |
| Logged policy | 1 | 0.4000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.5000 |
| Logged policy | 1 | 0.3500 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.6500 |
| Logged policy | 1 | −0.7000 |
| Logged policy | 1 | 0.3500 |
| Logged policy | 1 | 0.6500 |
| Logged policy | 1 | 0.6000 |
| Logged policy | 1 | 0.5500 |
| Logged policy | 1 | 0.5000 |
| Logged policy | 1 | 0.4500 |
| Logged policy | 1 | 0.4500 |
First 60 of 120 rows.
View data
| Weight |
|---|
| 16.327 |
| 32.653 |
| 11.900 |
Estimated value of the target policy (per episode)
| Estimator | Estimate | SE | 90% CI low | 90% CI high | vs logged |
|---|---|---|---|---|---|
| Trajectory IS | 0.7239 | 0.4480 | 0.1388 | 1.626 | 0.5572 |
| Per-decision IS | 0.7385 | 0.5673 | −0.0395 | 1.872 | 0.5719 |
| Weighted IS | 0.7134 | 0.0152 | 0.7000 | 0.7500 | 0.5467 |
| Weighted per-decision IS | 0.6991 | 0.2272 | 0.0682 | 0.8433 | 0.5324 |
| Fitted Q evaluation | 0.5325 | 0.0082 | 0.5193 | 0.5450 | 0.3658 |
| Doubly robust | 0.7055 | 0.0792 | 0.6023 | 0.8572 | 0.5388 |
| Weighted doubly robust | 0.7090 | 0.0321 | 0.6408 | 0.7441 | 0.5423 |
Weight diagnostics
| Diagnostic | Value |
|---|---|
| Episodes | 60 |
| Decisions | 640 |
| Longest episode (steps) | 14 |
| Episodes where the target agrees with every logged action | 3 |
| Effective sample size (episodes) | 2.514 |
| Mean episode weight (≈ 1 if propensities are right) | 1.015 |
| Largest episode weight | 32.653 |
| FQE iterations | 78 |
Weights by step
| Step | Episodes still going | Mean cumulative weight | Effective sample size |
|---|---|---|---|
| 1 | 60 | 1.024 | 35.973 |
| 2 | 60 | 0.9061 | 17.358 |
| 3 | 60 | 0.7017 | 8.614 |
| 4 | 60 | 1.077 | 6.670 |
| 5 | 60 | 1.072 | 4.729 |
| 6 | 57 | 1.015 | 2.514 |
| 7 | 51 | 1.015 | 2.514 |
| 8 | 46 | 1.015 | 2.514 |
| 9 | 45 | 1.015 | 2.514 |
| 10 | 40 | 1.015 | 2.514 |
| 11 | 32 | 1.015 | 2.514 |
| 12 | 26 | 1.015 | 2.514 |
| 13 | 23 | 1.015 | 2.514 |
| 14 | 20 | 1.015 | 2.514 |
- Effective sample size 2.5 is under 10% of the 60 episodes: importance-weighted estimates are noisy; prefer the doubly robust or FQE estimate.
- The target policy agrees with every logged action in only 3 of 60 episodes; the other episodes get weight 0 from that step on.
- Per-decision weights 1[target = logged action] / propensity, multiplied along each episode; returns discounted by 1 per step. FQE: a linear model in position, weather today per action, iterated to its fixed point, fit on all episodes; 300 bootstrap resamples of episodes (seed 42). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).
The exact R script · R R version 4.5.1 (2025-06-13)
# Off-policy evaluation of a sequential policy
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.ope_sequential 1.0.0 · spec f4acbedd40702250
# Dataset: pol_corridor (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_design(), cs_seq_*(): twins of codesplash.decide.ope / sequential (shared-RNG folds and bootstrap)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/pol_corridor.parquet", col_select = c("episode", "step", "position", "weather today", "action", "reward", "propensity", "always_right")))
n_input <- nrow(df)
df[["weather today"]] <- factor(df[["weather today"]], levels = c("rain", "sun")) # stored level order
df[["action"]] <- factor(df[["action"]], levels = c("left", "stay", "right")) # stored level order
df[["always_right"]] <- factor(df[["always_right"]], levels = c("right")) # stored level order
df <- df[stats::complete.cases(df[c("episode", "step", "position", "weather today", "action", "reward", "propensity", "always_right")]), , 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("episode", "step", "position", "weather today", "action", "reward", "propensity", "always_right")) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
ep_col <- "episode"
step_col <- "step"
a_col <- "action"
r_col <- "reward"
p_col <- "propensity"
t_col <- "always_right"
done_col <- NULL
features <- c("position", "weather today")
gamma <- as.numeric(1)
model <- "linear" # linear | mean
folds <- as.integer(1)
iterations <- as.integer(200)
n_boot <- as.integer(300)
conf <- 0.9
seed <- 42
# Yes/no columns count as 1/0.
as_flag <- function(v) if (is.factor(v)) as.character(v) == "true" else as.numeric(v) != 0
# Rows by episode (first appearance), then step.
ep_keys <- if (is.factor(df[[ep_col]])) as.character(df[[ep_col]]) else as.numeric(df[[ep_col]])
ord <- cs_seq_order(cs_seq_episode_codes(ep_keys), as.numeric(df[[step_col]]))
df <- df[ord, , drop = FALSE]
rownames(df) <- NULL
ep <- cs_seq_episode_codes(ep_keys[ord])
st <- cs_seq_structure(ep, as.numeric(df[[step_col]]), if (!is.null(done_col)) as_flag(df[[done_col]]) else NULL)
lv <- levels(df[[a_col]])
action <- as.character(df[[a_col]])
target <- as.character(df[[t_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as_flag(df[[r_col]])) 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]]))
# %% Checks (same order in both engines)
if (st$duplicates > 0) cs_error("CS_E_INVALID_VALUES", column = step_col, requirement = "unique within each episode", count = st$duplicates)
bad <- sum(propensity <= 0 | propensity > 1)
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = p_col, requirement = "a probability in (0, 1]", count = bad)
if (st$E < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = ep_col, min = 2, k = st$E)
unknown <- sort(setdiff(unique(target), lv), method = "radix")
if (length(unknown)) cs_error("CS_E_NOT_A_LEVEL", level = unknown[1], column = a_col)
a_idx <- match(action, lv)
pi_idx <- match(target, lv)
x <- if (model == "linear") cs_bandit_design(df, numeric_f, categorical_f) else matrix(1, nrow = nrow(df), ncol = 1)
# %% Estimate
res <- cs_seq_evaluate(st, x, a_idx, pi_idx, reward, propensity, length(lv), gamma, folds, iterations, n_boot, conf, seed, ep)
E <- res$E
n <- res$n
if (st$truncated > 0) {
warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true (cut short): their returns stop there, and their last step is left out of the Q-model because its next state is unknown.", st$truncated, E, done_col))
}
if (res$ess < 0.1 * E) {
warnings <- c(warnings, sprintf("Effective sample size %.1f is under 10%% of the %d episodes: importance-weighted estimates are noisy; prefer the doubly robust or FQE estimate.", res$ess, E))
}
if (res$matched < E) {
warnings <- c(warnings, sprintf("The target policy agrees with every logged action in only %d of %d episodes; the other episodes get weight 0 from that step on.", res$matched, E))
}
if (!res$fqe_converged) {
warnings <- c(warnings, sprintf("Fitted Q evaluation did not settle within %d iterations; raise the iteration limit or lower the discount.", iterations))
}
if (res$missing_support) {
warnings <- c(warnings, "The target policy takes an action at some states that the training episodes never logged; FQE values those actions at 0 there.")
}
# %% Result
lab <- cs_seq_labels()
pct <- sprintf("%.0f%%", conf * 100)
wdr <- res$estimate$wdr
wdr_ci <- res$ci$wdr
logged <- res$logged
gfmt <- format(gamma, digits = 6)
summary <- sprintf(
"The weighted doubly robust estimate says the target policy would earn %.3f per episode (discount %s), %s CI [%.3f, %.3f], %s than the %.3f the logged policy earned (%+.3f), from %s episodes and %s decisions. The target policy agrees with every logged action in %s episodes; the effective sample size of the episode weights is %.1f.",
wdr, gfmt, pct, wdr_ci[1], wdr_ci[2], if (wdr > logged) "more" else "less", logged, wdr - logged, format(E, big.mark = ","),
format(n, big.mark = ","), format(res$matched, 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_episodes = E,
n_steps = n, horizon = res$H, matched_episodes = res$matched, ess = res$ess, mean_weight = res$mean_weight,
max_weight = res$max_weight, improvement_wdr = wdr - logged, fqe_iterations = res$fqe_iterations, target_label = t_col)
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(unlist(lab[res$estimators])), "Logged policy")
w_end <- res$weights
returns <- res$returns
fqe_note <- if (model == "linear") paste("a linear model in", paste(features, collapse = ", ")) else "a mean"
cs_publish(list(
method = "decide.ope_sequential",
methodVersion = "1.0.0",
title = "Sequential off-policy evaluation",
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = summary,
statistics = list(
list(key = "wdr", label = "Target policy value (weighted doubly robust)", value = wdr),
list(key = "ci", label = paste(pct, "CI"), value = wdr_ci),
list(key = "logged", label = "Logged policy value", value = logged),
list(key = "ess", label = "Effective sample size (episodes)", value = res$ess)
),
tables = list(
list(key = "estimates", title = "Estimated value of the target policy (per episode)",
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("Episodes", "Decisions", "Longest episode (steps)", "Episodes where the target agrees with every logged action",
"Effective sample size (episodes)", "Mean episode weight (≈ 1 if propensities are right)",
"Largest episode weight", "FQE iterations"),
value = c(E, n, res$H, res$matched, res$ess, res$mean_weight, res$max_weight, res$fqe_iterations))),
list(key = "steps", title = "Weights by step",
columns = list(list(key = "t", label = "Step", type = "integer"), list(key = "episodes", label = "Episodes still going", type = "integer"),
list(key = "mean_weight", label = "Mean cumulative weight", type = "number"), list(key = "ess", label = "Effective sample size", type = "number")),
rows = data.frame(t = vapply(res$steps, function(s) s$t + 1L, integer(1)), episodes = vapply(res$steps, function(s) as.integer(s$episodes), integer(1)),
mean_weight = vapply(res$steps, function(s) s$mean_weight, numeric(1)), ess = vapply(res$steps, function(s) s$ess, numeric(1))))
),
warnings = warnings,
notes = list(paste0("Per-decision weights 1[target = logged action] / propensity, multiplied along each episode; returns discounted by ", gfmt,
" per step. FQE: ", fqe_note, " per action, iterated to its fixed point",
if (folds > 1) sprintf(", cross-fitted over %d episode folds", folds) else ", fit on all episodes",
sprintf("; %d bootstrap resamples of episodes (seed %s). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).", n_boot, seed))),
values = values,
charts = list(
cs_chart("estimates", "forest", "Estimated value per episode", 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("profile", "performance-profile", "Episode returns: logged vs target policy", list(
x = cs_col("Episode return", c(returns, returns)),
weight = cs_col("Weight", c(rep(1, E), w_end)),
series = cs_col("Policy", c(rep("Logged policy", E), rep("Target policy (weighted)", E)), levels = c("Logged policy", "Target policy (weighted)"))
)),
cs_chart("weights", "histogram", "Episode weights (episodes the target policy agrees with)", list(x = cs_col("Weight", w_end[w_end > 0])))
)
))
The weighted doubly robust estimate says the target policy would earn 0.709 per episode (discount 1), 90% CI [0.641, 0.744], more than the 0.167 the logged policy earned (+0.542), from 60 episodes and 640 decisions. The target policy agrees with every logged action in 3 episodes; the effective sample size of the episode weights is 2.5.
- Target policy value (weighted doubly robust)
- 0.7090
- 90% CI
- [0.6408, 0.7441]
- Logged policy value
- 0.1667
- Effective sample size (episodes)
- 2.514
To keep this page light, the plots are shown once, under the R tab.
Estimated value of the target policy (per episode)
| Estimator | Estimate | SE | 90% CI low | 90% CI high | vs logged |
|---|---|---|---|---|---|
| Trajectory IS | 0.7239 | 0.4480 | 0.1388 | 1.626 | 0.5572 |
| Per-decision IS | 0.7385 | 0.5673 | −0.0395 | 1.872 | 0.5719 |
| Weighted IS | 0.7134 | 0.0152 | 0.7000 | 0.7500 | 0.5467 |
| Weighted per-decision IS | 0.6991 | 0.2272 | 0.0682 | 0.8433 | 0.5324 |
| Fitted Q evaluation | 0.5325 | 0.0082 | 0.5193 | 0.5450 | 0.3658 |
| Doubly robust | 0.7055 | 0.0792 | 0.6023 | 0.8572 | 0.5388 |
| Weighted doubly robust | 0.7090 | 0.0321 | 0.6408 | 0.7441 | 0.5423 |
Weight diagnostics
| Diagnostic | Value |
|---|---|
| Episodes | 60 |
| Decisions | 640 |
| Longest episode (steps) | 14 |
| Episodes where the target agrees with every logged action | 3 |
| Effective sample size (episodes) | 2.514 |
| Mean episode weight (≈ 1 if propensities are right) | 1.015 |
| Largest episode weight | 32.653 |
| FQE iterations | 78 |
Weights by step
| Step | Episodes still going | Mean cumulative weight | Effective sample size |
|---|---|---|---|
| 1 | 60 | 1.024 | 35.973 |
| 2 | 60 | 0.9061 | 17.358 |
| 3 | 60 | 0.7017 | 8.614 |
| 4 | 60 | 1.077 | 6.670 |
| 5 | 60 | 1.072 | 4.729 |
| 6 | 57 | 1.015 | 2.514 |
| 7 | 51 | 1.015 | 2.514 |
| 8 | 46 | 1.015 | 2.514 |
| 9 | 45 | 1.015 | 2.514 |
| 10 | 40 | 1.015 | 2.514 |
| 11 | 32 | 1.015 | 2.514 |
| 12 | 26 | 1.015 | 2.514 |
| 13 | 23 | 1.015 | 2.514 |
| 14 | 20 | 1.015 | 2.514 |
- Effective sample size 2.5 is under 10% of the 60 episodes: importance-weighted estimates are noisy; prefer the doubly robust or FQE estimate.
- The target policy agrees with every logged action in only 3 of 60 episodes; the other episodes get weight 0 from that step on.
- Per-decision weights 1[target = logged action] / propensity, multiplied along each episode; returns discounted by 1 per step. FQE: a linear model in position, weather today per action, iterated to its fixed point, fit on all episodes; 300 bootstrap resamples of episodes (seed 42). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Off-policy evaluation of a sequential policy
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.ope_sequential 1.0.0 · spec f4acbedd40702250
# Dataset: pol_corridor (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, sequential as seq # twins of codesplashr::cs_bandit_design / cs_seq_* (shared-RNG folds and bootstrap)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_corridor.parquet", columns=["episode", "step", "position", "weather today", "action", "reward", "propensity", "always_right"])
n_input = len(df)
df["weather today"] = pd.Categorical(df["weather today"], categories=["rain", "sun"]) # stored level order
df["action"] = pd.Categorical(df["action"], categories=["left", "stay", "right"]) # stored level order
df["always_right"] = pd.Categorical(df["always_right"], categories=["right"]) # stored level order
df = df.dropna(subset=["episode", "step", "position", "weather today", "action", "reward", "propensity", "always_right"]) # listwise deletion over the analysis columns
df["weather today"] = df["weather today"].cat.remove_unused_categories()
df["action"] = df["action"].cat.remove_unused_categories()
df["always_right"] = df["always_right"].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, ["episode", "step", "position", "weather today", "action", "reward", "propensity", "always_right"]) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
ep_col, step_col, a_col, r_col, p_col, t_col = "episode", "step", "action", "reward", "propensity", "always_right"
done_col = None
features = ["position", "weather today"]
gamma = float(1)
model = "linear" # linear | mean
folds = int(1)
iterations = int(200)
n_boot = int(300)
conf = 0.9
seed = 42
def as_flag(s):
"""Yes/no columns count as 1/0."""
return (s.astype(str) == "true").to_numpy() if isinstance(s.dtype, pd.CategoricalDtype) else (s.to_numpy(dtype=float) != 0)
# Rows by episode (first appearance), then step.
ep_keys = df[ep_col].astype(str).tolist() if isinstance(df[ep_col].dtype, pd.CategoricalDtype) else df[ep_col].to_numpy(dtype=float).tolist()
order = seq.order_rows(seq.episode_codes(ep_keys), df[step_col].to_numpy(dtype=float))
df = df.iloc[order].reset_index(drop=True)
ep_keys = [ep_keys[i] for i in order]
ep = seq.episode_codes(ep_keys)
st = seq.structure(ep, df[step_col].to_numpy(dtype=float), as_flag(df[done_col]) if done_col else None)
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()
reward = as_flag(df[r_col]).astype(float) 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)}
# %% Checks (same order in both engines)
if st["duplicates"]:
cs.cs_error("CS_E_INVALID_VALUES", column=step_col, requirement="unique within each episode", count=st["duplicates"])
bad = int(np.sum((propensity <= 0) | (propensity > 1)))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=p_col, requirement="a probability in (0, 1]", count=bad)
if st["E"] < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=ep_col, min=2, k=st["E"])
unknown = sorted(set(target) - set(levels))
if unknown:
cs.cs_error("CS_E_NOT_A_LEVEL", level=unknown[0], column=a_col)
col_of = {lv: j for j, lv in enumerate(levels)}
a_idx = np.array([col_of[a] for a in action], dtype=np.int64)
pi_idx = np.array([col_of[a] for a in target], dtype=np.int64)
x = ope.design(df, numeric, categorical) if model == "linear" else np.ones((len(df), 1))
# %% Estimate
res = seq.evaluate(st, x, a_idx, pi_idx, reward, propensity, len(levels), gamma, folds, iterations, n_boot, conf, seed, ep)
E, n = res["E"], res["n"]
if st["truncated"]:
warnings.append(f"{st['truncated']} of {E} episodes end without {done_col} = true (cut short): their returns stop there, and their last step is left out of the Q-model because its next state is unknown.")
if res["ess"] < 0.1 * E:
warnings.append(f"Effective sample size {res['ess']:.1f} is under 10% of the {E} episodes: importance-weighted estimates are noisy; prefer the doubly robust or FQE estimate.")
if res["matched"] < E:
warnings.append(f"The target policy agrees with every logged action in only {res['matched']} of {E} episodes; the other episodes get weight 0 from that step on.")
if not res["fqe_converged"]:
warnings.append(f"Fitted Q evaluation did not settle within {iterations} iterations; raise the iteration limit or lower the discount.")
if res["missing_support"]:
warnings.append("The target policy takes an action at some states that the training episodes never logged; FQE values those actions at 0 there.")
# %% Result
lab = seq.LABELS
pct = f"{conf:.0%}"
wdr, (wdr_lo, wdr_hi) = res["estimate"]["wdr"], res["ci"]["wdr"]
logged = res["logged"]
direction = "more" if wdr > logged else "less"
summary = (
f"The weighted doubly robust estimate says the target policy would earn {wdr:.3f} per episode (discount {gamma:g}), {pct} CI [{wdr_lo:.3f}, {wdr_hi:.3f}], "
f"{direction} than the {logged:.3f} the logged policy earned ({wdr - logged:+.3f}), from {E:,} episodes and {n:,} decisions. "
f"The target policy agrees with every logged action in {res['matched']:,} episodes; the effective sample size of the episode weights is {res['ess']:.1f}."
)
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_episodes": E,
"n_steps": n, "horizon": res["H"], "matched_episodes": res["matched"], "ess": res["ess"], "mean_weight": res["mean_weight"],
"max_weight": res["max_weight"], "improvement_wdr": wdr - logged, "fqe_iterations": res["fqe_iterations"], "target_label": t_col}
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"]
w_end = res["weights"]
returns = res["returns"]
prof_series = ["Logged policy"] * E + ["Target policy (weighted)"] * E
cs.publish({
"method": "decide.ope_sequential",
"methodVersion": "1.0.0",
"title": "Sequential off-policy evaluation",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [
{"key": "wdr", "label": "Target policy value (weighted doubly robust)", "value": wdr},
{"key": "ci", "label": f"{pct} CI", "value": [wdr_lo, wdr_hi]},
{"key": "logged", "label": "Logged policy value", "value": logged},
{"key": "ess", "label": "Effective sample size (episodes)", "value": res["ess"]},
],
"tables": [
{"key": "estimates", "title": "Estimated value of the target policy (per episode)",
"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": "Episodes", "value": E}, {"metric": "Decisions", "value": n}, {"metric": "Longest episode (steps)", "value": res["H"]},
{"metric": "Episodes where the target agrees with every logged action", "value": res["matched"]},
{"metric": "Effective sample size (episodes)", "value": res["ess"]},
{"metric": "Mean episode weight (≈ 1 if propensities are right)", "value": res["mean_weight"]},
{"metric": "Largest episode weight", "value": res["max_weight"]},
{"metric": "FQE iterations", "value": res["fqe_iterations"]}]},
{"key": "steps", "title": "Weights by step",
"columns": [{"key": "t", "label": "Step", "type": "integer"}, {"key": "episodes", "label": "Episodes still going", "type": "integer"},
{"key": "mean_weight", "label": "Mean cumulative weight", "type": "number"}, {"key": "ess", "label": "Effective sample size", "type": "number"}],
"rows": [{"t": s["t"] + 1, "episodes": s["episodes"], "mean_weight": s["mean_weight"], "ess": s["ess"]} for s in res["steps"]]},
],
"warnings": warnings,
"notes": [
f"Per-decision weights 1[target = logged action] / propensity, multiplied along each episode; returns discounted by {gamma:g} per step. "
+ f"FQE: a {'linear model in ' + ', '.join(features) if model == 'linear' else 'mean'} per action, iterated to its fixed point"
+ (f", cross-fitted over {folds} episode folds" if folds > 1 else ", fit on all episodes")
+ f"; {n_boot} bootstrap resamples of episodes (seed {seed}). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).",
],
"values": values,
"charts": [
cs.chart("estimates", "forest", "Estimated value per episode", {
"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("profile", "performance-profile", "Episode returns: logged vs target policy", {
"x": cs.col("Episode return", np.concatenate([returns, returns])),
"weight": cs.col("Weight", np.concatenate([np.ones(E), w_end])),
"series": cs.col("Policy", prof_series, levels=["Logged policy", "Target policy (weighted)"]),
}),
cs.chart("weights", "histogram", "Episode weights (episodes the target policy agrees with)", {"x": cs.col("Weight", w_end[w_end > 0])}),
],
})
The logged corridor policy earned 0.167 per episode. "Always move right" agrees with every logged step in only 3 of 60 episodes, so the effective sample size of episodesEffective sample size of episodes(Σ weights)² / Σ weights² over episodes: about how many equally weighted episodes the importance-weighted estimates are worth. is 2.5.
Importance sampling rests on those few episodes. Fitted Q evaluationFitted Q evaluationRepeats a regression of reward plus the next state's value under the new policy until it settles; start-state values give the estimate. uses every transition instead: it fits a model of the return from each state and action, assuming the new policy from the next step on. The weighted doubly robust estimateWeighted doubly robust estimateAdds weighted corrections to a Q-model's predictions step by step; with self-normalized weights it stays steadier than importance sampling. starts from that model and adds weighted corrections where episodes do match. Here it puts the improvement at 0.542 per episode.
Which estimate do you report?
PredictPredict first
The weights table says the effective sample size is a few episodes out of sixty. Which estimate do you lead with?
Reveal
Weighted doubly robust, with FQE beside it. With so few effective episodes, importance-sampling estimates swing with a single episode. The doubly robust estimate leans on the Q-model when weights are near zero, so it is only as good as that model: when FQE and WDR disagree a lot, say so.
A check you can run
ReflectThe weighted doubly robust estimate says the target policy would earn 0.049 per episode (discount 0.95), 95% CI [-0.038, 0.139], less than the 0.049 the logged policy earned (-0.000), from 60 episodes and 640 decisions. The target policy agrees with every logged action in 60 episodes; the effective sample size of the episode weights is 60.0.
- Target policy value (weighted doubly robust)
- 0.0487
- 95% CI
- [−0.0376, 0.1387]
- Logged policy value
- 0.0487
- Effective sample size (episodes)
- 60
Plots
View data
| Value | Upper | Estimator | Lower |
|---|---|---|---|
| 0.0487 | 0.1387 | Trajectory IS | −0.0376 |
| 0.0487 | 0.1387 | Per-decision IS | −0.0376 |
| 0.0487 | 0.1387 | Weighted IS | −0.0376 |
| 0.0487 | 0.1387 | Weighted per-decision IS | −0.0376 |
| 0.1233 | 0.1533 | Fitted Q evaluation | 0.0904 |
| 0.0487 | 0.1387 | Doubly robust | −0.0376 |
| 0.0487 | 0.1387 | Weighted doubly robust | −0.0376 |
| 0.0487 | 0.1387 | Logged policy | −0.0376 |
View data
| Policy | Weight | Episode return |
|---|---|---|
| Logged policy | 1 | 0.5883 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.0537 |
| Logged policy | 1 | 0.2937 |
| Logged policy | 1 | 0.5089 |
| Logged policy | 1 | 0.1092 |
| Logged policy | 1 | 0.1675 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.2290 |
| Logged policy | 1 | 0.2937 |
| Logged policy | 1 | 0.1675 |
| Logged policy | 1 | 0.2290 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.0010 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.5089 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.5089 |
| Logged policy | 1 | 0.4334 |
| Logged policy | 1 | 0.1092 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.0010 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.2937 |
| Logged policy | 1 | 0.5089 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.5883 |
| Logged policy | 1 | 0.1675 |
| Logged policy | 1 | 0.2937 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.2290 |
| Logged policy | 1 | 0.5089 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.4334 |
| Logged policy | 1 | 0.1675 |
| Logged policy | 1 | 0.2290 |
| Logged policy | 1 | 0.4334 |
| Logged policy | 1 | 0.2290 |
| Logged policy | 1 | 0.5089 |
| Logged policy | 1 | 0.5883 |
| Logged policy | 1 | 0.2290 |
| Logged policy | 1 | 0.1092 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.2290 |
| Logged policy | 1 | 0.0537 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.4334 |
| Logged policy | 1 | −0.5123 |
| Logged policy | 1 | 0.0537 |
| Logged policy | 1 | 0.4334 |
| Logged policy | 1 | 0.3618 |
| Logged policy | 1 | 0.2937 |
| Logged policy | 1 | 0.2290 |
| Logged policy | 1 | 0.1675 |
| Logged policy | 1 | 0.1675 |
First 60 of 120 rows.
View data
| Weight |
|---|
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
| 1 |
Estimated value of the target policy (per episode)
| Estimator | Estimate | SE | 95% CI low | 95% CI high | vs logged |
|---|---|---|---|---|---|
| Trajectory IS | 0.0487 | 0.0513 | −0.0376 | 0.1387 | 0 |
| Per-decision IS | 0.0487 | 0.0513 | −0.0376 | 0.1387 | −4.857e-17 |
| Weighted IS | 0.0487 | 0.0460 | −0.0376 | 0.1387 | 0 |
| Weighted per-decision IS | 0.0487 | 0.0460 | −0.0376 | 0.1387 | 2.637e-16 |
| Fitted Q evaluation | 0.1233 | 0.0167 | 0.0904 | 0.1533 | 0.0746 |
| Doubly robust | 0.0487 | 0.0513 | −0.0376 | 0.1387 | −1.596e-16 |
| Weighted doubly robust | 0.0487 | 0.0460 | −0.0376 | 0.1387 | −2.359e-16 |
Weight diagnostics
| Diagnostic | Value |
|---|---|
| Episodes | 60 |
| Decisions | 640 |
| Longest episode (steps) | 14 |
| Episodes where the target agrees with every logged action | 60 |
| Effective sample size (episodes) | 60 |
| Mean episode weight (≈ 1 if propensities are right) | 1 |
| Largest episode weight | 1 |
| FQE iterations | 112 |
Weights by step
| Step | Episodes still going | Mean cumulative weight | Effective sample size |
|---|---|---|---|
| 1 | 60 | 1 | 60 |
| 2 | 60 | 1 | 60 |
| 3 | 60 | 1 | 60 |
| 4 | 60 | 1 | 60 |
| 5 | 60 | 1 | 60 |
| 6 | 57 | 1 | 60 |
| 7 | 51 | 1 | 60 |
| 8 | 46 | 1 | 60 |
| 9 | 45 | 1 | 60 |
| 10 | 40 | 1 | 60 |
| 11 | 32 | 1 | 60 |
| 12 | 26 | 1 | 60 |
| 13 | 23 | 1 | 60 |
| 14 | 20 | 1 | 60 |
- 18 of 60 episodes end without done = true (cut short): their returns stop there, and their last step is left out of the Q-model because its next state is unknown.
- Per-decision weights 1[target = logged action] / propensity, multiplied along each episode; returns discounted by 0.95 per step. FQE: a linear model in cell per action, iterated to its fixed point, cross-fitted over 2 episode folds; 200 bootstrap resamples of episodes (seed 42). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).
The exact R script · R R version 4.5.1 (2025-06-13)
# Off-policy evaluation of a sequential policy
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.ope_sequential 1.0.0 · spec 28873157e3adc525
# Dataset: pol_corridor (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_design(), cs_seq_*(): twins of codesplash.decide.ope / sequential (shared-RNG folds and bootstrap)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/pol_corridor.parquet", col_select = c("episode", "step", "cell", "action", "reward", "p_one", "logged_again", "done")))
n_input <- nrow(df)
df[["cell"]] <- factor(df[["cell"]], levels = c("c0", "c1", "c2", "c3", "c4", "c5")) # stored level order
df[["action"]] <- factor(df[["action"]], levels = c("left", "stay", "right")) # stored level order
df[["logged_again"]] <- factor(df[["logged_again"]], levels = c("left", "stay", "right")) # stored level order
df[["done"]] <- factor(df[["done"]], levels = c("false", "true")) # stored level order
df <- df[stats::complete.cases(df[c("episode", "step", "cell", "action", "reward", "p_one", "logged_again", "done")]), , 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("episode", "step", "cell", "action", "reward", "p_one", "logged_again", "done")) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
ep_col <- "episode"
step_col <- "step"
a_col <- "action"
r_col <- "reward"
p_col <- "p_one"
t_col <- "logged_again"
done_col <- "done"
features <- c("cell")
gamma <- as.numeric(0.95)
model <- "linear" # linear | mean
folds <- as.integer(2)
iterations <- as.integer(200)
n_boot <- as.integer(200)
conf <- 0.95
seed <- 42
# Yes/no columns count as 1/0.
as_flag <- function(v) if (is.factor(v)) as.character(v) == "true" else as.numeric(v) != 0
# Rows by episode (first appearance), then step.
ep_keys <- if (is.factor(df[[ep_col]])) as.character(df[[ep_col]]) else as.numeric(df[[ep_col]])
ord <- cs_seq_order(cs_seq_episode_codes(ep_keys), as.numeric(df[[step_col]]))
df <- df[ord, , drop = FALSE]
rownames(df) <- NULL
ep <- cs_seq_episode_codes(ep_keys[ord])
st <- cs_seq_structure(ep, as.numeric(df[[step_col]]), if (!is.null(done_col)) as_flag(df[[done_col]]) else NULL)
lv <- levels(df[[a_col]])
action <- as.character(df[[a_col]])
target <- as.character(df[[t_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as_flag(df[[r_col]])) 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]]))
# %% Checks (same order in both engines)
if (st$duplicates > 0) cs_error("CS_E_INVALID_VALUES", column = step_col, requirement = "unique within each episode", count = st$duplicates)
bad <- sum(propensity <= 0 | propensity > 1)
if (bad > 0) cs_error("CS_E_INVALID_VALUES", column = p_col, requirement = "a probability in (0, 1]", count = bad)
if (st$E < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = ep_col, min = 2, k = st$E)
unknown <- sort(setdiff(unique(target), lv), method = "radix")
if (length(unknown)) cs_error("CS_E_NOT_A_LEVEL", level = unknown[1], column = a_col)
a_idx <- match(action, lv)
pi_idx <- match(target, lv)
x <- if (model == "linear") cs_bandit_design(df, numeric_f, categorical_f) else matrix(1, nrow = nrow(df), ncol = 1)
# %% Estimate
res <- cs_seq_evaluate(st, x, a_idx, pi_idx, reward, propensity, length(lv), gamma, folds, iterations, n_boot, conf, seed, ep)
E <- res$E
n <- res$n
if (st$truncated > 0) {
warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true (cut short): their returns stop there, and their last step is left out of the Q-model because its next state is unknown.", st$truncated, E, done_col))
}
if (res$ess < 0.1 * E) {
warnings <- c(warnings, sprintf("Effective sample size %.1f is under 10%% of the %d episodes: importance-weighted estimates are noisy; prefer the doubly robust or FQE estimate.", res$ess, E))
}
if (res$matched < E) {
warnings <- c(warnings, sprintf("The target policy agrees with every logged action in only %d of %d episodes; the other episodes get weight 0 from that step on.", res$matched, E))
}
if (!res$fqe_converged) {
warnings <- c(warnings, sprintf("Fitted Q evaluation did not settle within %d iterations; raise the iteration limit or lower the discount.", iterations))
}
if (res$missing_support) {
warnings <- c(warnings, "The target policy takes an action at some states that the training episodes never logged; FQE values those actions at 0 there.")
}
# %% Result
lab <- cs_seq_labels()
pct <- sprintf("%.0f%%", conf * 100)
wdr <- res$estimate$wdr
wdr_ci <- res$ci$wdr
logged <- res$logged
gfmt <- format(gamma, digits = 6)
summary <- sprintf(
"The weighted doubly robust estimate says the target policy would earn %.3f per episode (discount %s), %s CI [%.3f, %.3f], %s than the %.3f the logged policy earned (%+.3f), from %s episodes and %s decisions. The target policy agrees with every logged action in %s episodes; the effective sample size of the episode weights is %.1f.",
wdr, gfmt, pct, wdr_ci[1], wdr_ci[2], if (wdr > logged) "more" else "less", logged, wdr - logged, format(E, big.mark = ","),
format(n, big.mark = ","), format(res$matched, 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_episodes = E,
n_steps = n, horizon = res$H, matched_episodes = res$matched, ess = res$ess, mean_weight = res$mean_weight,
max_weight = res$max_weight, improvement_wdr = wdr - logged, fqe_iterations = res$fqe_iterations, target_label = t_col)
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(unlist(lab[res$estimators])), "Logged policy")
w_end <- res$weights
returns <- res$returns
fqe_note <- if (model == "linear") paste("a linear model in", paste(features, collapse = ", ")) else "a mean"
cs_publish(list(
method = "decide.ope_sequential",
methodVersion = "1.0.0",
title = "Sequential off-policy evaluation",
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = summary,
statistics = list(
list(key = "wdr", label = "Target policy value (weighted doubly robust)", value = wdr),
list(key = "ci", label = paste(pct, "CI"), value = wdr_ci),
list(key = "logged", label = "Logged policy value", value = logged),
list(key = "ess", label = "Effective sample size (episodes)", value = res$ess)
),
tables = list(
list(key = "estimates", title = "Estimated value of the target policy (per episode)",
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("Episodes", "Decisions", "Longest episode (steps)", "Episodes where the target agrees with every logged action",
"Effective sample size (episodes)", "Mean episode weight (≈ 1 if propensities are right)",
"Largest episode weight", "FQE iterations"),
value = c(E, n, res$H, res$matched, res$ess, res$mean_weight, res$max_weight, res$fqe_iterations))),
list(key = "steps", title = "Weights by step",
columns = list(list(key = "t", label = "Step", type = "integer"), list(key = "episodes", label = "Episodes still going", type = "integer"),
list(key = "mean_weight", label = "Mean cumulative weight", type = "number"), list(key = "ess", label = "Effective sample size", type = "number")),
rows = data.frame(t = vapply(res$steps, function(s) s$t + 1L, integer(1)), episodes = vapply(res$steps, function(s) as.integer(s$episodes), integer(1)),
mean_weight = vapply(res$steps, function(s) s$mean_weight, numeric(1)), ess = vapply(res$steps, function(s) s$ess, numeric(1))))
),
warnings = warnings,
notes = list(paste0("Per-decision weights 1[target = logged action] / propensity, multiplied along each episode; returns discounted by ", gfmt,
" per step. FQE: ", fqe_note, " per action, iterated to its fixed point",
if (folds > 1) sprintf(", cross-fitted over %d episode folds", folds) else ", fit on all episodes",
sprintf("; %d bootstrap resamples of episodes (seed %s). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).", n_boot, seed))),
values = values,
charts = list(
cs_chart("estimates", "forest", "Estimated value per episode", 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("profile", "performance-profile", "Episode returns: logged vs target policy", list(
x = cs_col("Episode return", c(returns, returns)),
weight = cs_col("Weight", c(rep(1, E), w_end)),
series = cs_col("Policy", c(rep("Logged policy", E), rep("Target policy (weighted)", E)), levels = c("Logged policy", "Target policy (weighted)"))
)),
cs_chart("weights", "histogram", "Episode weights (episodes the target policy agrees with)", list(x = cs_col("Weight", w_end[w_end > 0])))
)
))
The weighted doubly robust estimate says the target policy would earn 0.049 per episode (discount 0.95), 95% CI [-0.038, 0.139], less than the 0.049 the logged policy earned (-0.000), from 60 episodes and 640 decisions. The target policy agrees with every logged action in 60 episodes; the effective sample size of the episode weights is 60.0.
- Target policy value (weighted doubly robust)
- 0.0487
- 95% CI
- [−0.0376, 0.1387]
- Logged policy value
- 0.0487
- Effective sample size (episodes)
- 60
To keep this page light, the plots are shown once, under the R tab.
Estimated value of the target policy (per episode)
| Estimator | Estimate | SE | 95% CI low | 95% CI high | vs logged |
|---|---|---|---|---|---|
| Trajectory IS | 0.0487 | 0.0513 | −0.0376 | 0.1387 | 0 |
| Per-decision IS | 0.0487 | 0.0513 | −0.0376 | 0.1387 | −6.245e-17 |
| Weighted IS | 0.0487 | 0.0460 | −0.0376 | 0.1387 | 0 |
| Weighted per-decision IS | 0.0487 | 0.0460 | −0.0376 | 0.1387 | 2.984e-16 |
| Fitted Q evaluation | 0.1233 | 0.0167 | 0.0904 | 0.1533 | 0.0746 |
| Doubly robust | 0.0487 | 0.0513 | −0.0376 | 0.1387 | −9.021e-17 |
| Weighted doubly robust | 0.0487 | 0.0460 | −0.0376 | 0.1387 | −4.163e-16 |
Weight diagnostics
| Diagnostic | Value |
|---|---|
| Episodes | 60 |
| Decisions | 640 |
| Longest episode (steps) | 14 |
| Episodes where the target agrees with every logged action | 60 |
| Effective sample size (episodes) | 60 |
| Mean episode weight (≈ 1 if propensities are right) | 1 |
| Largest episode weight | 1 |
| FQE iterations | 112 |
Weights by step
| Step | Episodes still going | Mean cumulative weight | Effective sample size |
|---|---|---|---|
| 1 | 60 | 1 | 60 |
| 2 | 60 | 1 | 60 |
| 3 | 60 | 1 | 60 |
| 4 | 60 | 1 | 60 |
| 5 | 60 | 1 | 60 |
| 6 | 57 | 1 | 60 |
| 7 | 51 | 1 | 60 |
| 8 | 46 | 1 | 60 |
| 9 | 45 | 1 | 60 |
| 10 | 40 | 1 | 60 |
| 11 | 32 | 1 | 60 |
| 12 | 26 | 1 | 60 |
| 13 | 23 | 1 | 60 |
| 14 | 20 | 1 | 60 |
- 18 of 60 episodes end without done = true (cut short): their returns stop there, and their last step is left out of the Q-model because its next state is unknown.
- Per-decision weights 1[target = logged action] / propensity, multiplied along each episode; returns discounted by 0.95 per step. FQE: a linear model in cell per action, iterated to its fixed point, cross-fitted over 2 episode folds; 200 bootstrap resamples of episodes (seed 42). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Off-policy evaluation of a sequential policy
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.ope_sequential 1.0.0 · spec 28873157e3adc525
# Dataset: pol_corridor (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, sequential as seq # twins of codesplashr::cs_bandit_design / cs_seq_* (shared-RNG folds and bootstrap)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_corridor.parquet", columns=["episode", "step", "cell", "action", "reward", "p_one", "logged_again", "done"])
n_input = len(df)
df["cell"] = pd.Categorical(df["cell"], categories=["c0", "c1", "c2", "c3", "c4", "c5"]) # stored level order
df["action"] = pd.Categorical(df["action"], categories=["left", "stay", "right"]) # stored level order
df["logged_again"] = pd.Categorical(df["logged_again"], categories=["left", "stay", "right"]) # stored level order
df["done"] = pd.Categorical(df["done"], categories=["false", "true"]) # stored level order
df = df.dropna(subset=["episode", "step", "cell", "action", "reward", "p_one", "logged_again", "done"]) # listwise deletion over the analysis columns
df["cell"] = df["cell"].cat.remove_unused_categories()
df["action"] = df["action"].cat.remove_unused_categories()
df["logged_again"] = df["logged_again"].cat.remove_unused_categories()
df["done"] = df["done"].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, ["episode", "step", "cell", "action", "reward", "p_one", "logged_again", "done"]) # infinite values stop the run (registry/errors.yaml)
# %% Inputs
ep_col, step_col, a_col, r_col, p_col, t_col = "episode", "step", "action", "reward", "p_one", "logged_again"
done_col = "done"
features = ["cell"]
gamma = float(0.95)
model = "linear" # linear | mean
folds = int(2)
iterations = int(200)
n_boot = int(200)
conf = 0.95
seed = 42
def as_flag(s):
"""Yes/no columns count as 1/0."""
return (s.astype(str) == "true").to_numpy() if isinstance(s.dtype, pd.CategoricalDtype) else (s.to_numpy(dtype=float) != 0)
# Rows by episode (first appearance), then step.
ep_keys = df[ep_col].astype(str).tolist() if isinstance(df[ep_col].dtype, pd.CategoricalDtype) else df[ep_col].to_numpy(dtype=float).tolist()
order = seq.order_rows(seq.episode_codes(ep_keys), df[step_col].to_numpy(dtype=float))
df = df.iloc[order].reset_index(drop=True)
ep_keys = [ep_keys[i] for i in order]
ep = seq.episode_codes(ep_keys)
st = seq.structure(ep, df[step_col].to_numpy(dtype=float), as_flag(df[done_col]) if done_col else None)
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()
reward = as_flag(df[r_col]).astype(float) 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)}
# %% Checks (same order in both engines)
if st["duplicates"]:
cs.cs_error("CS_E_INVALID_VALUES", column=step_col, requirement="unique within each episode", count=st["duplicates"])
bad = int(np.sum((propensity <= 0) | (propensity > 1)))
if bad:
cs.cs_error("CS_E_INVALID_VALUES", column=p_col, requirement="a probability in (0, 1]", count=bad)
if st["E"] < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=ep_col, min=2, k=st["E"])
unknown = sorted(set(target) - set(levels))
if unknown:
cs.cs_error("CS_E_NOT_A_LEVEL", level=unknown[0], column=a_col)
col_of = {lv: j for j, lv in enumerate(levels)}
a_idx = np.array([col_of[a] for a in action], dtype=np.int64)
pi_idx = np.array([col_of[a] for a in target], dtype=np.int64)
x = ope.design(df, numeric, categorical) if model == "linear" else np.ones((len(df), 1))
# %% Estimate
res = seq.evaluate(st, x, a_idx, pi_idx, reward, propensity, len(levels), gamma, folds, iterations, n_boot, conf, seed, ep)
E, n = res["E"], res["n"]
if st["truncated"]:
warnings.append(f"{st['truncated']} of {E} episodes end without {done_col} = true (cut short): their returns stop there, and their last step is left out of the Q-model because its next state is unknown.")
if res["ess"] < 0.1 * E:
warnings.append(f"Effective sample size {res['ess']:.1f} is under 10% of the {E} episodes: importance-weighted estimates are noisy; prefer the doubly robust or FQE estimate.")
if res["matched"] < E:
warnings.append(f"The target policy agrees with every logged action in only {res['matched']} of {E} episodes; the other episodes get weight 0 from that step on.")
if not res["fqe_converged"]:
warnings.append(f"Fitted Q evaluation did not settle within {iterations} iterations; raise the iteration limit or lower the discount.")
if res["missing_support"]:
warnings.append("The target policy takes an action at some states that the training episodes never logged; FQE values those actions at 0 there.")
# %% Result
lab = seq.LABELS
pct = f"{conf:.0%}"
wdr, (wdr_lo, wdr_hi) = res["estimate"]["wdr"], res["ci"]["wdr"]
logged = res["logged"]
direction = "more" if wdr > logged else "less"
summary = (
f"The weighted doubly robust estimate says the target policy would earn {wdr:.3f} per episode (discount {gamma:g}), {pct} CI [{wdr_lo:.3f}, {wdr_hi:.3f}], "
f"{direction} than the {logged:.3f} the logged policy earned ({wdr - logged:+.3f}), from {E:,} episodes and {n:,} decisions. "
f"The target policy agrees with every logged action in {res['matched']:,} episodes; the effective sample size of the episode weights is {res['ess']:.1f}."
)
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_episodes": E,
"n_steps": n, "horizon": res["H"], "matched_episodes": res["matched"], "ess": res["ess"], "mean_weight": res["mean_weight"],
"max_weight": res["max_weight"], "improvement_wdr": wdr - logged, "fqe_iterations": res["fqe_iterations"], "target_label": t_col}
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"]
w_end = res["weights"]
returns = res["returns"]
prof_series = ["Logged policy"] * E + ["Target policy (weighted)"] * E
cs.publish({
"method": "decide.ope_sequential",
"methodVersion": "1.0.0",
"title": "Sequential off-policy evaluation",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [
{"key": "wdr", "label": "Target policy value (weighted doubly robust)", "value": wdr},
{"key": "ci", "label": f"{pct} CI", "value": [wdr_lo, wdr_hi]},
{"key": "logged", "label": "Logged policy value", "value": logged},
{"key": "ess", "label": "Effective sample size (episodes)", "value": res["ess"]},
],
"tables": [
{"key": "estimates", "title": "Estimated value of the target policy (per episode)",
"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": "Episodes", "value": E}, {"metric": "Decisions", "value": n}, {"metric": "Longest episode (steps)", "value": res["H"]},
{"metric": "Episodes where the target agrees with every logged action", "value": res["matched"]},
{"metric": "Effective sample size (episodes)", "value": res["ess"]},
{"metric": "Mean episode weight (≈ 1 if propensities are right)", "value": res["mean_weight"]},
{"metric": "Largest episode weight", "value": res["max_weight"]},
{"metric": "FQE iterations", "value": res["fqe_iterations"]}]},
{"key": "steps", "title": "Weights by step",
"columns": [{"key": "t", "label": "Step", "type": "integer"}, {"key": "episodes", "label": "Episodes still going", "type": "integer"},
{"key": "mean_weight", "label": "Mean cumulative weight", "type": "number"}, {"key": "ess", "label": "Effective sample size", "type": "number"}],
"rows": [{"t": s["t"] + 1, "episodes": s["episodes"], "mean_weight": s["mean_weight"], "ess": s["ess"]} for s in res["steps"]]},
],
"warnings": warnings,
"notes": [
f"Per-decision weights 1[target = logged action] / propensity, multiplied along each episode; returns discounted by {gamma:g} per step. "
+ f"FQE: a {'linear model in ' + ', '.join(features) if model == 'linear' else 'mean'} per action, iterated to its fixed point"
+ (f", cross-fitted over {folds} episode folds" if folds > 1 else ", fit on all episodes")
+ f"; {n_boot} bootstrap resamples of episodes (seed {seed}). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).",
],
"values": values,
"charts": [
cs.chart("estimates", "forest", "Estimated value per episode", {
"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("profile", "performance-profile", "Episode returns: logged vs target policy", {
"x": cs.col("Episode return", np.concatenate([returns, returns])),
"weight": cs.col("Weight", np.concatenate([np.ones(E), w_end])),
"series": cs.col("Policy", prof_series, levels=["Logged policy", "Target policy (weighted)"]),
}),
cs.chart("weights", "histogram", "Episode weights (episodes the target policy agrees with)", {"x": cs.col("Weight", w_end[w_end > 0])}),
],
})
Here the "new" policy repeats the logged actions and every propensity is 1, so every weight is 1. Every importance-weighted and doubly robust estimate equals the logged return, 0.0487. CodeSplash runs this identity as a test, in Python and R.
Check your understanding
CheckpointCheck yourself
Why does fitted Q evaluation still give an answer when no episode matches the new policy all the way?
Show the answer
Answer: b
FQE chains one-step regressions, so partial agreement is enough. The price is model error: a linear Q-model that is wrong biases the estimate.
Check yourself
Some episodes stop at a time limit without ending (done is false on their last row). What does the method do with that last step?
Show the answer
Answer: b
Treating a cut-short step as an ending would teach the Q-model that the episode stops there, pulling values toward 0.
Try it
In the appIn the Policy learning studio, choose a dataset of logged episodes, then Evaluate. You need the episode, the step, the state, the logged action with its propensity, the reward and the action your new policy would take at each logged state.
import numpy as np
import pandas as pd
df = pd.read_csv("episodes.csv").sort_values(["episode", "step"])
match = (df["action"] == df["target"]).to_numpy()
df["w"] = match / df["propensity"]
df["W"] = df.groupby("episode")["w"].cumprod()
gamma = 0.95
df["disc"] = gamma ** df.groupby("episode").cumcount()
pdis = (df["disc"] * df["W"] * df["reward"]).groupby(df["episode"]).sum().mean()
w_end = df.groupby("episode")["W"].last()
ess = w_end.sum() ** 2 / (w_end**2).sum()
print(round(pdis, 4), round(ess, 1))df <- read.csv("episodes.csv", check.names = FALSE)
df <- df[order(df$episode, df$step), ]
df$w <- (df$action == df$target) / df$propensity
df$W <- ave(df$w, df$episode, FUN = cumprod)
gamma <- 0.95
df$disc <- gamma^(ave(df$step, df$episode, FUN = seq_along) - 1)
pdis <- mean(tapply(df$disc * df$W * df$reward, df$episode, sum))
w_end <- tapply(df$W, df$episode, function(x) x[length(x)])
ess <- sum(w_end)^2 / sum(w_end^2)
round(c(pdis = pdis, ess = ess), 4)Recap
Recap- Over episodes, importance weights multiply step by step and drop to 0 after the first disagreement.
- The effective sample size of episodes says how many episodes the weighted estimates really rest on.
- Fitted Q evaluation uses every transition but depends on its Q-model; weighted doubly robust combines both and is the usual headline.
- Off-policy estimates screen policies; a live test or a simulated environment confirms them.
Concepts in this lesson