DDecisions · decide.offline_rl
Offline policy learning from logged episodes
Which decision policy does the logged data support, and how much better would it do than the current one?
Learns a decision policy from logged episodes without trying anything new: fitted Q iteration (a linear Q-model per action), behavior cloning (imitates the logged actions), conservative Q-learning (CQL, a neural Q-network kept close to the logged actions) or implicit Q-learning (IQL, expectile values and an advantage-weighted policy). Every run is checked against a behavior-cloning baseline and evaluated with fitted Q evaluation — plus weighted doubly robust and per-decision importance sampling when the logging propensities are known — with episode-bootstrap intervals, a support guard and the learned action per state.
A real result
Example “Corridor fqi tabular”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Fitted Q iteration learned a policy from 60 episodes (640 decisions). Fitted Q evaluation puts its return per episode at 0.511, 95% CI [0.494, 0.529], against 0.049 for the logged policy (discount 0.95). It agrees with the logged action at 64% of the logged states.
- Learned policy value (FQE)
- 0.5107
- 95% CI
- [0.4940, 0.5289]
- Logged policy value
- 0.0487
- Agreement with logged actions
- 0.6406
Plots
View data
| Value | Upper | Policy and estimator | Lower |
|---|---|---|---|
| 0.5107 | 0.5289 | Fitted Q iteration · Fitted Q evaluation | 0.4940 |
| 0.5323 | 0.5866 | Fitted Q iteration · Weighted doubly robust | 0.4717 |
| 0.5185 | 0.6622 | Fitted Q iteration · Weighted per-decision IS | −0.2262 |
| 0.5107 | 0.5289 | Behavior cloning (baseline) · Fitted Q evaluation | 0.4940 |
| 0.5323 | 0.5866 | Behavior cloning (baseline) · Weighted doubly robust | 0.4717 |
| 0.5185 | 0.6622 | Behavior cloning (baseline) · Weighted per-decision IS | −0.2262 |
| 0.0487 | 0.1387 | Logged policy · Observed return | −0.0376 |
View data
| Iteration | Estimated value |
|---|---|
| 1 | −0.0404 |
| 2 | −0.0736 |
| 3 | −0.1034 |
| 4 | −0.0104 |
| 5 | 0.1554 |
| 6 | 0.3249 |
| 7 | 0.4345 |
| 8 | 0.4823 |
| 9 | 0.5001 |
| 10 | 0.5067 |
| 11 | 0.5094 |
| 12 | 0.5107 |
| 13 | 0.5113 |
| 14 | 0.5117 |
| 15 | 0.5118 |
| 16 | 0.5119 |
| 17 | 0.5120 |
| 18 | 0.5120 |
| 19 | 0.5120 |
| 20 | 0.5120 |
| 21 | 0.5120 |
| 22 | 0.5120 |
| 23 | 0.5120 |
| 24 | 0.5120 |
| 25 | 0.5120 |
| 26 | 0.5120 |
| 27 | 0.5120 |
| 28 | 0.5120 |
| 29 | 0.5120 |
| 30 | 0.5120 |
| 31 | 0.5120 |
| 32 | 0.5120 |
| 33 | 0.5120 |
| 34 | 0.5120 |
| 35 | 0.5120 |
| 36 | 0.5120 |
| 37 | 0.5120 |
View data
| Action | Share | Policy |
|---|---|---|
| left | 0.1688 | Logged |
| stay | 0.1906 | Logged |
| right | 0.6406 | Logged |
| left | 0 | Learned |
| stay | 0 | Learned |
| right | 1 | Learned |
Estimated return per episode
| Policy | Estimator | Estimate | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Fitted Q iteration | Fitted Q evaluation | 0.5107 | 0.4940 | 0.5289 |
| Fitted Q iteration | Weighted doubly robust | 0.5323 | 0.4717 | 0.5866 |
| Fitted Q iteration | Weighted per-decision IS | 0.5185 | −0.2262 | 0.6622 |
| Behavior cloning (baseline) | Fitted Q evaluation | 0.5107 | 0.4940 | 0.5289 |
| Behavior cloning (baseline) | Weighted doubly robust | 0.5323 | 0.4717 | 0.5866 |
| Behavior cloning (baseline) | Weighted per-decision IS | 0.5185 | −0.2262 | 0.6622 |
| Logged policy | Observed return | 0.0487 | −0.0376 | 0.1387 |
Learned policy by state (12 of 12 distinct states)
| cell | weather today | Learned action | Q(left) | Q(stay) | Q(right) |
|---|---|---|---|---|---|
| c1 | sun | right | 0.3494 | 0.4398 | 0.5287 |
| c2 | sun | right | 0.4448 | 0.5278 | 0.6198 |
| c3 | rain | right | 0.5220 | 0.6187 | 0.6798 |
| c4 | rain | right | 0.6164 | 0.7227 | 0.7901 |
| c5 | rain | right | 0.7310 | 0.8331 | 0.9077 |
| c1 | rain | right | 0.3447 | 0.4361 | 0.4884 |
| c0 | sun | right | 0.3653 | 0.3605 | 0.4423 |
| c3 | sun | right | 0.5267 | 0.6224 | 0.7202 |
| c2 | rain | right | 0.4401 | 0.5241 | 0.5794 |
| c4 | sun | right | 0.6211 | 0.7263 | 0.8305 |
| c5 | sun | right | 0.7357 | 0.8367 | 0.9480 |
| c0 | rain | right | 0.3606 | 0.3568 | 0.4019 |
Actions: logged vs learned policy
| action | Logged share | Learned share |
|---|---|---|
| left | 16.9% | 0.0% |
| stay | 19.1% | 0.0% |
| right | 64.1% | 100.0% |
Training by iteration
| Iteration | Loss | Estimated start-state value |
|---|---|---|
| 1 | 0.0104 | −0.0404 |
| 2 | 0.0085 | −0.0736 |
| 3 | 0.0063 | −0.1034 |
| 4 | 0.0053 | −0.0104 |
| 5 | 0.0046 | 0.1554 |
| 6 | 0.0037 | 0.3249 |
| 7 | 0.0025 | 0.4345 |
| 8 | 0.0015 | 0.4823 |
| 9 | 0.0011 | 0.5001 |
| 10 | 0.0009 | 0.5067 |
| 11 | 0.0009 | 0.5094 |
| 12 | 0.0009 | 0.5107 |
| 13 | 0.0009 | 0.5113 |
| 14 | 0.0009 | 0.5117 |
| 15 | 0.0008 | 0.5118 |
| 16 | 0.0008 | 0.5119 |
| 17 | 0.0008 | 0.5120 |
| 18 | 0.0008 | 0.5120 |
| 19 | 0.0008 | 0.5120 |
| 20 | 0.0008 | 0.5120 |
| 21 | 0.0008 | 0.5120 |
| 22 | 0.0008 | 0.5120 |
| 23 | 0.0008 | 0.5120 |
| 24 | 0.0008 | 0.5120 |
| 25 | 0.0008 | 0.5120 |
| 26 | 0.0008 | 0.5120 |
| 27 | 0.0008 | 0.5120 |
| 28 | 0.0008 | 0.5120 |
| 29 | 0.0008 | 0.5120 |
| 30 | 0.0008 | 0.5120 |
| 31 | 0.0008 | 0.5120 |
| 32 | 0.0008 | 0.5120 |
| 33 | 0.0008 | 0.5120 |
| 34 | 0.0008 | 0.5120 |
| 35 | 0.0008 | 0.5120 |
| 36 | 0.0008 | 0.5120 |
| 37 | 0.0008 | 0.5120 |
- 18 of 60 episodes end without done = true (cut short): their last step is left out of the Q-models because its next state is unknown.
- Effective sample size 2.5 of 60 episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.
- The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.
- Fitted Q iteration; discount 0.95; Q-models and evaluation use cell, weather today. Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds), weighted doubly robust and weighted per-decision IS with the logged propensities; 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
Fitted Q iteration learned a policy from 60 episodes (640 decisions). Fitted Q evaluation puts its return per episode at 0.511, 95% CI [0.494, 0.529], against 0.049 for the logged policy (discount 0.95). It agrees with the logged action at 64% of the logged states.
- Learned policy value (FQE)
- 0.5107
- 95% CI
- [0.4940, 0.5289]
- Logged policy value
- 0.0487
- Agreement with logged actions
- 0.6406
To keep this page light, the plots are shown once, under the R tab.
Estimated return per episode
| Policy | Estimator | Estimate | 95% CI low | 95% CI high |
|---|---|---|---|---|
| Fitted Q iteration | Fitted Q evaluation | 0.5107 | 0.4940 | 0.5289 |
| Fitted Q iteration | Weighted doubly robust | 0.5323 | 0.4717 | 0.5866 |
| Fitted Q iteration | Weighted per-decision IS | 0.5185 | −0.2262 | 0.6622 |
| Behavior cloning (baseline) | Fitted Q evaluation | 0.5107 | 0.4940 | 0.5289 |
| Behavior cloning (baseline) | Weighted doubly robust | 0.5323 | 0.4717 | 0.5866 |
| Behavior cloning (baseline) | Weighted per-decision IS | 0.5185 | −0.2262 | 0.6622 |
| Logged policy | Observed return | 0.0487 | −0.0376 | 0.1387 |
Learned policy by state (12 of 12 distinct states)
| cell | weather today | Learned action | Q(left) | Q(stay) | Q(right) |
|---|---|---|---|---|---|
| c1 | sun | right | 0.3494 | 0.4398 | 0.5287 |
| c2 | sun | right | 0.4448 | 0.5278 | 0.6198 |
| c3 | rain | right | 0.5220 | 0.6187 | 0.6798 |
| c4 | rain | right | 0.6164 | 0.7227 | 0.7901 |
| c5 | rain | right | 0.7310 | 0.8331 | 0.9077 |
| c1 | rain | right | 0.3447 | 0.4361 | 0.4884 |
| c0 | sun | right | 0.3653 | 0.3605 | 0.4423 |
| c3 | sun | right | 0.5267 | 0.6224 | 0.7202 |
| c2 | rain | right | 0.4401 | 0.5241 | 0.5794 |
| c4 | sun | right | 0.6211 | 0.7263 | 0.8305 |
| c5 | sun | right | 0.7357 | 0.8367 | 0.9480 |
| c0 | rain | right | 0.3606 | 0.3568 | 0.4019 |
Actions: logged vs learned policy
| action | Logged share | Learned share |
|---|---|---|
| left | 16.9% | 0.0% |
| stay | 19.1% | 0.0% |
| right | 64.1% | 100.0% |
Training by iteration
| Iteration | Loss | Estimated start-state value |
|---|---|---|
| 1 | 0.0104 | −0.0404 |
| 2 | 0.0085 | −0.0736 |
| 3 | 0.0063 | −0.1034 |
| 4 | 0.0053 | −0.0104 |
| 5 | 0.0046 | 0.1554 |
| 6 | 0.0037 | 0.3249 |
| 7 | 0.0025 | 0.4345 |
| 8 | 0.0015 | 0.4823 |
| 9 | 0.0011 | 0.5001 |
| 10 | 0.0009 | 0.5067 |
| 11 | 0.0009 | 0.5094 |
| 12 | 0.0009 | 0.5107 |
| 13 | 0.0009 | 0.5113 |
| 14 | 0.0009 | 0.5117 |
| 15 | 0.0008 | 0.5118 |
| 16 | 0.0008 | 0.5119 |
| 17 | 0.0008 | 0.5120 |
| 18 | 0.0008 | 0.5120 |
| 19 | 0.0008 | 0.5120 |
| 20 | 0.0008 | 0.5120 |
| 21 | 0.0008 | 0.5120 |
| 22 | 0.0008 | 0.5120 |
| 23 | 0.0008 | 0.5120 |
| 24 | 0.0008 | 0.5120 |
| 25 | 0.0008 | 0.5120 |
| 26 | 0.0008 | 0.5120 |
| 27 | 0.0008 | 0.5120 |
| 28 | 0.0008 | 0.5120 |
| 29 | 0.0008 | 0.5120 |
| 30 | 0.0008 | 0.5120 |
| 31 | 0.0008 | 0.5120 |
| 32 | 0.0008 | 0.5120 |
| 33 | 0.0008 | 0.5120 |
| 34 | 0.0008 | 0.5120 |
| 35 | 0.0008 | 0.5120 |
| 36 | 0.0008 | 0.5120 |
| 37 | 0.0008 | 0.5120 |
- 18 of 60 episodes end without done = true (cut short): their last step is left out of the Q-models because its next state is unknown.
- Effective sample size 2.5 of 60 episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.
- The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.
- Fitted Q iteration; discount 0.95; Q-models and evaluation use cell, weather today. Evaluation: fitted Q evaluation (linear per action, cross-fitted over 2 episode folds), weighted doubly robust and weighted per-decision IS with the logged propensities; 200 bootstrap resamples of episodes (seed 42). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.
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 fqi tabularpol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step
- Corridor bc numericpol_corridor · action: action · done: done · episode: episode · reward: reward · state: position, weather today · step: step
- Inventory fqipol_inventory · action: order · episode: store week · propensity: p_logged · reward: profit · state: stock · step: week
- Corridor cqlpol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step
- Corridor cql dueling singlepol_corridor · action: action · done: done · episode: episode · reward: reward · state: position, weather today · step: step
- Inventory iqlpol_inventory · action: order · episode: store week · propensity: p_logged · reward: profit · state: stock · step: week
- Degenerate constantpol_corridor · action: action · done: done · episode: episode · propensity: propensity · reward: reward · state: cell, weather today · step: step
- Degenerate n1pol_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 …); 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 learned policy picks an action from these.
- 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 (0 < p ≤ 1). With it, the evaluation adds importance-weighted estimates.
- 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
- Algorithmdefault fqi
How the policy is learned from the logged episodes.
- Fitted Q iteration (linear)(default) — Repeats a per-action linear regression of reward plus the best next value; transparent, fast and exact for a categorical state.
- Behavior cloning — Learns to copy the logged actions: a baseline that can't beat the logging policy by much, but rarely does worse.
- Conservative Q-learning (neural) — A Q-network with a penalty that keeps values low for actions the logging policy rarely took.
- Implicit Q-learning (neural) — Learns values only from logged actions (expectile regression), then weights the logged actions by their advantage.
- Discount per stepdefault 0.95
How much a reward one step later counts; lower values care more about the next few steps.
- FQI iteration limitdefault 300
Fitted Q iteration repeats its regression until the coefficients stop changing or this many times.
model
- Target updates (rounds)default 20
How many times the network's targets are recomputed; each round trains for the set number of epochs.
- Hidden layers (units)default 32,32
Units in each hidden layer of the Q, value and policy networks, input side first.
- Epochs per rounddefault 20
Training passes over the transitions in each round (the IQL policy trains for five times as many).
- Learning ratedefault 0.005
Adam's step size.
- Batch sizedefault 256
Transitions per gradient step; batches follow a seeded shuffle each epoch (the same in Python and R).
- Conservatism (α)default 1
Weight of the penalty that pushes down Q for actions the logging policy rarely took (0 = plain fitted Q).
- Double Q targetsdefault on
Picks the next action with the current network and values it with the previous one, which curbs overestimation.
- Dueling headdefault off
Splits the network's output into a state value and mean-centered action advantages.
- Expectile (τ)default 0.7
How optimistic the value is about the logged actions: 0.5 averages them, values near 1 approach the best one.
- Advantage temperature (β)default 3
How strongly the policy favors high-advantage logged actions (0 = behavior cloning); weights are capped at 100.
statistics
- Evaluation foldsdefault 2
Episodes are split into folds; each episode's evaluation Q-values come from a model fit on the other folds (1 = in-sample).
- FQE iteration limitdefault 200
Fitted Q evaluation of each policy repeats its regression until the coefficients stop changing or this many times.
- 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.
Advanced
- Optimizerdefault default
How the weights are updated. The method's own choice is the usual one.
- Method's own(default) — Adam or AdamW, as the method describes; the usual choice.
- Adam — Adam without decoupled weight decay (an AdamW method's weight decay is then not applied).
- AdamW — Adam with decoupled weight decay; on an Adam method it adds decay 0.01 on weight matrices.
- SGD with momentum — Plain gradient steps with momentum 0.9; often needs a larger learning rate and a schedule.
- Learning-rate scheduledefault none
How the learning rate changes over training.
- Constant(default) — The same learning rate every epoch (the method's default).
- Cosine — Falls smoothly from the learning rate toward 0 over the epochs.
- Step — Divides the learning rate by 10 after each third of the epochs.
- One cycle — Rises from a 25th of the learning rate to the full rate over the first 30% of steps, then falls far below it.
- Reduce on plateau — Divides the learning rate by 10 after 10 epochs without improvement in the validation loss.
- Warm-up epochsdefault 0
Epochs at the start that ramp the learning rate up linearly; 0 = no warm-up.
- Gradient clippingdefault 0
Largest gradient size (L2 norm over all weights) before a step; larger gradients are scaled down. 0 = off.
- Weight average (EMA)default 0
Keeps a moving average of the weights (for example 0.99) and uses it for validation and the result. 0 = off.
- Weight average from epoch (SWA)default 0
Averages the weights at the end of every epoch from this one on and returns the average. 0 = off; not with EMA.
- Record every stepdefault off
Saves the loss, learning rate and gradient size after every batch in the training history, not only per epoch.
- Compute profiledefault parity
Where and how precisely the network trains. Parity matches the other engine; the faster profiles can give slightly different numbers.
- Parity(default) — Double precision on one CPU thread: the same numbers in Python and R, run after run (the default).
- Faster CPU — Single precision on all performance cores; repeatable on this Mac, results differ slightly from Parity.
- Apple GPU — Single precision on the Apple GPU (macOS 15 or later); results can differ slightly. Falls back to Faster CPU without a GPU.
- Checkpoint every (epochs)default —
Saves the training state this often and when training ends, so a stopped run can resume where it was. Automatic saves about every 30 seconds; 0 = off. Each save holds the weights and the optimizer's state, so a large text encoder tuned on every layer can take 1–2 GB per fold.
What it reports
- policy_value
- Learns a decision policy from logged episodes only, without trying new actions; it can only be trusted where the logs tried them.
- policy_ci_low
- Learns a decision policy from logged episodes only, without trying new actions; it can only be trusted where the logs tried them.
- policy_ci_high
- Learns a decision policy from logged episodes only, without trying new actions; it can only be trusted where the logs tried them.
- 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.
- agreement
- Learns to copy the logged actions from the states (here a multinomial logistic regression): a baseline every learned policy should beat.
- low_support_share
- Share of logged states where the learned policy picks an action the logging policy rarely took (estimated probability under 5%).
- 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.
- iterations_run
- Repeats a regression of reward plus the best next value until the Q-model settles; the policy picks the action with the highest Q.
- final_loss
- Repeats a regression of reward plus the best next value until the Q-model settles; the policy picks the action with the highest Q.
- n_states
- One row per distinct state seen in the logs with the learned action and each action's Q-value (or probability for behavior cloning).
- algorithm
- Learns a decision policy from logged episodes only, without trying new actions; it can only be trusted where the logs tried them.
Per group, level or term: policy_value_wdr, policy_wdr_ci_low, policy_wdr_ci_high, ess, bc_value, weight_ess, weight_capped
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, pandas, torch, codesplash; R uses stats, nanoparquet, torch, codesplashr.
Default traps between the two languages
- Fitted Q iteration, behavior cloning (Newton–Raphson) and fitted Q evaluation solve the same normal equations with LAPACK in both engines (agreement near 1e-12).
- CQL and IQL train the same networks on the written-out Adam from shared initial weights and batch order; R's and Python's torch ship different LibTorch builds, so single kernels can differ by an ulp and values agree to about 1e-7.
The exact script CodeSplash ran for example “Corridor fqi tabular” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Offline policy learning from logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.offline_rl 1.1.0 · spec 10dbaa8e2b656318
# 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", "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"
done_col = "done"
features = ["cell", "weather today"]
algorithm = "fqi" # fqi | bc | cql | iql
gamma = float(0.95)
iterations = int(300)
rounds = int(20)
hidden = [int(u) for u in [32, 32]]
epochs = int(20)
lr = float(0.005)
batch_size = 256
alpha = float(1)
double = True
dueling = False
expectile = float(0.7)
temperature = float(3)
folds = int(2)
fqe_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]
K = len(levels)
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)
propensity = df[p_col].to_numpy(dtype=float) if p_col else None
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"])
if propensity is not None:
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"])
present = len(set(action.tolist()))
if present < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=a_col, min=2, k=present)
col_of = {lv: j for j, lv in enumerate(levels)}
a_idx = np.array([col_of[a] for a in action], dtype=np.int64)
x = ope.design(df, numeric, categorical)
starts = st["starts"]
fit_rows = st["fit_rows"]
# %% Learn
q_all = None
probs_all = None
bc = seq.behavior_cloning(x, a_idx, K)
bc_policy = np.argmax(bc["probs"], axis=1)
extra = {}
if algorithm == "fqi":
beta, support, iters_run, converged, trace = seq.fitted_q(x, a_idx, reward, st["next"], K, gamma, fit_rows, iterations, starts=starts)
q_all = seq.q_values(x, beta)
policy = seq.greedy(q_all, support)
if not converged:
warnings.append(f"Fitted Q iteration did not settle within {iterations} iterations; raise the limit or lower the discount.")
elif algorithm == "bc":
probs_all = bc["probs"]
policy = bc_policy
trace = bc["trace"]
iters_run, converged = bc["iterations"], bc["converged"]
if not converged:
warnings.append(f"Behavior cloning did not converge within {iters_run} Newton steps.")
else:
z = seq.nn_features(x, len(numeric))
if algorithm == "cql":
fit = orl.cql(z, a_idx, reward, st["next"], fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, alpha, double, dueling, seed, starts)
q_all = orl.q_numpy(orl.core.torch_init(), fit["params"], z, dueling, K)
policy = np.argmax(q_all, axis=1)
else:
fit = orl.iql(z, a_idx, reward, st["next"], fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, expectile, temperature, seed, starts)
q_all = orl.q_numpy(orl.core.torch_init(), fit["params"], z, False, K)
policy = np.argmax(orl.policy_logits(fit["policy_params"], z), axis=1)
extra = {"weight_ess": fit["weight_ess"], "weight_capped": fit["weight_capped"]}
if fit["weight_capped"] > 0.05:
warnings.append(f"{fit['weight_capped']:.0%} of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.")
trace = fit["trace"]
iters_run, converged = rounds, True
# %% Evaluate (FQE always; weighted doubly robust when propensities are given)
ev = seq.evaluate(st, x, a_idx, policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep)
ev_bc = seq.evaluate(st, x, a_idx, bc_policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep) if algorithm != "bc" else None
E, n = ev["E"], ev["n"]
agreement = float(np.mean(policy == a_idx))
low_support = float(np.mean(bc["probs"][np.arange(n), policy] < 0.05))
if st["truncated"]:
warnings.append(f"{st['truncated']} of {E} episodes end without {done_col} = true (cut short): their last step is left out of the Q-models because its next state is unknown.")
if low_support > 0.2:
warnings.append(f"At {low_support:.0%} of the logged states the learned policy picks an action the logging policy rarely took (estimated probability under 5%): its value there is extrapolated.")
if not ev["fqe_converged"]:
warnings.append(f"Fitted Q evaluation of the learned policy did not settle within {fqe_iterations} iterations.")
if propensity is not None and ev["ess"] < 0.1 * E:
warnings.append(f"Effective sample size {ev['ess']:.1f} of {E} episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.")
warnings.append("The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.")
# %% Result
alg_label = {"fqi": "Fitted Q iteration", "bc": "Behavior cloning", "cql": "Conservative Q-learning", "iql": "Implicit Q-learning"}[algorithm]
pct = f"{conf:.0%}"
v_fqe, (v_lo, v_hi) = ev["estimate"]["fqe"], ev["ci"]["fqe"]
logged = ev["logged"]
summary = (
f"{alg_label} learned a policy from {E:,} episodes ({n:,} decisions). Fitted Q evaluation puts its return per episode at {v_fqe:.3f}, "
f"{pct} CI [{v_lo:.3f}, {v_hi:.3f}], against {logged:.3f} for the logged policy (discount {gamma:g}). It agrees with the logged action at "
f"{agreement:.0%} of the logged states."
)
eval_rows = []
for name, res in [(alg_label, ev), ("Behavior cloning (baseline)", ev_bc)]:
if res is None:
continue
for e in [k for k in ("fqe", "wdr", "wpdis") if k in res["estimate"]]:
eval_rows.append({"policy": name, "estimator": seq.LABELS[e], "estimate": res["estimate"][e], "low": res["ci"][e][0], "high": res["ci"][e][1]})
eval_rows.append({"policy": "Logged policy", "estimator": "Observed return", "estimate": logged, "low": ev["logged_ci"][0], "high": ev["logged_ci"][1]})
values = {"policy_value": v_fqe, "policy_ci_low": v_lo, "policy_ci_high": v_hi, "logged_value": logged, "logged_ci_low": ev["logged_ci"][0],
"logged_ci_high": ev["logged_ci"][1], "agreement": agreement, "low_support_share": low_support, "n_episodes": E, "n_steps": n,
"iterations_run": iters_run, "final_loss": trace[-1]["loss"] if trace else None, "algorithm": algorithm}
if "wdr" in ev["estimate"]:
values.update({"policy_value_wdr": ev["estimate"]["wdr"], "policy_wdr_ci_low": ev["ci"]["wdr"][0], "policy_wdr_ci_high": ev["ci"]["wdr"][1], "ess": ev["ess"]})
if ev_bc is not None:
values["bc_value"] = ev_bc["estimate"]["fqe"]
values.update(extra)
# Policy table: one row per distinct state (first appearance).
first, n_states = seq.distinct_states(x)
values["n_states"] = n_states
pol_cols = [{"key": f"s{j + 1}", "label": c, "type": "string" if c in categorical else "number"} for j, c in enumerate(features)]
pol_cols.append({"key": "action", "label": "Learned action", "type": "string"})
score = q_all if q_all is not None else probs_all
score_label = "Q" if q_all is not None else "P"
for j, lv in enumerate(levels):
pol_cols.append({"key": f"v{j + 1}", "label": f"{score_label}({lv})", "type": "number"})
pol_rows = []
for i in first:
r = {f"s{j + 1}": (str(df[c].iloc[i]) if c in categorical else float(df[c].iloc[i])) for j, c in enumerate(features)}
r["action"] = levels[int(policy[i])]
for j in range(K):
r[f"v{j + 1}"] = float(score[i, j])
pol_rows.append(r)
share_rows = [{"action": lv, "logged": float(np.mean(a_idx == j)), "learned": float(np.mean(policy == j))} for j, lv in enumerate(levels)]
train_value = [t.get("value") for t in trace]
charts = [
cs.chart("evaluation", "forest", "Estimated return per episode", {
"label": cs.col("Policy and estimator", [f"{r['policy']} · {r['estimator']}" for r in eval_rows], levels=[f"{r['policy']} · {r['estimator']}" for r in eval_rows]),
"estimate": cs.col("Value", [r["estimate"] for r in eval_rows]),
"low": cs.col("Lower", [r["low"] for r in eval_rows]),
"high": cs.col("Upper", [r["high"] for r in eval_rows]),
}, controls={"reference": logged}),
cs.chart("actions", "share-compare", "Action shares: logged vs learned", {
"level": cs.col("Action", [r["action"] for r in share_rows] * 2, levels=levels),
"share": cs.col("Share", [r["logged"] for r in share_rows] + [r["learned"] for r in share_rows]),
"source": cs.col("Policy", ["Logged"] * K + ["Learned"] * K, levels=["Logged", "Learned"]),
}, question="How often does the learned policy choose each action, compared with the logged policy?"),
]
if all(v is not None for v in train_value) and train_value:
charts.insert(1, cs.chart("training", "return-curve", "Estimated start-state value by iteration", {
"x": cs.col("Iteration", [t["iteration"] for t in trace]),
"y": cs.col("Estimated value", train_value),
}, controls={"reference": logged}))
cs.publish({
"method": "decide.offline_rl",
"methodVersion": "1.1.0",
"title": f"Offline policy learning ({alg_label})",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": summary,
"statistics": [
{"key": "policy_value", "label": "Learned policy value (FQE)", "value": v_fqe},
{"key": "ci", "label": f"{pct} CI", "value": [v_lo, v_hi]},
{"key": "logged", "label": "Logged policy value", "value": logged},
{"key": "agreement", "label": "Agreement with logged actions", "value": agreement},
],
"tables": [
{"key": "evaluation", "title": "Estimated return per episode",
"columns": [{"key": "policy", "label": "Policy", "type": "string"}, {"key": "estimator", "label": "Estimator", "type": "string"},
{"key": "estimate", "label": "Estimate", "type": "number"}, {"key": "low", "label": f"{pct} CI low", "type": "number"},
{"key": "high", "label": f"{pct} CI high", "type": "number"}],
"rows": eval_rows},
{"key": "policy", "title": f"Learned policy by state ({min(n_states, 500)} of {n_states} distinct states)", "columns": pol_cols, "rows": pol_rows},
{"key": "actions", "title": "Actions: logged vs learned policy",
"columns": [{"key": "action", "label": a_col, "type": "string"}, {"key": "logged", "label": "Logged share", "type": "percent"},
{"key": "learned", "label": "Learned share", "type": "percent"}],
"rows": share_rows},
{"key": "training", "title": "Training by iteration",
"columns": [{"key": "iteration", "label": "Iteration", "type": "integer"}, {"key": "loss", "label": "Loss", "type": "number"},
{"key": "value", "label": "Estimated start-state value", "type": "number"}],
"rows": [{"iteration": t["iteration"], "loss": t["loss"], "value": t.get("value")} for t in trace]},
],
"warnings": warnings,
"notes": [
f"{alg_label}; discount {gamma:g}; Q-models and evaluation use {', '.join(features)}"
+ (f" (networks: hidden layers {', '.join(str(h) for h in hidden)}, {rounds} rounds × {epochs} epochs, learning rate {lr:g})" if algorithm in ("cql", "iql") else "")
+ f". Evaluation: fitted Q evaluation (linear per action, cross-fitted over {folds} episode folds)"
+ (", weighted doubly robust and weighted per-decision IS with the logged propensities" if propensity is not None else "")
+ f"; {n_boot} bootstrap resamples of episodes (seed {seed}). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.",
],
"values": values,
"charts": charts,
})
The exact script CodeSplash ran for example “Corridor fqi tabular” · R version 4.5.1 (2025-06-13)
# Offline policy learning from logged episodes
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method decide.offline_rl 1.1.0 · spec 10dbaa8e2b656318
# 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_*(), cs_orl_*(): twins of codesplash.decide.ope / sequential / offline_rl
# %% 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"
done_col <- "done"
features <- c("cell", "weather today")
algorithm <- "fqi" # fqi | bc | cql | iql
gamma <- as.numeric(0.95)
iterations <- as.integer(300)
rounds <- as.integer(20)
hidden <- as.integer(unlist(c(32, 32)))
epochs <- as.integer(20)
lr <- as.numeric(0.005)
batch_size <- 256
alpha <- as.numeric(1)
double <- TRUE
dueling <- FALSE
expectile <- as.numeric(0.7)
temperature <- as.numeric(3)
folds <- as.integer(2)
fqe_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]])
K <- length(lv)
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]])
propensity <- if (!is.null(p_col)) as.numeric(df[[p_col]]) else NULL
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)
if (!is.null(propensity)) {
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)
present <- length(unique(action))
if (present < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = a_col, min = 2, k = present)
a_idx <- match(action, lv)
x <- cs_bandit_design(df, numeric_f, categorical_f)
starts <- st$starts
fit_rows <- st$fit_rows
# %% Learn
q_all <- NULL
probs_all <- NULL
bc <- cs_seq_behavior_cloning(x, a_idx, K)
bc_policy <- as.integer(apply(bc$probs, 1, which.max))
extra <- list()
if (algorithm == "fqi") {
fq <- cs_seq_fitted_q(x, a_idx, reward, st$nxt, K, gamma, fit_rows, iterations, starts = starts)
q_all <- x %*% t(fq$beta)
policy <- cs_seq_greedy(q_all, fq$support)
trace <- fq$trace
iters_run <- fq$iterations
if (!fq$converged) warnings <- c(warnings, sprintf("Fitted Q iteration did not settle within %d iterations; raise the limit or lower the discount.", iterations))
} else if (algorithm == "bc") {
probs_all <- bc$probs
policy <- bc_policy
trace <- bc$trace
iters_run <- bc$iterations
if (!bc$converged) warnings <- c(warnings, sprintf("Behavior cloning did not converge within %d Newton steps.", iters_run))
} else {
z <- cs_seq_nn_features(x, length(numeric_f))
if (algorithm == "cql") {
fit <- cs_orl_cql(z, a_idx, reward, st$nxt, fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, alpha, double, dueling, seed, starts)
q_all <- cs_orl_q_values(fit$params, z, dueling, K)
policy <- as.integer(apply(q_all, 1, which.max))
} else {
fit <- cs_orl_iql(z, a_idx, reward, st$nxt, fit_rows, K, gamma, hidden, rounds, epochs, lr, batch_size, expectile, temperature, seed, starts)
q_all <- cs_orl_q_values(fit$params, z, FALSE, K)
policy <- as.integer(apply(cs_orl_policy_logits(fit$policy_params, z), 1, which.max))
extra <- list(weight_ess = fit$weight_ess, weight_capped = fit$weight_capped)
if (fit$weight_capped > 0.05) {
warnings <- c(warnings, sprintf("%.0f%% of the advantage weights hit the cap of 100: lower the temperature, or the policy imitates a few rows.", fit$weight_capped * 100))
}
}
trace <- fit$trace
iters_run <- rounds
}
# %% Evaluate (FQE always; weighted doubly robust when propensities are given)
ev <- cs_seq_evaluate(st, x, a_idx, policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep)
ev_bc <- if (algorithm != "bc") cs_seq_evaluate(st, x, a_idx, bc_policy, reward, propensity, K, gamma, folds, fqe_iterations, n_boot, conf, seed, ep) else NULL
E <- ev$E
n <- ev$n
agreement <- mean(policy == a_idx)
low_support <- mean(bc$probs[cbind(seq_len(n), policy)] < 0.05)
if (st$truncated > 0) {
warnings <- c(warnings, sprintf("%d of %d episodes end without %s = true (cut short): their last step is left out of the Q-models because its next state is unknown.", st$truncated, E, done_col))
}
if (low_support > 0.2) {
warnings <- c(warnings, sprintf("At %.0f%% of the logged states the learned policy picks an action the logging policy rarely took (estimated probability under 5%%): its value there is extrapolated.", low_support * 100))
}
if (!ev$fqe_converged) warnings <- c(warnings, sprintf("Fitted Q evaluation of the learned policy did not settle within %d iterations.", fqe_iterations))
if (!is.null(propensity) && ev$ess < 0.1 * E) {
warnings <- c(warnings, sprintf("Effective sample size %.1f of %d episodes for the learned policy: the weighted doubly robust estimate leans on the Q-model.", ev$ess, E))
}
warnings <- c(warnings, "The policy was learned and evaluated on the same episodes, so its estimated value is optimistic; check it on new episodes or in a simulated environment before acting on it.")
# %% Result
alg_label <- c(fqi = "Fitted Q iteration", bc = "Behavior cloning", cql = "Conservative Q-learning", iql = "Implicit Q-learning")[[algorithm]]
pct <- sprintf("%.0f%%", conf * 100)
v_fqe <- ev$estimate$fqe
v_ci <- ev$ci$fqe
logged <- ev$logged
gfmt <- format(gamma, digits = 6)
summary <- sprintf(
"%s learned a policy from %s episodes (%s decisions). Fitted Q evaluation puts its return per episode at %.3f, %s CI [%.3f, %.3f], against %.3f for the logged policy (discount %s). It agrees with the logged action at %.0f%% of the logged states.",
alg_label, format(E, big.mark = ","), format(n, big.mark = ","), v_fqe, pct, v_ci[1], v_ci[2], logged, gfmt, agreement * 100
)
lab <- cs_seq_labels()
eval_rows <- list()
for (pair in list(list(alg_label, ev), list("Behavior cloning (baseline)", ev_bc))) {
res <- pair[[2]]
if (is.null(res)) next
for (e in intersect(c("fqe", "wdr", "wpdis"), names(res$estimate))) {
eval_rows[[length(eval_rows) + 1L]] <- data.frame(policy = pair[[1]], estimator = lab[[e]], estimate = res$estimate[[e]],
low = res$ci[[e]][1], high = res$ci[[e]][2])
}
}
eval_rows[[length(eval_rows) + 1L]] <- data.frame(policy = "Logged policy", estimator = "Observed return", estimate = logged,
low = ev$logged_ci[1], high = ev$logged_ci[2])
eval_df <- do.call(rbind, eval_rows)
values <- list(policy_value = v_fqe, policy_ci_low = v_ci[1], policy_ci_high = v_ci[2], logged_value = logged,
logged_ci_low = ev$logged_ci[1], logged_ci_high = ev$logged_ci[2], agreement = agreement, low_support_share = low_support,
n_episodes = E, n_steps = n, iterations_run = iters_run, final_loss = if (length(trace)) trace[[length(trace)]]$loss else NULL,
algorithm = algorithm)
if ("wdr" %in% names(ev$estimate)) {
values$policy_value_wdr <- ev$estimate$wdr
values$policy_wdr_ci_low <- ev$ci$wdr[1]
values$policy_wdr_ci_high <- ev$ci$wdr[2]
values$ess <- ev$ess
}
if (!is.null(ev_bc)) values$bc_value <- ev_bc$estimate$fqe
values <- c(values, extra)
# Policy table: one row per distinct state (first appearance).
ds <- cs_seq_distinct_states(x)
values$n_states <- ds$count
score <- if (!is.null(q_all)) q_all else probs_all
score_label <- if (!is.null(q_all)) "Q" else "P"
pol_cols <- lapply(seq_along(features), function(j) list(key = sprintf("s%d", j), label = features[j], type = if (is_cat[j]) "string" else "number"))
pol_cols[[length(pol_cols) + 1L]] <- list(key = "action", label = "Learned action", type = "string")
for (j in seq_len(K)) pol_cols[[length(pol_cols) + 1L]] <- list(key = sprintf("v%d", j), label = sprintf("%s(%s)", score_label, lv[j]), type = "number")
pol_df <- data.frame(row.names = seq_along(ds$rows))
for (j in seq_along(features)) {
c <- features[j]
pol_df[[sprintf("s%d", j)]] <- if (is_cat[j]) as.character(df[[c]][ds$rows]) else as.numeric(df[[c]][ds$rows])
}
pol_df$action <- lv[policy[ds$rows]]
for (j in seq_len(K)) pol_df[[sprintf("v%d", j)]] <- as.numeric(score[ds$rows, j])
rownames(pol_df) <- NULL
share_df <- data.frame(action = lv, logged = vapply(seq_len(K), function(j) mean(a_idx == j), numeric(1)),
learned = vapply(seq_len(K), function(j) mean(policy == j), numeric(1)))
train_value <- lapply(trace, function(t) t$value)
train_df <- data.frame(iteration = vapply(trace, function(t) as.integer(t$iteration), integer(1)),
loss = vapply(trace, function(t) as.numeric(t$loss), numeric(1)))
train_df$value <- if (length(trace) && !any(vapply(train_value, is.null, logical(1)))) unlist(train_value) else rep(NA_real_, nrow(train_df))
eval_labels <- paste(eval_df$policy, eval_df$estimator, sep = " · ")
charts <- list(
cs_chart("evaluation", "forest", "Estimated return per episode", list(
label = cs_col("Policy and estimator", eval_labels, levels = eval_labels),
estimate = cs_col("Value", eval_df$estimate),
low = cs_col("Lower", eval_df$low),
high = cs_col("Upper", eval_df$high)
), controls = list(reference = logged)),
cs_chart("actions", "share-compare", "Action shares: logged vs learned", list(
level = cs_col("Action", c(share_df$action, share_df$action), levels = lv),
share = cs_col("Share", c(share_df$logged, share_df$learned)),
source = cs_col("Policy", c(rep("Logged", K), rep("Learned", K)), levels = c("Logged", "Learned"))
), question = "How often does the learned policy choose each action, compared with the logged policy?")
)
if (length(trace) && !any(vapply(train_value, is.null, logical(1)))) {
charts <- append(charts, list(cs_chart("training", "return-curve", "Estimated start-state value by iteration", list(
x = cs_col("Iteration", train_df$iteration),
y = cs_col("Estimated value", train_df$value)
), controls = list(reference = logged))), after = 1L)
}
net_note <- if (algorithm %in% c("cql", "iql")) {
sprintf(" (networks: hidden layers %s, %d rounds × %d epochs, learning rate %s)", paste(hidden, collapse = ", "), rounds, epochs, format(lr, digits = 6))
} else ""
cs_publish(list(
method = "decide.offline_rl",
methodVersion = "1.1.0",
title = sprintf("Offline policy learning (%s)", alg_label),
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = summary,
statistics = list(
list(key = "policy_value", label = "Learned policy value (FQE)", value = v_fqe),
list(key = "ci", label = paste(pct, "CI"), value = v_ci),
list(key = "logged", label = "Logged policy value", value = logged),
list(key = "agreement", label = "Agreement with logged actions", value = agreement)
),
tables = list(
list(key = "evaluation", title = "Estimated return per episode",
columns = list(list(key = "policy", label = "Policy", type = "string"), list(key = "estimator", label = "Estimator", type = "string"),
list(key = "estimate", label = "Estimate", type = "number"), list(key = "low", label = paste(pct, "CI low"), type = "number"),
list(key = "high", label = paste(pct, "CI high"), type = "number")),
rows = eval_df),
list(key = "policy", title = sprintf("Learned policy by state (%d of %d distinct states)", min(ds$count, 500L), ds$count), columns = pol_cols, rows = pol_df),
list(key = "actions", title = "Actions: logged vs learned policy",
columns = list(list(key = "action", label = a_col, type = "string"), list(key = "logged", label = "Logged share", type = "percent"),
list(key = "learned", label = "Learned share", type = "percent")),
rows = share_df),
list(key = "training", title = "Training by iteration",
columns = list(list(key = "iteration", label = "Iteration", type = "integer"), list(key = "loss", label = "Loss", type = "number"),
list(key = "value", label = "Estimated start-state value", type = "number")),
rows = train_df)
),
warnings = warnings,
notes = list(paste0(alg_label, "; discount ", gfmt, "; Q-models and evaluation use ", paste(features, collapse = ", "), net_note,
sprintf(". Evaluation: fitted Q evaluation (linear per action, cross-fitted over %d episode folds)", folds),
if (!is.null(propensity)) ", weighted doubly robust and weighted per-decision IS with the logged propensities" else "",
sprintf("; %d bootstrap resamples of episodes (seed %s). The behavior-cloning baseline is a multinomial logistic regression of the logged action on the state.", n_boot, seed))),
values = values,
charts = charts
))
Sources
- Ernst, D., Geurts, P., & Wehenkel, L. (2005). Tree-based batch mode reinforcement learning. JMLR, 6, 503–556.
- Kumar, A., Zhou, A., Tucker, G., & Levine, S. (2020). Conservative Q-learning for offline reinforcement learning. NeurIPS, 1179–1191.
- Kostrikov, I., Nair, A., & Levine, S. (2022). Offline reinforcement learning with implicit Q-learning. ICLR.
- van Hasselt, H., Guez, A., & Silver, D. (2016). Deep reinforcement learning with double Q-learning. AAAI, 2094–2100.
- Wang, Z., Schaul, T., Hessel, M., van Hasselt, H., Lanctot, M., & de Freitas, N. (2016). Dueling network architectures for deep reinforcement learning. ICML, 1995–2003.
- Levine, S., Kumar, A., Tucker, G., & Fu, J. (2020). Offline reinforcement learning: tutorial, review, and perspectives on open problems. arXiv:2005.01643.
From the CodeSplash method registry · decide.offline_rl v1.1.0.