Skip to content

DDecisions · decide.trajectories

Logged episodes

What do the logged episodes look like, and can they support judging a new policy?

Describes logged episodes before a policy is learned or evaluated from them — one row per decision, with the episode, the step within it, the state, the action taken, its reward and, when logged, the probability the logging policy gave that action. Counts episodes and their lengths, averages the discounted return per episode, tabulates the actions, checks the logging probabilities, and groups rows by state to show where some action was never tried (where a new policy that prefers it can't be judged from these logs).

Verified in Python and R Python and R agree to 10 decimals

A real result

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

Logged episodesRecorded · Python and R agreeRecorded 2026-11-21 · 24 values compared
R

60 episodes hold 640 decisions, 10.7 per episode on average; the average discounted return is 0.049. 100% of the judged decisions fall in state groups where every action was tried. The smallest logging probability is 0.100; 0.0% of decisions had one under 0.05.

Episodes
60
Decisions
640
Average discounted return
0.0487
Decisions where every action was tried
100.0%

Plots

Decisions per episodeHow is one numeric variable distributed?
View data
Decisions per episode
5
14
13
9
6
12
11
14
14
10
9
11
10
14
14
14
6
14
6
7
12
14
14
14
9
6
14
14
14
5
11
9
14
10
6
14
7
11
10
7
10
6
5
10
12
14
10
13
14
14
14
7
14
13
7
8
9
10
11
11
Discounted return per episode (γ = 0.95)How is one numeric variable distributed?
View data
Discounted return
0.5883
−0.5123
0.0537
0.2937
0.5089
0.1092
0.1675
−0.5123
−0.5123
0.2290
0.2937
0.1675
0.2290
−0.5123
0.0010
−0.5123
0.5089
−0.5123
0.5089
0.4334
0.1092
−0.5123
0.0010
−0.5123
0.2937
0.5089
−0.5123
−0.5123
−0.5123
0.5883
0.1675
0.2937
−0.5123
0.2290
0.5089
−0.5123
0.4334
0.1675
0.2290
0.4334
0.2290
0.5089
0.5883
0.2290
0.1092
−0.5123
0.2290
0.0537
−0.5123
−0.5123
−0.5123
0.4334
−0.5123
0.0537
0.4334
0.3618
0.2937
0.2290
0.1675
0.1675
Actions loggedHow often does each category occur?
View data
action
right
right
right
right
right
left
stay
left
right
right
stay
stay
right
right
stay
right
left
right
right
left
right
stay
right
right
stay
stay
right
left
stay
right
stay
right
right
left
right
right
right
right
stay
stay
right
right
right
right
right
right
right
right
right
right
right
right
stay
right
right
right
left
right
right
left

First 60 of 640 rows.

Assumptions

  • Episodes are in order — Each step appears once per episode.
  • Logging probabilities — The smallest logging probability is 0.100.
  • Every action tried — 100% of the judged decisions fall in state groups where every action was tried; 0 of 12 groups miss at least one action.

Episodes

SummaryValue
Episodes60
Decisions640
Decisions per episode (mean)10.667
Decisions per episode (median)11
Shortest episode5
Longest episode14
Discounted return (mean, γ = 0.95)0.0487
Discounted return (SD)0.3972
Reward per decision (mean)0.0156

Actions logged

actionDecisionsShareMean rewardMean logging probabilityJudged groups never trying it
left10816.9%−0.05000.23150
stay12219.1%−0.05000.20000
right41064.1%0.05240.63270

State groups where some action was never tried

State groupDecisionsActions triedNever tried

Groups with at least 10 decisions; numeric state columns are cut into at most 4 groups each. Largest groups first (up to 50).

Logging probabilities

SummaryValue
Smallest0.1000
Median0.5000
Largest0.7000
Share under 0.050
Outside (0, 1]0
  • 18 of 60 episodes end without done = true; Learn and Evaluate treat each as ending at its last row.
  • Rows ordered by episode (first appearance), then step. Returns are discounted by 0.95 per step from each episode's first decision. State groups: cell, weather today; a group is judged once it has 10 decisions.
Python

60 episodes hold 640 decisions, 10.7 per episode on average; the average discounted return is 0.049. 100% of the judged decisions fall in state groups where every action was tried. The smallest logging probability is 0.100; 0.0% of decisions had one under 0.05.

Episodes
60
Decisions
640
Average discounted return
0.0487
Decisions where every action was tried
100.0%

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

Assumptions

  • Episodes are in order — Each step appears once per episode.
  • Logging probabilities — The smallest logging probability is 0.100.
  • Every action tried — 100% of the judged decisions fall in state groups where every action was tried; 0 of 12 groups miss at least one action.

Episodes

SummaryValue
Episodes60
Decisions640
Decisions per episode (mean)10.667
Decisions per episode (median)11
Shortest episode5
Longest episode14
Discounted return (mean, γ = 0.95)0.0487
Discounted return (SD)0.3972
Reward per decision (mean)0.0156

Actions logged

actionDecisionsShareMean rewardMean logging probabilityJudged groups never trying it
left10816.9%−0.05000.23150
stay12219.1%−0.05000.20000
right41064.1%0.05240.63270

State groups where some action was never tried

State groupDecisionsActions triedNever tried

Groups with at least 10 decisions; numeric state columns are cut into at most 4 groups each. Largest groups first (up to 50).

Logging probabilities

SummaryValue
Smallest0.1000
Median0.5000
Largest0.7000
Share under 0.050
Outside (0, 1]0
  • 18 of 60 episodes end without done = true; Learn and Evaluate treat each as ending at its last row.
  • Rows ordered by episode (first appearance), then step. Returns are discounted by 0.95 per step from each episode's first decision. State groups: cell, weather today; a group is judged once it has 10 decisions.

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 donepol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step
  • Corridor numeric statepol_corridor · action: action · episode: episode · propensity: propensity · reward: reward · state: position, weather today · step: step
  • Corridor no propensitypol_corridor · action: action · episode: episode · reward: reward · state: cell · step: step
  • Inventorypol_inventory · action: order · episode: store week · propensity: p_logged · reward: profit · state: stock · step: week
  • Deterministic loggingpol_corridor · action: rule · done: done · episode: episode · propensity: p_one · reward: reward · state: cell, weather today · step: step
  • Degenerate all napol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step
  • Degenerate empty after filterpol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step
  • Degenerate infpol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step

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 …); rows are put in this order before anything is counted.
State featuresnumeric / categorical / boolean · 1–50 columns
What was known when each decision was made; rows are grouped by them to check that every action was tried.
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 · 0–1 column
Optional: the logging policy's probability of the logged action at that step (0 < p ≤ 1). Evaluate needs it.
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 in an episode's return (1 = the plain total).

