Skip to content

DDecisions · decide.ope_sequential

Off-policy evaluation of a sequential policy

How much would a new policy have earned per episode, judged only from episodes logged under the current one?

Estimates the discounted return per episode that a new (target) policy would earn from logged episodes — states, actions, rewards and the logging policy's probability of each logged action — before running it. Trajectory and per-decision importance sampling, their weighted (self-normalized) forms, fitted Q evaluation (a linear Q-model per action, cross-fitted over episode folds), and the doubly robust and weighted doubly robust estimators, with episode-bootstrap intervals from a shared seeded stream and weight diagnostics by step.

Verified in Python and R Python and R agree to 6 decimals Seeded

A real result

Example “Corridor rule”, recorded in both engines. In the app, “Try this example” loads it into Analyze.

Sequential off-policy evaluationRecorded · Python and R agreeRecorded 2026-11-21 · 41 values compared
R

The weighted doubly robust estimate says the target policy would earn 0.214 per episode (discount 0.95), 95% CI [0.178, 0.296], more than the 0.049 the logged policy earned (+0.165), from 60 episodes and 640 decisions. The target policy agrees with every logged action in 0 episodes; the effective sample size of the episode weights is 0.0.

Target policy value (weighted doubly robust)
0.2141
95% CI
[0.1784, 0.2958]
Logged policy value
0.0487
Effective sample size (episodes)
0

Plots

Estimated value per episodeHow large are several estimates, how precise, and which exclude the null?
View data
ValueUpperEstimatorLower
00Trajectory IS0
−0.0399−0.0250Per-decision IS−0.0580
——Weighted IS—
−0.1426−0.0500Weighted per-decision IS−0.1426
0.30520.3363Fitted Q evaluation0.2740
0.28270.3191Doubly robust0.2436
0.21410.2958Weighted doubly robust0.1784
0.04870.1377Logged policy−0.0414
Episode returns: logged vs target policyHow often does each policy beat a given return, across the whole distribution of episodes rather than just the mean?
View data
PolicyWeightEpisode return
Logged policy10.5883
Logged policy1−0.5123
Logged policy10.0537
Logged policy10.2937
Logged policy10.5089
Logged policy10.1092
Logged policy10.1675
Logged policy1−0.5123
Logged policy1−0.5123
Logged policy10.2290
Logged policy10.2937
Logged policy10.1675
Logged policy10.2290
Logged policy1−0.5123
Logged policy10.0010
Logged policy1−0.5123
Logged policy10.5089
Logged policy1−0.5123
Logged policy10.5089
Logged policy10.4334
Logged policy10.1092
Logged policy1−0.5123
Logged policy10.0010
Logged policy1−0.5123
Logged policy10.2937
Logged policy10.5089
Logged policy1−0.5123
Logged policy1−0.5123
Logged policy1−0.5123
Logged policy10.5883
Logged policy10.1675
Logged policy10.2937
Logged policy1−0.5123
Logged policy10.2290
Logged policy10.5089
Logged policy1−0.5123
Logged policy10.4334
Logged policy10.1675
Logged policy10.2290
Logged policy10.4334
Logged policy10.2290
Logged policy10.5089
Logged policy10.5883
Logged policy10.2290
Logged policy10.1092
Logged policy1−0.5123
Logged policy10.2290
Logged policy10.0537
Logged policy1−0.5123
Logged policy1−0.5123
Logged policy1−0.5123
Logged policy10.4334
Logged policy1−0.5123
Logged policy10.0537
Logged policy10.4334
Logged policy10.3618
Logged policy10.2937
Logged policy10.2290
Logged policy10.1675
Logged policy10.1675

First 60 of 120 rows.

Episode weights (episodes the target policy agrees with)How is one numeric variable distributed?
View data
Weight

Estimated value of the target policy (per episode)

EstimatorEstimateSE95% CI low95% CI highvs logged
Trajectory IS0000−0.0487
Per-decision IS−0.03990.0084−0.0580−0.0250−0.0886
Weighted IS—————
Weighted per-decision IS−0.14260.0340−0.1426−0.0500−0.1913
Fitted Q evaluation0.30520.01550.27400.33630.2565
Doubly robust0.28270.01960.24360.31910.2340
Weighted doubly robust0.21410.03030.17840.29580.1654

Weight diagnostics

DiagnosticValue
Episodes60
Decisions640
Longest episode (steps)14
Episodes where the target agrees with every logged action0
Effective sample size (episodes)0
Mean episode weight (≈ 1 if propensities are right)0
Largest episode weight0
FQE iterations76

Weights by step

StepEpisodes still goingMean cumulative weightEffective sample size
1600.690518.086
2600.06802
3600.04861
46000
56000
65700
75100
84600
94500
104000
113200
122600
132300
142000
  • 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.
  • Effective sample size 0.0 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 0 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 0.95 per step. FQE: a linear model in cell, weather today per action, iterated to its fixed point, cross-fitted over 2 episode folds; 300 bootstrap resamples of episodes (seed 42). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).