Groups per numeric state columndefault 4

Numeric state columns are cut at data values into at most this many groups for the support check (1 = ignore them).

Decisions to judge a state groupdefault 10

A state group is judged only once it has this many decisions; smaller groups are left out of the support check.

statistics

Small logging probabilitydefault 0.05

Logging probabilities under this value are flagged: their importance weights are large, so a few episodes can dominate.

Checks and remedies

CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.

  • Episodes are in order

    Each step value appears once per episode, and an episode's end flag is on its last row.

  • Logging probabilities

    Recorded, between 0 and 1, and not too small. Off-policy evaluation divides by them.

  • Every action tried

    In each judged state group, every action was taken at least once (passes at 90% of decisions or more).

What it reports

n_episodes
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
n_steps
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
mean_length
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
median_length
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
min_length
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
max_length
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
mean_return
An episode's rewards added up with later ones counted less: r₁ + γr₂ + γ²r₃ … for a discount γ between 0 and 1.
sd_return
An episode's rewards added up with later ones counted less: r₁ + γr₂ + γ²r₃ … for a discount γ between 0 and 1.
min_return
An episode's rewards added up with later ones counted less: r₁ + γr₂ + γ²r₃ … for a discount γ between 0 and 1.
max_return
An episode's rewards added up with later ones counted less: r₁ + γr₂ + γ²r₃ … for a discount γ between 0 and 1.
mean_reward
An episode's rewards added up with later ones counted less: r₁ + γr₂ + γ²r₃ … for a discount γ between 0 and 1.
duplicate_steps
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
n_groups
Whether every action was taken at least sometimes in each kind of situation; logs can only judge actions they contain.
n_judged_groups
Whether every action was taken at least sometimes in each kind of situation; logs can only judge actions they contain.
n_unsupported_groups
Whether every action was taken at least sometimes in each kind of situation; logs can only judge actions they contain.
support_share
Whether every action was taken at least sometimes in each kind of situation; logs can only judge actions they contain.
n_actions
Whether every action was taken at least sometimes in each kind of situation; logs can only judge actions they contain.
truncated_episodes
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
early_done_episodes
One run of decisions from start to end (a journey, a course of treatment), recorded as one row per decision in step order.
min_propensity
The probability the logging policy gave the action it took. Off-policy estimates divide by it, so tiny values give huge weights.
median_propensity
The probability the logging policy gave the action it took. Off-policy estimates divide by it, so tiny values give huge weights.
max_propensity
The probability the logging policy gave the action it took. Off-policy estimates divide by it, so tiny values give huge weights.
share_low_propensity
The probability the logging policy gave the action it took. Off-policy estimates divide by it, so tiny values give huge weights.
invalid_propensity
The probability the logging policy gave the action it took. Off-policy estimates divide by it, so tiny values give huge weights.

Python and R

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

Default traps between the two languages

  • Counting and averaging only; numeric state groups are cut at data values (order statistics), so no interpolation differs between engines.
Python

The exact script CodeSplash ran for example “Corridor done” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0

# Logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.trajectories 1.0.0 · spec e642cf16864dcda7
# 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 trajectories as tj  # twin of codesplashr::cs_trajectories (counting and averaging only)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/pol_corridor.parquet", columns=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "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["done"] = pd.Categorical(df["done"], categories=["false", "true"])  # stored level order
df = df.dropna(subset=["episode", "step", "cell", "weather today", "action", "reward", "propensity", "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["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", "done"])  # infinite values stop the run (registry/errors.yaml)

# %% Inputs
ep_col, step_col, a_col, r_col = "episode", "step", "action", "reward"
p_col = "propensity"  # optional: the logging probability of each logged action
done_col = "done"  # optional: true on the step that ended the episode
states = ["cell", "weather today"]
gamma = float(0.95)
bins = int(4)
min_cell = int(10)
low = float(0.05)


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)


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()
levels = [str(x) for x in df[a_col].cat.categories]
action = df[a_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)
groups = tj.state_groups(
    [(c, df[c].astype(str).tolist() if isinstance(df[c].dtype, pd.CategoricalDtype) else df[c].to_numpy(dtype=float), isinstance(df[c].dtype, pd.CategoricalDtype)) for c in states],
    bins,
)

# %% Summarize
res = tj.summarize(
    ep_keys, df[step_col].to_numpy(dtype=float), action, levels, reward, groups,
    propensity=df[p_col].to_numpy(dtype=float) if p_col else None,
    done=as_flag(df[done_col]) if done_col else None,
    gamma=gamma, low=low, min_cell=min_cell,
)
E, n = res["n_episodes"], res["n_steps"]
if len(levels) < 2:
    warnings.append(f"Only one action appears in {a_col}: a policy learned from these logs can only copy it, and no other action can be judged.")
if res["max_length"] == 1:
    warnings.append("Every episode has one decision: this is a one-step (bandit) problem, and the Decisions studio's off-policy evaluation fits it better.")
if res["duplicate_steps"]:
    warnings.append(f"{res['duplicate_steps']} step value(s) repeat within an episode; Learn and Evaluate stop until each step is unique within its episode.")
if res["truncated_episodes"]:
    warnings.append(f"{res['truncated_episodes']} of {E} episodes end without {done_col} = true; Learn and Evaluate treat each as ending at its last row.")
if res["early_done_episodes"]:
    warnings.append(f"{res['early_done_episodes']} episode(s) mark {done_col} = true before their last row; the rows after it are still counted here.")

# %% Checks
assumptions = []
order_ok = res["duplicate_steps"] == 0 and not res["early_done_episodes"]
assumptions.append({
    "key": "episode_order", "label": "Episodes are in order",
    "status": "pass" if order_ok else "warn",
    "detail": "Each step appears once per episode." if order_ok else
              f"{res['duplicate_steps']} repeated step value(s); {res['early_done_episodes'] or 0} episode(s) end before their last row.",
})
if not p_col:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "info",
                        "detail": "Not recorded. Learn can still run, but Evaluate and the doubly robust values need the logging probability of each action."})