Python

The weighted doubly robust estimate says the target policy would earn 0.214 per episode (discount 0.95), 95% CI [0.178, 0.296], more than the 0.049 the logged policy earned (+0.165), from 60 episodes and 640 decisions. The target policy agrees with every logged action in 0 episodes; the effective sample size of the episode weights is 0.0.

Target policy value (weighted doubly robust)
0.2141
95% CI
[0.1784, 0.2958]
Logged policy value
0.0487
Effective sample size (episodes)
0

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

Estimated value of the target policy (per episode)

EstimatorEstimateSE95% CI low95% CI highvs logged
Trajectory IS0000−0.0487
Per-decision IS−0.03990.0084−0.0580−0.0250−0.0886
Weighted IS—————
Weighted per-decision IS−0.14260.0340−0.1426−0.0500−0.1913
Fitted Q evaluation0.30520.01550.27400.33630.2565
Doubly robust0.28270.01960.24360.31910.2340
Weighted doubly robust0.21410.03030.17840.29580.1654

Weight diagnostics

DiagnosticValue
Episodes60
Decisions640
Longest episode (steps)14
Episodes where the target agrees with every logged action0
Effective sample size (episodes)0
Mean episode weight (≈ 1 if propensities are right)0
Largest episode weight0
FQE iterations76

Weights by step

StepEpisodes still goingMean cumulative weightEffective sample size
1600.690518.086
2600.06802
3600.04861
46000
56000
65700
75100
84600
94500
104000
113200
122600
132300
142000
  • 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.
  • Effective sample size 0.0 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 0 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 0.95 per step. FQE: a linear model in cell, weather today per action, iterated to its fixed point, cross-fitted over 2 episode folds; 300 bootstrap resamples of episodes (seed 42). Shorter episodes continue in an absorbing state (weight unchanged, reward 0).

Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.

Worked examples in the app

  • Corridor rulepol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step · target: rule
  • Corridor always right numericpol_corridor · action: action · episode: episode · propensity: propensity · reward: reward · state: position, weather today · step: step · target: always_right
  • Corridor mean modelpol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell · step: step · target: rule
  • Inventory base stockpol_inventory · action: order · episode: store week · propensity: p_logged · reward: profit · state: stock · step: week · target: base_stock
  • On policy identitypol_corridor · action: action · done: done · episode: episode · propensity: p_one · reward: reward · state: cell · step: step · target: logged_again
  • Degenerate constantpol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step · target: rule
  • Degenerate n1pol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step · target: rule
  • Degenerate infpol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step · target: rule

In the guides

Where it sits in the decision guides

  • Reinforcement learning (bandits, RL) · DS & ML Decision Guide · Optimize / decide
  • Prescriptive analytics (simulation, OR, causal RL) · DS & ML Decision Guide · Optimize / decide

What you need

Episodecategorical / numeric · 1 column
Which episode (customer journey, session, patient course) each decision belongs to.
Stepnumeric · 1 column
The order of decisions within an episode (1, 2, 3 …); the next state is the next row of the same episode.
State featuresnumeric / categorical / boolean · 1–50 columns
What was known when each decision was made; the Q-model for fitted Q evaluation uses them.
Logged actioncategorical / boolean · 1 column · 2–50 levels
The action the logging (current) policy took at each step.
Rewardnumeric / boolean · 1 column
The reward right after each decision (yes/no counts as 1/0).
Logging propensitynumeric · 1 column
The logging policy's probability of the logged action at that step (0 < p ≤ 1).
Target policy's actioncategorical / boolean · 1 column
The action the new policy would take at each logged state (same labels as the logged action).
Episode endedboolean / numeric · 0–1 column
Optional: yes on the step that ended the episode. Without it, the last row of each episode ends it.

Choices you make

options

Discount per stepdefault 0.95

How much a reward one step later counts (1 = an undiscounted episode total).

Q-model (FQE, DR)default linear

The model of future reward that fitted Q evaluation and the doubly robust estimators use.

  • Linear in the state features (per action)(default) — Fits a linear Q-model for each action; a categorical state alone gives one value per state and action.
  • Mean per action — Ignores the state: each action's value is a single number. Use it when episodes are few.
Cross-fitting foldsdefault 2

Episodes are split into folds; each episode's Q-values come from a model fit on the other folds (1 = in-sample).

FQE iteration limitdefault 200

Fitted Q evaluation repeats its regression until the coefficients stop changing or this many times.

statistics

Bootstrap resamplesdefault 1000

Resamples of whole episodes for the intervals. More gives steadier intervals but takes longer.

Confidence leveldefault 0.95