elif res["invalid_propensity"]:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "fail",
                        "detail": f"{res['invalid_propensity']} decision(s) have a logging probability outside (0, 1].", "statistic": res["invalid_propensity"]})
elif res["share_low_propensity"] > 0:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "warn",
                        "detail": f"{res['share_low_propensity']:.1%} of decisions had a logging probability under {low:g} (smallest {res['min_propensity']:.3f}): a few episodes can dominate off-policy estimates.",
                        "statistic": res["min_propensity"]})
else:
    assumptions.append({"key": "propensity", "label": "Logging probabilities", "status": "pass",
                        "detail": f"The smallest logging probability is {res['min_propensity']:.3f}.", "statistic": res["min_propensity"]})
if res["support_share"] is None:
    assumptions.append({"key": "support", "label": "Every action tried", "status": "info",
                        "detail": f"No state group has {min_cell} decisions yet, so support can't be judged."})
else:
    ok = res["support_share"] >= 0.9
    assumptions.append({"key": "support", "label": "Every action tried", "status": "pass" if ok else "warn",
                        "detail": f"{res['support_share']:.0%} of the judged decisions fall in state groups where every action was tried; "
                                  f"{res['n_unsupported_groups']} of {res['n_judged_groups']} groups miss at least one action.",
                        "statistic": res["support_share"]})

# %% Result
summary = (
    f"{E:,} episodes hold {n:,} decisions, {res['mean_length']:.1f} per episode on average; the average discounted return is {res['mean_return']:.3f}. "
    + (f"{res['support_share']:.0%} of the judged decisions fall in state groups where every action was tried."
       if res["support_share"] is not None else f"No state group has {min_cell} decisions yet, so support can't be judged.")
    + (f" The smallest logging probability is {res['min_propensity']:.3f}; {res['share_low_propensity']:.1%} of decisions had one under {low:g}." if p_col else "")
)
values = {k: res[k] for k in ["n_episodes", "n_steps", "mean_length", "median_length", "min_length", "max_length", "mean_return", "sd_return",
                              "min_return", "max_return", "mean_reward", "duplicate_steps", "n_groups", "n_judged_groups", "n_unsupported_groups",
                              "support_share"]}
values["n_actions"] = len(levels)
# Without an end flag or logging probabilities these keys are null (nothing to count).
for k in ["truncated_episodes", "early_done_episodes", "min_propensity", "median_propensity", "max_propensity", "share_low_propensity", "invalid_propensity"]:
    values[k] = res[k]
metric_rows = [
    {"metric": "Episodes", "value": E},
    {"metric": "Decisions", "value": n},
    {"metric": "Decisions per episode (mean)", "value": res["mean_length"]},
    {"metric": "Decisions per episode (median)", "value": res["median_length"]},
    {"metric": "Shortest episode", "value": res["min_length"]},
    {"metric": "Longest episode", "value": res["max_length"]},
    {"metric": f"Discounted return (mean, γ = {gamma:g})", "value": res["mean_return"]},
    {"metric": "Discounted return (SD)", "value": res["sd_return"]},
    {"metric": "Reward per decision (mean)", "value": res["mean_reward"]},
]
action_cols = [{"key": "action", "label": a_col, "type": "string"}, {"key": "rows", "label": "Decisions", "type": "integer"},
               {"key": "share", "label": "Share", "type": "percent"}, {"key": "mean_reward", "label": "Mean reward", "type": "number"}]
if p_col:
    action_cols.append({"key": "mean_propensity", "label": "Mean logging probability", "type": "number"})
action_cols.append({"key": "groups_missing", "label": "Judged groups never trying it", "type": "integer"})
tables = [
    {"key": "episodes", "title": "Episodes",
     "columns": [{"key": "metric", "label": "Summary", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
     "rows": metric_rows},
    {"key": "actions", "title": "Actions logged",
     "columns": action_cols,
     "rows": [{k: a[k] for k in [c["key"] for c in action_cols]} for a in res["actions"]]},
    {"key": "support", "title": "State groups where some action was never tried",
     "columns": [{"key": "group", "label": "State group", "type": "string"}, {"key": "rows", "label": "Decisions", "type": "integer"},
                 {"key": "seen", "label": "Actions tried", "type": "integer"}, {"key": "missing", "label": "Never tried", "type": "string"}],
     "rows": res["unsupported"],
     "note": f"Groups with at least {min_cell} decisions; numeric state columns are cut into at most {bins} groups each. Largest groups first (up to 50)."},
]
if p_col:
    tables.append({"key": "propensity", "title": "Logging probabilities",
                   "columns": [{"key": "metric", "label": "Summary", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
                   "rows": [{"metric": "Smallest", "value": res["min_propensity"]}, {"metric": "Median", "value": res["median_propensity"]},
                            {"metric": "Largest", "value": res["max_propensity"]}, {"metric": f"Share under {low:g}", "value": res["share_low_propensity"]},
                            {"metric": "Outside (0, 1]", "value": res["invalid_propensity"]}]})
cs.publish({
    "method": "decide.trajectories",
    "methodVersion": "1.0.0",
    "title": "Logged episodes",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": n,
    "summary": summary,
    "statistics": [
        {"key": "episodes", "label": "Episodes", "value": E, "format": "integer"},
        {"key": "decisions", "label": "Decisions", "value": n, "format": "integer"},
        {"key": "mean_return", "label": "Average discounted return", "value": res["mean_return"]},
        {"key": "support", "label": "Decisions where every action was tried", "value": res["support_share"], "format": "percent"},
    ],
    "tables": tables,
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [
        f"Rows ordered by {ep_col} (first appearance), then {step_col}. Returns are discounted by {gamma:g} per step from each episode's first decision. "
        f"State groups: {', '.join(states)}; a group is judged once it has {min_cell} decisions.",
    ],
    "values": values,
    "charts": [
        cs.chart("lengths", "histogram", "Decisions per episode", {"x": cs.col("Decisions per episode", res["lengths"].astype(float))}),
        cs.chart("returns", "histogram", f"Discounted return per episode (γ = {gamma:g})", {"x": cs.col("Discounted return", res["returns"])}),
        cs.chart("actions", "bar", "Actions logged", {"x": cs.col(a_col, list(action), levels=levels)}),
    ],
})
R

The exact script CodeSplash ran for example “Corridor done” · R version 4.5.1 (2025-06-13)

# Logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.trajectories 1.0.0 · spec e642cf16864dcda7
# 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_trajectories(): twin of codesplash.decide.trajectories (counting and averaging only)

# %% 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", "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[["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", "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", "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" # optional: the logging probability of each logged action
done_col <- "done" # optional: true on the step that ended the episode
states <- c("cell", "weather today")
gamma <- as.numeric(0.95)
bins <- as.integer(4)
min_cell <- as.integer(10)
low <- as.numeric(0.05)

# Yes/no columns count as 1/0.
as_flag <- function(v) if (is.factor(v)) as.character(v) == "true" else as.numeric(v) != 0

ep_keys <- if (is.factor(df[[ep_col]])) as.character(df[[ep_col]]) else as.numeric(df[[ep_col]])
lv <- levels(df[[a_col]])
action <- as.character(df[[a_col]])
reward <- if (is.factor(df[[r_col]])) as.numeric(as_flag(df[[r_col]])) else as.numeric(df[[r_col]])
groups <- cs_trajectories_groups(lapply(states, function(c) {
  v <- df[[c]]
  list(name = c, values = if (is.factor(v)) as.character(v) else as.numeric(v), categorical = is.factor(v))
}), bins)

# %% Summarize
res <- cs_trajectories(ep_keys, as.numeric(df[[step_col]]), action, lv, reward, groups,
                       propensity = if (!is.null(p_col)) as.numeric(df[[p_col]]) else NULL,
                       done = if (!is.null(done_col)) as_flag(df[[done_col]]) else NULL,
                       gamma = gamma, low = low, min_cell = min_cell)
E <- res$n_episodes
n <- res$n_steps
if (length(lv) < 2) {
  warnings <- c(warnings, sprintf("Only one action appears in %s: a policy learned from these logs can only copy it, and no other action can be judged.", a_col))
}
if (res$max_length == 1) {
  warnings <- c(warnings, "Every episode has one decision: this is a one-step (bandit) problem, and the Decisions studio's off-policy evaluation fits it better.")
}
if (res$duplicate_steps > 0) {
  warnings <- c(warnings, sprintf("%d step value(s) repeat within an episode; Learn and Evaluate stop until each step is unique within its episode.", res$duplicate_steps))
}
if (!is.null(res$truncated_episodes) && res$truncated_episodes > 0) {
  warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true; Learn and Evaluate treat each as ending at its last row.", res$truncated_episodes, E, done_col))
}
if (!is.null(res$early_done_episodes) && res$early_done_episodes > 0) {
  warnings <- c(warnings, sprintf("%d episode(s) mark %s = true before their last row; the rows after it are still counted here.", res$early_done_episodes, done_col))
}

# %% Checks
early <- if (is.null(res$early_done_episodes)) 0L else res$early_done_episodes
order_ok <- res$duplicate_steps == 0 && early == 0
assumptions <- list(list(
  key = "episode_order", label = "Episodes are in order", status = if (order_ok) "pass" else "warn",
  detail = if (order_ok) "Each step appears once per episode." else sprintf("%d repeated step value(s); %d episode(s) end before their last row.", res$duplicate_steps, early)
))
pct1 <- function(x) sprintf("%.1f%%", 100 * x)
pct0 <- function(x) sprintf("%.0f%%", 100 * x)
assumptions[[2]] <- if (is.null(p_col)) {
  list(key = "propensity", label = "Logging probabilities", status = "info",
       detail = "Not recorded. Learn can still run, but Evaluate and the doubly robust values need the logging probability of each action.")
} else if (res$invalid_propensity > 0) {
  list(key = "propensity", label = "Logging probabilities", status = "fail",
       detail = sprintf("%d decision(s) have a logging probability outside (0, 1].", res$invalid_propensity), statistic = res$invalid_propensity)
} else if (res$share_low_propensity > 0) {
  list(key = "propensity", label = "Logging probabilities", status = "warn",
       detail = sprintf("%s of decisions had a logging probability under %s (smallest %.3f): a few episodes can dominate off-policy estimates.",
                        pct1(res$share_low_propensity), sprintf("%g", low), res$min_propensity),
       statistic = res$min_propensity)
} else {
  list(key = "propensity", label = "Logging probabilities", status = "pass",
       detail = sprintf("The smallest logging probability is %.3f.", res$min_propensity), statistic = res$min_propensity)
}
assumptions[[3]] <- if (is.null(res$support_share)) {
  list(key = "support", label = "Every action tried", status = "info",
       detail = sprintf("No state group has %d decisions yet, so support can't be judged.", min_cell))
} else {
  list(key = "support", label = "Every action tried", status = if (res$support_share >= 0.9) "pass" else "warn",
       detail = sprintf("%s of the judged decisions fall in state groups where every action was tried; %d of %d groups miss at least one action.",
                        pct0(res$support_share), res$n_unsupported_groups, res$n_judged_groups),
       statistic = res$support_share)
}

# %% Result
summary <- paste0(
  sprintf("%s episodes hold %s decisions, %.1f per episode on average; the average discounted return is %.3f. ",
          format(E, big.mark = ","), format(n, big.mark = ","), res$mean_length, res$mean_return),
  if (!is.null(res$support_share)) sprintf("%s of the judged decisions fall in state groups where every action was tried.", pct0(res$support_share))
  else sprintf("No state group has %d decisions yet, so support can't be judged.", min_cell),
  if (!is.null(p_col)) sprintf(" The smallest logging probability is %.3f; %s of decisions had one under %s.", res$min_propensity,
                               pct1(res$share_low_propensity), sprintf("%g", low)) else ""
)
keys <- c("n_episodes", "n_steps", "mean_length", "median_length", "min_length", "max_length", "mean_return", "sd_return",
          "min_return", "max_return", "mean_reward", "duplicate_steps", "n_groups", "n_judged_groups", "n_unsupported_groups", "support_share")
values <- stats::setNames(lapply(keys, function(k) res[[k]]), keys)
values$n_actions <- length(lv)
# Without an end flag or logging probabilities these keys are null (nothing to count).
for (k in c("truncated_episodes", "early_done_episodes", "min_propensity", "median_propensity", "max_propensity", "share_low_propensity",
            "invalid_propensity")) values[k] <- list(res[[k]])
na_null <- function(x) if (is.null(x)) NA_real_ else x
metric_rows <- data.frame(
  metric = c("Episodes", "Decisions", "Decisions per episode (mean)", "Decisions per episode (median)", "Shortest episode", "Longest episode",
             sprintf("Discounted return (mean, γ = %s)", sprintf("%g", gamma)), "Discounted return (SD)", "Reward per decision (mean)"),
  value = c(E, n, res$mean_length, res$median_length, res$min_length, res$max_length, res$mean_return, na_null(res$sd_return), res$mean_reward)
)
action_cols <- list(list(key = "action", label = a_col, type = "string"), list(key = "rows", label = "Decisions", type = "integer"),
                    list(key = "share", label = "Share", type = "percent"), list(key = "mean_reward", label = "Mean reward", type = "number"))
if (!is.null(p_col)) action_cols[[length(action_cols) + 1]] <- list(key = "mean_propensity", label = "Mean logging probability", type = "number")
action_cols[[length(action_cols) + 1]] <- list(key = "groups_missing", label = "Judged groups never trying it", type = "integer")
action_keys <- vapply(action_cols, function(c) c$key, character(1))
action_rows <- lapply(res$actions, function(a) stats::setNames(lapply(action_keys, function(k) a[[k]]), action_keys))
tables <- list(
  list(key = "episodes", title = "Episodes",
       columns = list(list(key = "metric", label = "Summary", type = "string"), list(key = "value", label = "Value", type = "number")),
       rows = metric_rows),
  list(key = "actions", title = "Actions logged", columns = action_cols, rows = action_rows),
  list(key = "support", title = "State groups where some action was never tried",
       columns = list(list(key = "group", label = "State group", type = "string"), list(key = "rows", label = "Decisions", type = "integer"),
                      list(key = "seen", label = "Actions tried", type = "integer"), list(key = "missing", label = "Never tried", type = "string")),
       rows = res$unsupported,
       note = sprintf("Groups with at least %d decisions; numeric state columns are cut into at most %d groups each. Largest groups first (up to 50).", min_cell, bins))
)
if (!is.null(p_col)) {
  tables[[length(tables) + 1]] <- list(
    key = "propensity", title = "Logging probabilities",
    columns = list(list(key = "metric", label = "Summary", type = "string"), list(key = "value", label = "Value", type = "number")),
    rows = data.frame(metric = c("Smallest", "Median", "Largest", sprintf("Share under %s", sprintf("%g", low)), "Outside (0, 1]"),
                      value = c(res$min_propensity, res$median_propensity, res$max_propensity, res$share_low_propensity, res$invalid_propensity))
  )
}
cs_publish(list(
  method = "decide.trajectories",
  methodVersion = "1.0.0",
  title = "Logged episodes",
  engine = cs_engine_info("stats", "codesplashr"),
  n = n,
  summary = summary,
  statistics = list(
    list(key = "episodes", label = "Episodes", value = E, format = "integer"),
    list(key = "decisions", label = "Decisions", value = n, format = "integer"),
    list(key = "mean_return", label = "Average discounted return", value = res$mean_return),
    list(key = "support", label = "Decisions where every action was tried", value = res$support_share, format = "percent")
  ),
  tables = tables,
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Rows ordered by %s (first appearance), then %s. Returns are discounted by %s per step from each episode's first decision. State groups: %s; a group is judged once it has %d decisions.",
                       ep_col, step_col, sprintf("%g", gamma), paste(states, collapse = ", "), min_cell)),
  values = values,
  charts = list(
    cs_chart("lengths", "histogram", "Decisions per episode", list(x = cs_col("Decisions per episode", as.numeric(res$lengths)))),
    cs_chart("returns", "histogram", sprintf("Discounted return per episode (γ = %s)", sprintf("%g", gamma)), list(x = cs_col("Discounted return", res$returns))),
    cs_chart("actions", "bar", "Actions logged", list(x = cs_col(a_col, action, levels = lv)))
  )
))

Sources

  • Levine, S., Kumar, A., Tucker, G., & Fu, J. (2020). Offline reinforcement learning: Tutorial, review, and perspectives on open problems. arXiv:2005.01643.
  • 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.trajectories v1.0.0.