How sure the intervals should be: 0.95 gives 95% confidence intervals.

What it reports

value[is]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
value[pdis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
value[wis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
value[wpdis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
value[fqe]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
value[dr]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
value[wdr]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
se[is]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
se[pdis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
se[wis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
se[wpdis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
se[fqe]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
se[dr]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
se[wdr]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_low[is]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_low[pdis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_low[wis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_low[wpdis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_low[fqe]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_low[dr]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_low[wdr]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_high[is]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_high[pdis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_high[wis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_high[wpdis]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_high[fqe]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_high[dr]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
ci_high[wdr]
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
logged_value
The average discounted return the logged episodes actually earned: the bar a new policy has to beat.
logged_ci_low
The average discounted return the logged episodes actually earned: the bar a new policy has to beat.
logged_ci_high
The average discounted return the logged episodes actually earned: the bar a new policy has to beat.
n_episodes
How many episodes and decisions the estimate rests on, and the longest episode; intervals resample whole episodes.
n_steps
How many episodes and decisions the estimate rests on, and the longest episode; intervals resample whole episodes.
horizon
How many episodes and decisions the estimate rests on, and the longest episode; intervals resample whole episodes.
matched_episodes
Weights 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.
ess
(Σ weights)² / Σ weights² over episodes: about how many equally weighted episodes the importance-weighted estimates are worth.
mean_weight
Weights 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.
max_weight
Weights 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.
improvement_wdr
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.
fqe_iterations
Repeats a regression of reward plus the next state's value under the new policy until it settles; start-state values give the estimate.
target_label
Estimates a new policy's return per episode from episodes logged under another policy, before anyone runs the new one.

Python and R

Python and R agree to 6 decimals (relative tolerance 1e-8). Python uses numpy, pandas, codesplash; R uses stats, nanoparquet, codesplashr.

Default traps between the two languages

  • Fitted Q evaluation iterates ridge-stabilized normal equations solved with LAPACK in both engines; the iteration contracts, so rounding differences stay near 1e-13.
Python

The exact script CodeSplash ran for example “Corridor rule” · 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 ffc82845252b4af0
# 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", "weather today", "action", "reward", "propensity", "rule", "done"])
n_input = len(df)
df["cell"] = pd.Categorical(df["cell"], categories=["c0", "c1", "c2", "c3", "c4", "c5"])  # stored level order
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["rule"] = pd.Categorical(df["rule"], categories=["right", "stay"])  # stored level order
df["done"] = pd.Categorical(df["done"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "rule", "done"])  # listwise deletion over the analysis columns
df["cell"] = df["cell"].cat.remove_unused_categories()
df["weather today"] = df["weather today"].cat.remove_unused_categories()
df["action"] = df["action"].cat.remove_unused_categories()
df["rule"] = df["rule"].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", "weather today", "action", "reward", "propensity", "rule", "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", "propensity", "rule"
done_col = "done"
features = ["cell", "weather today"]
gamma = float(0.95)
model = "linear"  # linear | mean
folds = int(2)
iterations = int(200)
n_boot = int(300)
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])}),
    ],
})
R

The exact script CodeSplash ran for example “Corridor rule” · 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 ffc82845252b4af0
# 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", "weather today", "action", "reward", "propensity", "rule", "done")))
n_input <- nrow(df)
df[["cell"]] <- factor(df[["cell"]], levels = c("c0", "c1", "c2", "c3", "c4", "c5"))  # stored level order
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[["rule"]] <- factor(df[["rule"]], levels = c("right", "stay"))  # 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", "weather today", "action", "reward", "propensity", "rule", "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", "weather today", "action", "reward", "propensity", "rule", "done"))  # 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 <- "rule"
done_col <- "done"
features <- c("cell", "weather today")
gamma <- as.numeric(0.95)
model <- "linear" # linear | mean
folds <- as.integer(2)
iterations <- as.integer(200)
n_boot <- as.integer(300)
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])))
  )
))

Sources

  • Precup, D., Sutton, R. S., & Singh, S. (2000). Eligibility traces for off-policy policy evaluation. ICML, 759–766.
  • Jiang, N., & Li, L. (2016). Doubly robust off-policy value evaluation for reinforcement learning. ICML, 652–661.
  • Thomas, P., & Brunskill, E. (2016). Data-efficient off-policy policy evaluation for reinforcement learning. ICML, 2139–2148.
  • Le, H., Voloshin, C., & Yue, Y. (2019). Batch policy learning under constraints. ICML, 3703–3712 (fitted Q evaluation).
  • Voloshin, C., Le, H. M., Jiang, N., & Yue, Y. (2021). Empirical study of off-policy policy evaluation for reinforcement learning. NeurIPS Datasets and Benchmarks.

From the CodeSplash method registry · decide.ope_sequential v1.0.0.